Matplotlib是一个python的 2D绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形。通过Matplotlib,开发者可以仅需要几行代码,便可以生成绘图,直方图,功率谱,条形图,错误图,散点图等。
运行结果: 注意: 1.如果不使用plo.show()图表是显示不出来的,因为可能你要对图表进行多种的描述,所以通过显式的调用show()可以避免不必要的错误。
我这里单拿出一个一个的对象,然后后面在进行总结。在matplotlib中,整个图表为一个figure对象。其实对于每一个弹出的小窗口就是一个Figure对象,那么如何在一个代码中创建多个Figure对象,也就是多个小窗口呢? matplotlib.pyplot.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class ‘matplotlib.figure.Figure’>, clear=False, **kwargs) (1)num:这个参数是一个可选参数,即可以给参数也可以不给参数。可以将该num理解为窗口的属性id,即该窗口的身份标识。 如果不提供该参数,则创建窗口的时候该参数会自增,如果提供的话则该窗口会以该num为Id存在。 (2)figsize:可选参数。整数元组,默认是无。 提供整数元组则会以该元组为长宽,若不提供,默认为 rc fiuguer.figsize 例如(4,4)即以长4英寸 宽4英寸的大小创建一个窗口 (3)dpi:可选参数,整数。表示该窗口的分辨率,如果没有提供则默认为 figure.dpi (4)facecolor:可选参数,表示窗口的背景颜色,如果没有提供则默认为figure.facecolor 其中颜色的设置是通过RGB,范围是’#000000’~’#FFFFFF’,其中每2个字节16位表示RGB的0-255 例如’#FF0000’表示R:255 G:0 B:0 即红色。 (5)edgecolor:可选参数,表示窗口的边框颜色,如果没有提供则默认为figure,edgecolor (6)frameon:可选参数,表示是否绘制窗口的图框,默认是 (7)figureclass:暂不了解 (8)clear:可选参数,默认是false,如果提供参数为ture,并且该窗口存在的话 则该窗口内容会被清除。
import matplotlib.pyplot as plt import numpy as np x=np.linspace(-1,1,100) y1=x**2 y2=x*2 #这是第一个figure对象,下面的数据都会在第一个figure中显示 plt.figure() plt.plot(x,y1) #这里是第二个figure对象,下面的数据都会在第二个figure中显示 plt.figure(num=3,figsize=(10,5)) plt.plot(x,y2,color='red',linewidth='3.0',linestyle='--') plt.show()这里需要注意的是:
我们看上面的每个图像的窗口,可以看出figure并没有从1开始然后到2,这是因为我们在创建第二个figure对象的时候,指定了一个num = 3的参数,所以第二个窗口标题上显示的figure3。对于每一个窗口,我们也可以对他们分别去指定窗口的大小。也就是figsize参数。若我们想让他们的线有所区别,我们可以用下面语句进行修改 plt.plot(x,y2,color = 'red',linewidth = 3.0,linestyle = '--')numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None) 在指定的间隔内返回均匀间隔的数字。 返回num均匀分布的样本,在[start, stop]。 这个区间的端点可以任意的被排除在外。 了解更多.
运行截图
我们很多时候会再一个figures中去添加多条线,那我们如何去区分多条线呢?这里就用到了legend。 plt.legend(handles = [l1,l2],labels = [‘up’,‘down’],loc = ‘best’,shodow=True) 一旦在legend()函数中使用了labels属性,那么之前在plot函数中设置的label就会失效。如果labels中设置的参数比handels的参数少,那么labels中有多少个参数就会在图例中显示多少个函数信息。 plot函数石油返回值的,若想用legend函数的handles属性,必须在接收plot函数的返回值是加上一个‘,’。 loc表示图例的显示位置,默认显示位置为‘best’,即以最好的方式显示在图片中,尽量少的遮挡函数。
import matplotlib.pyplot as plt import numpy as np x=np.linspace(0,4,50) y1=2*x y2=4*x # 简单的使用 l1, = plt.plot(x, y1, label='linear line')#注意','很重要 l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line') # 简单的设置legend(设置位置) #方式一 plt.legend(loc='center')#(lower,center,upper)和(left,center,right)之间进行组合,还有特殊的‘center'指位于图中间,'best'表示放在遮住数据最少的位置 #方式二 plt.legend(loc="best",handles =[l1,l2],labels=["line1","line2"],shadow=True) plt.show()运行截图
注意:
xy就是需要进行注释的点的横纵坐标;xycoords = 'data’说明的是要注释点的xy的坐标是以横纵坐标轴为基准的;xytext=(+30,-30)和textcoords='data’说明了这里的文字是基于标注的点的x坐标的偏移+30以及标注点y坐标-30位置,就是我们要进行注释文字的位置;fontsize = 16就说明字体的大小;arrowprops = dict()这个是对于这个箭头的描述,arrowstyle=’->'这个是箭头的类型,connectionstyle="arc3,rad=.2"这两个是描述我们的箭头的弧度以及角度的。 第一种添加标签 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=.2"))第二种添加标签
print("-----方式二-----") plt.text(-3.7,3,r'$this\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$', fontdict={'size':16,'color':'r'})了解更多关于 cmap.
多合一显示
import matplotlib.pyplot as plt import numpy as np plt.figure() plt.subplot(2, 1, 1) plt.plot([0, 1], [0, 1]) # ax=plt.gca() # #右边的脊梁 # ax.spines['right'].set_color('none') # ax.spines['top'].set_color('none') # print("----重新设置x轴和y轴-------") # # 将底下的作为x轴 # ax.xaxis.set_ticks_position('bottom') # # 以y轴的数据为基本,设置‘bottom’脊梁的位置 # ax.spines['bottom'].set_position(('data', 0.5))#axes定义百分比位置 # # # 将左边的作为y轴 # ax.yaxis.set_ticks_position('left') # # 以x轴的数据为基本,设置‘left’脊梁的位置 # ax.spines['left'].set_position(('data', 0.5)) plt.subplot(2, 3, 4) plt.plot([0, 1], [0, 2]) plt.subplot(2, 3, 5) plt.plot([0, 1], [0, 1]) plt.subplot(2, 3, 6) plt.plot([0, 4], [0, 4]) plt.show()Subplot 分隔显示
import matplotlib.pyplot as plt import numpy as np #第二种分隔显示需要导入的模块 import matplotlib.gridspec as gridspec #方法一:subplot2.grid plt.figure() ax1=plt.subplot2grid((3,3),(0,0),colspan=3,rowspan=1) ax1.plot([1,2],[1,2]) #ax1.set_title()==plt.title()类似的都用set_ ax1.set_title('ax1_title') ax2=plt.subplot2grid((3,3),(1,0),colspan=2) ax3=plt.subplot2grid((3,3),(1,2),rowspan=2) ax4=plt.subplot2grid((3,3),(2,0)) ax5=plt.subplot2grid((3,3),(2,1)) #方法二:gridspec plt.figure() gs=gridspec.GridSpec(3,3) ax1=plt.subplot(gs[0,:]) ax2=plt.subplot(gs[1,:2]) ax3=plt.subplot(gs[1:,2]) ax4=plt.subplot(gs[-1,0]) ax5=plt.subplot(gs[-1,-2]) #方法三:easy to define structure f, ((ax11, ax12), (ax21, ax22)) = plt.subplots(2, 2, sharex=True, sharey=True) ax11.scatter([1,2],[1,2]) plt.tight_layout() plt.show()图中图
import matplotlib.pyplot as plt import numpy as np fig = plt.figure() x = [1, 2, 3, 4, 5, 6, 7] y = [1, 3, 4, 2, 5, 8, 6] left, bottom, width, height = 0.15, 0.1, 0.8, 0.8 ax1 = fig.add_axes([left, bottom, width, height]) ax1.plot(x, y, 'r') ax1.set_xlabel('x') ax1.set_ylabel('y') ax1.set_title('title') left, bottom, width, height = 0.2, 0.6, 0.25, 0.25 ax2 = fig.add_axes([left, bottom, width, height]) ax2.plot(y, x, 'g') plt.axes([.6, .2, .25, .25]) # y[::-1]将y中数据进行逆序 plt.plot(y[::-1], x, 'b') plt.show()次坐标轴
import matplotlib.pyplot as plt import numpy as np x = np.arange(0, 10, 0.1) y1 = 0.05 * x ** 2 y2 = -1 * y1 fg, ax1 = plt.subplots() ax2 = ax1.twinx() 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()animation动画
import matplotlib.pyplot as plt import numpy as np # 动画需要导入的模块 from matplotlib import animation fig, ax = plt.subplots() x = np.arange(0, 2 * np.pi, 0.01) line, = ax.plot(x, np.sin(x)) def animation1(i): global line line.set_ydata(np.sin(x + i / 150 * np.pi * 2)) return line def init1(): line.set_ydata(np.sin(x)) return line, ani = animation.FuncAnimation(fig=fig, func=animation1, frames=150, init_func=init1, interval=20, blit=False) plt.show()