Matplotlib 学习笔记
基本用法
import matplotlib.pyplot as pltimport numpy as npx = np.linspace(-1,1,50)y = 2*x + 1plt.plot(x,y)plt.show()
figure 图像
import matplotlib.pyplot as pltimport numpy as npx = np.linspace(-1,1,50)y1 = 2*x + 1y2 = x**2plt.figure() #这一张图的开头,下面的参数都调整这一张图plt.plot(x, y1)plt.figure()#这个地方可以给参数以定义figure的序号 ,也可以定义大小。#plt.figure(num=3,figsize=(8,5))plt.plot(x, y2)plt.plot(x,y1,color=\'red\',linewidth=1.0,linestyle=\'--\')plt.show()
设置坐标轴
import matplotlib.pyplot as pltimport numpy as npx = np.linspace(-1,1,50)y1 = 2*x + 1y2 = x**2plt.figure()plt.plot(x, y2)plt.plot(x,y1,color=\'red\',linewidth=1.0,linestyle=\'--\')#设置坐标轴的范围plt.xlim((-1,2))plt.ylim((-2,3))#设置坐标轴的labelplt.xlabel((\'I am x\'))plt.ylabel((\'I am y\'))#设置坐标轴的ticksnew_ticks = np.linspace(-1,2,5)plt.xticks(new_ticks)# 修改字体可以通过机器可读的符号,如前后加上$#反斜杠加一些命令可以生产数学符号 如: \\alphaplt.yticks([-2,-1.8,-1,1.2, 3],[r\'$really\\ bad$\', r\'$bad\\ \\alpha$\', r\'$normal$\', r\'$good$\', r\'$really\\ good$\'])# gca = \'get current axis\'ax = plt.gca()ax.spines[\'right\'].set_color(\'none\') # 图片的框线ax.spines[\'top\'].set_color(\'none\')ax.xaxis.set_ticks_position(\'bottom\')ax.yaxis.set_ticks_position(\'left\')ax.spines[\'bottom\'].set_position((\'data\',0)) #横坐标的位置就是纵坐标的0ax.spines[\'left\'].set_position((\'data\',0))#其中的\'data\'还可以换成 outward,axes(相对于另一个轴百分之多少的位置)plt.show()
legend 图例
import matplotlib.pyplot as pltimport numpy as npx = np.linspace(-1,1,50)y1 = 2*x + 1y2 = x**2plt.figure()#设置坐标轴的labelplt.xlabel((\'I am x\'))plt.ylabel((\'I am y\'))#设置坐标轴的ticksnew_ticks = np.linspace(-1,2,5)plt.xticks(new_ticks)plt.yticks([-2,-1.8,-1,1.2, 3],[r\'$really\\ bad$\', r\'$bad\\ \\alpha$\', r\'$normal$\', r\'$good$\', r\'$really\\ good$\'])#通过label参数可以调整线的名字l1, = plt.plot(x, y2,label=\'up\') #这行代码其实是有返回值的,设为l1, 注意一定要加逗号!l2, = plt.plot(x,y1,color=\'red\',linewidth=1.0,linestyle=\'--\',label=\'down\')# legend可以设定参数handles(),labels(给一个不同的名字),loc=\'best\'/\'upper right\'/\'lower right\'plt.legend(handles=[l1,l2,],labels=[\'aaa\',\'bbb\'],loc=\'best\')plt.show()
Annotation标注
import matplotlib.pyplot as pltimport numpy as npx = np.linspace(-3,3,50)y = 2*x + 1plt.figure(num=1,figsize=(8,5))plt.plot(x,y)# gca = \'get current axis\'ax = plt.gca()ax.spines[\'right\'].set_color(\'none\') # 图片的框线ax.spines[\'top\'].set_color(\'none\')ax.xaxis.set_ticks_position(\'bottom\')ax.yaxis.set_ticks_position(\'left\')ax.spines[\'bottom\'].set_position((\'data\',0))ax.spines[\'left\'].set_position((\'data\',0))x0 = 1y0 = 2*x0 + 1plt.scatter(x0, y0,s=50,color=\'b\')plt.plot([x0,x0],[y0,0],\'k--\',lw=1.0) #k代表黑色,形状是虚线# method 1###############plt.annotate(r\'$2x+1=%s$\'% y0,xy=(x0,y0),xycoords=\'data\',xytext=(+30,-30),textcoords=\'offset points\',fontsize=16,arrowprops=dict(arrowstyle=\'->\',connectionstyle=\'arc3, rad=0.2\'))# xy是坐标,表示在什么点上打印;xycoords表示以data的值作为基准;xytext表示基于数据的点横坐标加上30纵坐标-30打印;arrowprops展示箭头# method 2###############plt.text(-3.7,3,r\'$This\\ is\\ some\\ text.\\ \\mu\\ \\sigma_i\\ \\alpha_t $\',fontdict={\'size\':16,\'color\':\'r\'})plt.show()
axis tick透明度设置
import matplotlib.pyplot as pltimport numpy as npx = np.linspace(-3,3,50)y = 2*x + 1plt.figure(num=1,figsize=(8,5))plt.plot(x,y,linewidth=10)# gca = \'get current axis\'ax = plt.gca()ax.spines[\'right\'].set_color(\'none\') # 图片的框线ax.spines[\'top\'].set_color(\'none\')ax.xaxis.set_ticks_position(\'bottom\')ax.yaxis.set_ticks_position(\'left\')ax.spines[\'bottom\'].set_position((\'data\',0))ax.spines[\'left\'].set_position((\'data\',0))for label in ax.get_xticklabels() + ax.get_yticklabels():label.set_fontsize(12)label.set_bbox(dict(facecolor=\'white\', edgecolor=\'None\',alpha=0.7))plt.show()
绘制散点图
import matplotlib.pyplot as pltimport numpy as npn = 1024X = np.random.normal(0,1,n)Y = np.random.normal(0,1,n)T = np.arctan2(Y,X) # for color valueplt.scatter(X,Y,s=75,c=T,alpha=0.5)plt.xlim((-1.5,1.5))plt.ylim((-1.5,1.5))plt.xticks(())plt.yticks(())plt.show()
绘制柱状图
import matplotlib.pyplot as pltimport numpy as npn = 12X = np.arange(n)Y1 = (1 - X/float(n)*np.random.uniform(0.5,1.0,n))Y2 = (1 - X/float(n)*np.random.uniform(0.5,1.0,n))plt.bar(X,+Y1,facecolor=\'#9999ff\',edgecolor=\'white\')plt.bar(X,-Y2,facecolor=\'#ff9999\',edgecolor=\'white\')# zip:可以把X和Y1打包起来分别给x和yfor x,y in zip(X,Y1):# ha: horizontal alignmentplt.text(x+0.4,y+0.05,\'%.2f\' % y,ha=\'center\',va=\'bottom\') # 定义了位置for x,y in zip(X,Y2):# ha: horizontal alignmentplt.text(x+0.4,-y-0.05,\'-%.2f\' % y,ha=\'center\',va=\'top\') # 定义了位置plt.xlim(-.5,n)plt.xticks(())plt.ylim(-1.25,1.25)plt.show()
绘制等高线图
import matplotlib.pyplot as pltimport numpy as npdef f(x,y):return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)n=256x = np.linspace(-3,3,n)y = np.linspace(-3,3,n)X, Y = np.meshgrid(x,y)# 填充等高线的颜色,8 代表用几条线来作划分plt.contourf(X,Y,f(X,Y),8,alpha=0.75,cmap=plt.cm.hot) ## 填充等高线的线C = plt.contour(X,Y,f(X,Y),8,colors=\'black\',linewidth=.5)# 加上数字描述,clabel=contour label,inline表示数字是否会穿过线plt.clabel(C,inline=True,fontsize=10)plt.xticks(())plt.yticks(())plt.show()
绘制3D图
import matplotlib.pyplot as pltimport numpy as npfrom mpl_toolkits.mplot3d import Axes3Dfig = plt.figure()ax = Axes3D(fig)X = np.arange(-4,4,0.25)Y = np.arange(-4,4,0.25)X,Y = np.meshgrid(X,Y)R = np.sqrt(X**2 + Y**2)Z = np.sin(R)#stride表示跨度ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=plt.get_cmap(\'rainbow\'))ax.contourf(X,Y,Z,zidr=\'Z\',offset=-2,cmap=\'rainbow\')ax.set_zlim(-2,2)plt.show()
Subplot 分格显示
第一种方法
import matplotlib.pyplot as pltimport numpy as npimport matplotlib.gridspec as gridspec# method1:subplotgrid################################plt.figure()# (3,3),(0,0) 设置索引,表示0行0列开始ax1 = plt.subplot2grid((3,3),(0,0),colspan=3,rowspan=1) #cspan表示列跨度,即有3列,1行.ax1.plot([1,2],[1,2])#在不是子图的情况下,之前用的 plt.xlabel() plt.title(),现在需要ax1.set_xlabel() ax1.set_lim()ax1.set_title(\'ax1_title\')ax2 = plt.subplot2grid((3,3),(1,0),colspan=2,rowspan=1)ax3 = plt.subplot2grid((3,3),(1,2),colspan=2,rowspan=2)ax4 = plt.subplot2grid((3,3),(2,0))ax5 = plt.subplot2grid((3,3),(2,1))plt.show()
第二种方法
第三种方法
import matplotlib.pyplot as pltf, ((ax11,ax12),(ax21,ax22)) = plt.subplots(2,2,sharex=True,sharey=True)plt.tight_layout()plt.show()
次坐标轴
import matplotlib.pyplot as pltimport numpy as npx = np.arange(0,10,0.1)y1 = 0.05*x**2y2 = -1* y1fig, ax1 = plt.subplots()ax2 = ax1.twinx() #将ax1对称反转ax1.plot(x,y1,\'g-\')ax2.plot(x,y2,\'b--\')ax1.set_xlabel(\'X data\')ax1.set_ylabel(\'Y1\',color=\'g\')ax2.set_ylabel(\'Y2\',color=\'b\')plt.show()
动画效果
import matplotlib.pyplot as pltimport numpy as npfrom matplotlib import animationfig,ax = plt.subplots()x = np.arange(0,2*np.pi,0.01)line, = ax.plot(x,np.sin(x))def animate(i):line.set_ydata(np.sin(x+i/100))return line,def init():line.set_ydata(np.sin(x))return line,ani = animation.FuncAnimation(fig=fig,func=animate,frames=100,init_func=init(),interval=20,blit=True) #frames表示100帧