300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > python中利用matplotlib画图

python中利用matplotlib画图

时间:2023-04-02 05:34:08

相关推荐

python中利用matplotlib画图

介绍三种比较简单的方法

基于matplotlib的画图方式

plt.plot(),常用款

plt.hist(), 画直方图

plt.pie(),画饼状图

plt.figure()基于pandas的画图

s.plot()s是pandas的Series对象

df.plot()df是pandas的DataFrame对象

1.1.plt.plot()#绘制y关于x的变化关系.

x,y是成对出现的。可以省略x,则y是关于y的个数的函数关系。

当y是Series或DataFrame对象对象时,不出现x

[fmt]]可以设置线性,颜色,样式等。

Plot y versus x as lines and/or markers

plot([x], y, [fmt], data=None, **kwargs)

plot([x], y, [fmt], [x2], y2, [fmt2], …, **kwargs)

以一个比较简单的例子入手:

import numpy as npfrom matplotlib import pyplot as plt%matplotlib inlinex = np.arange(-10,11)y = x**2plt.plot(x,y)

增加一些功能

设置标题、坐标轴标签、轴边界、轴刻度、显示中文及正负号

import numpy as npfrom matplotlib import pyplot as plt%matplotlib inlinex = np.arange(-10,11)y = x**2plt.plot(x,y)#添加标题plt.title('二次函数')#设置x,y轴标签plt.xlabel('x')plt.ylabel('y')#设置x,y轴边界plt.xlim([-12,12])plt.ylim([-10,110])#设置x,y轴刻度plt.xticks([i for i in range(-10,11)])plt.yticks([i for i in range(-10,101,10)])plt.rcParams['font.sans-serif']=['SimHei'] #显示中文plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

增加图例

配合plot()中的label参数,设置图例。loc设置图例的位置。color设置颜色,linestyle设置颜色,marker设置有值处点的形状。

x = np.arange(-10,11)y = x**2plt.plot(x,y,label='y=x^2',color = 'r',linestyle = ':',marker = 'o')plt.legend(loc = 'upper right')

plt.plot()的参数是Series对象

plt.plot()的参数是DataFrame对象。DataFrame对象画图时,使用df.plot()更好,图例显示的就是列名。

1.2plt.hist()画直方图

1.3.plt.pie()画饼状图 基于pandas

2.1s.plot()

s = pd.Series(np.random.randn(50).cumsum())s.plot(linestyle = '-.', marker = '_')

2.2df.plot()

通过df.plot(kind='line')画图,其中的kind参数可取‘line’,‘bar’,‘kde’(密度图),‘hist’,‘area’(面积图)等。返回对象axes

# 图名,图例,轴标签,轴边界,轴刻度,轴刻度标签等df = pd.DataFrame(np.random.rand(10,2),columns=['A','B'])fig = df.plot(figsize=(6,4))# figsize:创建图表窗口,设置窗口大小# 创建图表对象,并赋值与figplt.title('Interesting Graph - Check it out') # 图名plt.xlabel('Plot Number') # x轴标签plt.ylabel('Important var') # y轴标签plt.legend(loc = 'best') plt.xlim([0,12]) # x轴边界plt.ylim([0,1.5]) # y轴边界plt.xticks(range(11)) # 设置x刻度plt.yticks([0,0.2,0.4,0.6,0.8,1.0,1.2]) # 设置y刻度# fig.set_xticklabels("%.1f" %i for i in range(10)) # x轴刻度标签# 周刻度另命名fig.set_xticklabels("%c" %i for i in list('abcdegfhij')) # x轴刻度标签fig.set_yticklabels("%.2f" %i for i in [0,0.2,0.4,0.6,0.8,1.0,1.2]) # y轴刻度标签

保存图像plt.savefig('a.png')创建子图

3.1 子图创建1 - 先建立子图然后填充图表

在子图中添加标题

ax1.title.set_text('First Plot')

# 子图创建1 - 先建立子图然后填充图表fig = plt.figure(figsize=(10,6),facecolor = 'gray')ax1 = fig.add_subplot(2,2,1) # 第一行的左图ax1.plot(np.random.rand(50).cumsum(),'r--')ax1.plot(np.random.randn(50).cumsum(),'b--')ax1.title.set_text('cumsum -- line')ax2 = fig.add_subplot(2,2,2) # 第一行的右图ax2.hist(np.random.rand(50),alpha=0.5)ax2.title.set_text('hist')ax4 = fig.add_subplot(2,2,4) # 第二行的右图df2 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])ax4.plot(df2,alpha=0.5,linestyle='--',marker='.')ax2.title.set_text('mess')plt.show()# 也可以直接在子图后用图表创建函数直接生成图表

3.2 创建一个新的figure,并返回一个subplot对象的numpy数组 → plt.subplot

# 子图创建2 - 创建一个新的figure,并返回一个subplot对象的numpy数组 → plt.subplotfig,axes = plt.subplots(2,3,figsize=(10,4))ts = pd.Series(np.random.randn(1000).cumsum())ts2 = pd.Series(np.random.randint(100,size=100))print(axes, axes.shape, type(axes))# 生成图表对象的数组ax1 = axes[0,1]ax1.plot(ts)ax2 = axes[0,2]ax2.plot(ts2)

参数调整

# plt.subplots,参数调整fig, axis = plt.subplots(4,4,figsize=(12,10))# 设置子图是4*4,图大小的12*10fig.suptitle('Histogram')# 添加总标题# sharex=True,sharey=True。sharex,sharey:是否共享x,y刻度for i in range(4):for j in range(4):num = i*4+j+1axis[i][j].hist(df_x['f'+str(num)])# 画出f1~f13axis[i][j].set_title('f%d' % num)# 设置子图的标题if num>=13:breakplt.subplots_adjust(wspace=0.3,hspace=0.3)# wspace,hspace:用于控制宽度和高度的百分比,比如subplot之间的间距

colorbar配合inshow使用

import numpy as npfrom matplotlib import pyplot as pltm = np.linspace(-100,100,50)n = np.linspace(-100,100,50)x,y = np.meshgrid(m,n)z = x**2 + y**2plt.imshow(z,cmap='spring')plt.colorbar(shrink=0.8)# 颜色条占图高的比例plt.show()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。