一、导入1.导入matplotlib库简写为pltimportmatplotlib.pyplotasplt二、基本图表2.用plot方法画出x=(0,10)间sin的图像x=np.linspace(0,10,30)plt.plot(x,np.sin(x));3.用点加线的方式画出x=(0,10)间sin的图像plt.plot(x,np.sin(x),'-o');4.用scatter方法画出x=(0,10)间sin的点图像plt.scatter(x,np.sin(x));5.用饼图的面积及颜色展示一组4维数据rng=np.random.RandomState(0)x=rng.randn(100)y=rng.randn(100)colors=rng.rand(100)sizes=1000*rng.rand(100)plt.scatter(x,y,c=colors,s=sizes,alpha=0.3,cmap='viridis')plt.colorbar();#展示色阶6.绘制一组误差为±0.8的数据的误差条图x=np.linspace(0,10,50)dy=0.8y=np.sin(x)+dy*np.random.randn(50)plt.errorbar(x,y,yerr=dy,fmt='.k')7.绘制一个柱状图x=[1,2,3,4,5,6,7,8]y=[3,1,4,5,8,9,7,2]label=['A','B','C','D','E','F','G','H']plt.bar(x,y,tick_label=label);8.绘制一个水平方向柱状图plt.barh(x,y,tick_label=label);9.绘制1000个随机值的直方图data=np.random.randn(1000)plt.hist(data);10.设置直方图分30个bins,并设置为频率分布plt.hist(data,bins=30,histtype='stepfilled',density=True)plt.show();11.在一张图中绘制3组不同的直方图,并设置透明度x1=np.random.normal(0,0.8,1000)x2=np.random.normal(-2,1,1000)x3=np.random.normal(3,2,1000)kwargs=dict(alpha=0.3,bins=40,density=True)plt.hist(x1,**kwargs);plt.hist(x2,**kwargs);plt.hist(x3,**kwargs);12.绘制一张二维直方图mean=[0,0]cov=[[1,1],[1,2]]x,y=np.random.multivariate_normal(mean,cov,10000).Tplt.hist2d(x,y,bins=30);13.绘制一张设置网格大小为30的六角形直方图plt.hexbin(x,y,gridsize=30);三、自定义图表元素14.绘制x=(0,10)间sin的图像,设置线性为虚线x=np.linspace(0,10,100)plt.plot(x,np.sin(x),'--');15设置y轴显示范围为(-1.5,1.5)x=np.linspace(0,10,100)plt.plot(x,np.sin(x))plt.ylim(-1.5,1.5);16.设置x,y轴标签variablex,valueyx=np.linspace(0.05,10,100)y=np.sin(x)plt.plot(x,y,label='sin(x)')plt.xlabel('variablex');plt.ylabel('valuey');17.设置图表标题“三角函数”x=np.linspace(0.05,10,100)y=np.sin(x)plt.plot(x,y,label='sin(x)')plt.title('三角函数');18.显示网格x=np.linspace(0.05,10,100)y=np.sin(x)plt.plot(x,y)plt.grid()19.绘制平行于x轴y=0.8的水平参考线x=np.linspace(0.05,10,100)y=np.sin(x)plt.plot(x,y)plt.axhline(y=0.8,ls='--',c='r')20.绘制垂直于x轴x4andx6的参考区域,以及y轴y0.2andy-0.2的参考区域x=np.linspace(0.05,10,100)y=np.sin(x)plt.plot(x,y)plt.axvspan(xmin=4,xmax=6,facecolor='r',alpha=0.3)#垂直x轴plt.axhspan(ymin=-0.2,ymax=0.2,facecolor='y',alpha=0.3);#垂直y轴21.添加注释文字sin(x)x=np.linspace(0.05,10,100)y=np.sin(x)plt.plot(x,y)plt.text(3.2,0,'sin(x)',weight='bold',color='r');22.用箭头标出第一个峰值x=np.linspace(0.05,10,100)y=np.sin(x)plt.plot(x,y)plt.annotate('maximum',xy=(np.pi/2,1),xytext=(np.pi/2+1,1),weight='bold',color='r',arrowprops=dict(arrowstyle='-',connectionstyle='arc3',color='r'));四、自定义图例23.在一张图里绘制sin,cos的图形,并展示图例x=np.linspace(0,10,1000)fig,ax=plt.subplots()ax.plot(x,np.sin(x),label='sin')ax.plot(x,np.cos(x),'--',label='cos')ax.legend();24.调整图例在左上角展示,且不显示边框ax.legend(loc='upperleft',frameon=False);fig25.调整图例在画面下方居中展示,且分成2列ax.legend(frameon=False,loc='lowercenter',ncol=2)fig26.绘制的图像,并只显示前2者的图例y=np.sin(x[:,np.newaxis]+np.pi*np.arange(0,2,0.5))lines=plt.plot(x,y)#lines是plt.Line2D类型的实例的列表plt.legend(lines[:2],['first','second']);#第二个方法#plt.plot(x,y[:,0],label='first')#plt.plot(x,y[:,1],label='second')#plt.plot(x,y[:,2:])#plt.legend(framealpha=1,frameon=True);27.将图例分不同的区域展示fig,ax=plt.subplots()lines=[]styles=['-','--','-.',':']x=np.linspace(0,10,1000)foriinrange(4):lines+=ax.plot(x,np.sin(x-i*np.pi/2),styles[i],color='black')ax.axis('equal')#设置第一组标签ax.legend(lines[:2],['lineA','lineB'],loc='upperright',frameon=False)#创建第二组标签frommatplotlib.legendimportLegendleg=Legend(ax,lines[2:],['lineC','lineD'],loc='lowerright',frameon=False)ax.add_artist(leg);五、自定义色阶28.展示色阶x=np.linspace(0,10,1000)I=np.sin(x)*np.cos(x[:,np.newaxis])plt.imshow(I)plt.colorbar();29.改变配色为'gray'plt.imshow(I,cmap='gray');30.将色阶分成6个离散值显示plt.imshow(I,cmap=plt.cm.get_cmap('Blues',6))plt.colorbar()plt.clim(-1,1);六、多子图31.在一个1010的画布中,(0.65,0.65)的位置创建一个0.20.2的子图ax1=plt.axes()ax2=plt.axes([0.65,0.65,0.2,0.2])32.在2个子图中,显示sin(x)和cos(x)的图像fig=plt.figure()ax1=fig.add_axes([0.1,0.5,0.8,0.4],ylim=(-1.2,1.2))ax2=fig.add_axes([0.1,0.1,0.8,0.4],ylim=(-1.2,1.2))x=np.linspace(0,10)ax1.plot(np.sin(x));ax2.plot(np.cos(x));33.用for创建6个子图,并且在图中标识出对应的子图坐标foriinrange(1,7):plt.subplot(2,3,i)plt.text(0.5,0.5,str((2,3,i)),fontsize=18,ha='center')#方法二#fig=plt.figure()#fig.subplots_adjust(hspace=0.4,wspace=0.4)#foriinrange(1,7):#ax=fig.add_subplot(2,3,i)#ax.text(0.5,0.5,str((2,3,i)),fontsize=18,ha='center')34.设置相同行和列共享x,y轴fig,ax=plt.subplots(2,3,sharex='col',sharey='row')35.用[]的方式取出每个子图,并添加子图座标文字foriinrange(2):forjinrange(3):ax[i,j].text(0.5,0.5,str((i,j)),fontsize=18,ha='center')fig36.组合绘制大小不同的子图,样式如下ImageNamegrid=plt.GridSpec(2,3,wspace=0.4,hspace=0.3)plt.subplot(grid[0,0])plt.subplot(grid[0,1:])plt.subplot(grid[1,:2])plt.subplot(grid[1,2]);37.显示一组二维数据的频度分布,并分别在x,y轴上,显示该维度的数据的频度分布mean=[0,0]cov=[[1,1],[1,2]]x,y=np.random.multivariate_normal(mean,cov,3000).T#Setuptheaxeswithgridspecfig=plt.figure(figsize=(6,6))grid=plt.GridSpec(4,4,hspace=0.2,wspace=0.2)main_ax=fig.add_subplot(grid[:-1,1:])y_hist=fig.add_subplot(grid[:-1,0],xticklabels=[],sharey=main_ax)x_hist=fig.add_subplot(grid[-1,1:],yticklabels=[],sharex=main_ax)#scatterpointsonthemainaxesmain_ax.scatter(x,y,s=3,alpha=0.2)#histogramontheattachedaxesx_hist.hist(x,40,histtype='st