https://www.zhihu.com/collection/260736383

https://blog.csdn.net/gaotihong/article/details/80983937

<此处就不自己写了,看了遍,照着写了一边,作者写的不错。不过有些有些偷懒,我只做了常见的功能>
作者:触摸壹缕阳光
链接:https://zhuanlan.zhihu.com/p/33270402
来源:知乎
著作权归作者所有,转载请联系作者获得授权。

1.前言

Matplotlib是一个python的 2D绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形。通过Matplotlib,开发者可以仅需要几行代码,便可以生成绘图,直方图,功率谱,条形图,错误图,散点图等。

2.简单的使用

  1.  
    import matplotlib.pyplot as plt
  2.  
    import numpy as np
  3.  
     
  4.  
    x = np.linspace(-1,1,50)#从(-1,1)均匀取50个点
  5.  
    y = 2 * x
  6.  
     
  7.  
    plt.plot(x,y)
  8.  
    plt.show()

y = 2x图像

注意:
1.如果不使用plo.show()图表是显示不出来的,因为可能你要对图表进行多种的描述,所以通过显式的调用show()可以避免不必要的错误。

3.Figure对象

我这里单拿出一个一个的对象,然后后面在进行总结。在matplotlib中,整个图表为一个figure对象。其实对于每一个弹出的小窗口就是一个Figure对象,那么如何在一个代码中创建多个Figure对象,也就是多个小窗口呢?

  1.  
    import matplotlib.pyplot as plt
  2.  
    import numpy as np
  3.  
     
  4.  
    x = np.linspace(-1,1,50)
  5.  
    y1 = x ** 2
  6.  
    y2 = x * 2
  7.  
    #这个是第一个figure对象,下面的内容都会在第一个figure中显示
  8.  
    plt.figure()
  9.  
    plt.plot(x,y1)
  10.  
    #这里第二个figure对象
  11.  
    plt.figure(num = 3,figsize = (10,5))
  12.  
    plt.plot(x,y2)
  13.  
    plt.show()

这里需要注意的是:

  1. 我们看上面的每个图像的窗口,可以看出figure并没有从1开始然后到2,这是因为我们在创建第二个figure对象的时候,指定了一个num = 3的参数,所以第二个窗口标题上显示的figure3。
  2. 对于每一个窗口,我们也可以对他们分别去指定窗口的大小。也就是figsize参数。
  3. 若我们想让他们的线有所区别,我们可以用下面语句进行修改
plt.plot(x,y2,color = 'red',linewidth = 3.0,linestyle = '--')

4.设置坐标轴

我们想更改在图表上显示x,y的取值范围:

  1.  
    import matplotlib.pyplot as plt
  2.  
    import numpy as np
  3.  
     
  4.  
    x = np.linspace(-1,1,50)
  5.  
    y = x *2
  6.  
     
  7.  
    plt.plot(x,y)
  8.  
    plt.show()

默认的横纵坐标

  1.  
    #在plt.show()之前添加
  2.  
    plt.xlim((0,2))
  3.  
    plt.ylim((-2,2))

更改横纵坐标的取值范围之后

给横纵坐标设置名称:

  1.  
    import matplotlib.pyplot as plt
  2.  
    import numpy as np
  3.  
     
  4.  
    x = np.linspace(-1,1,50)
  5.  
    y = x * 2
  6.  
     
  7.  
    plt.xlabel("x'slabel")#x轴上的名字
  8.  
    plt.ylabel("y's;abel")#y轴上的名字
  9.  
    plt.plot(x,y,color='green',linewidth = 3)
  10.  
    plt.show()

把坐标轴换成不同的单位:

  1.  
    new_ticks = np.linspace(-1,2,5)
  2.  
    plt.xticks(new_ticks)
  3.  
    #在对应坐标处更换名称
  4.  
    plt.yticks([-2,-1,0,1,2],['really bad','b','c','d','good'])

更换后的坐标名称

那么如果我想把坐标轴上的字体更改成数学的那种形式:

  1.  
    #在对应坐标处更换名称
  2.  
    plt.yticks([-2,-1,0,1,2],[r'$really\ bad$',r'$b$',r'$c\ \alpha$','d','good'])

将单位改成数学的字体格式

注意:

  1. 我们如果要使用空格的话需要进行对空格的转义"\ "这种转义才能输出空格;
  2. 我们可以在里面加一些数学的公式,如"\alpha"来表示  。

如何去更换坐标原点,坐标轴呢?我们在plt.show()之前:

  1.  
    #gca = 'get current axis'
  2.  
    #获取当前的这四个轴
  3.  
    ax = plt.gca()
  4.  
    #设置脊梁(也就是包围在图标四周的默认黑线)
  5.  
    #所以设置脊梁的时候,一共有四个方位
  6.  
    ax.spines['right'].set_color('r')
  7.  
    ax.spines['top'].set_color('none')
  8.  
     
  9.  
    #将底部脊梁作为x轴
  10.  
    ax.xaxis.set_ticks_position('bottom')
  11.  
    #ACCEPTS:['top' | 'bottom' | 'both'|'default'|'none']
  12.  
     
  13.  
    #设置x轴的位置(设置底的时候依据的是y轴)
  14.  
    ax.spines['bottom'].set_position(('data',0))
  15.  
    #the 1st is in 'outward' |'axes' | 'data'
  16.  
    #axes : precentage of y axis
  17.  
    #data : depend on y data
  18.  
     
  19.  
    ax.yaxis.set_ticks_position('left')
  20.  
    # #ACCEPTS:['top' | 'bottom' | 'both'|'default'|'none']
  21.  
     
  22.  
    #设置左脊梁(y轴)依据的是x轴的0位置
  23.  
    ax.spines['left'].set_position(('data',0))

更改坐标轴位置

5.legend图例

我们很多时候会再一个figures中去添加多条线,那我们如何去区分多条线呢?这里就用到了legend。

  1.  
    #简单的使用
  2.  
    l1, = plt.plot(x, y1, label='linear line')
  3.  
    l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')
  4.  
     
  5.  
    #简单的设置legend(设置位置)
  6.  
    #位置在右上角
  7.  
    plt.legend(loc = 'upper right')

  1.  
    l1, = plt.plot(x, y1, label='linear line')
  2.  
    l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')
  3.  
     
  4.  
     
  5.  
    plt.legend(handles = [l1,l2],labels = ['up','down'],loc = 'best')
  6.  
    #the ',' is very important in here l1, = plt...and l2, = plt...for this step
  7.  
    """legend( handles=(line1, line2, line3),
  8.  
    labels=('label1', 'label2', 'label3'),
  9.  
    'upper right')
  10.  
    shadow = True 设置图例是否有阴影
  11.  
    The *loc* location codes are::
  12.  
    'best' : 0,
  13.  
    'upper right' : 1,
  14.  
    'upper left' : 2,
  15.  
    'lower left' : 3,
  16.  
    'lower right' : 4,
  17.  
    'right' : 5,
  18.  
    'center left' : 6,
  19.  
    'center right' : 7,
  20.  
    'lower center' : 8,
  21.  
    'upper center' : 9,
  22.  
    'center' : 10,"""

这里需要注意的是:

  1. 如果我们没有在legend方法的参数中设置labels,那么就会使用画线的时候,也就是plot方法中的指定的label参数所指定的名称,当然如果都没有的话就会抛出异常;
  2. 其实我们plt.plot的时候返回的是一个线的对象,如果我们想在handle中使用这个对象,就必须在返回的名字的后面加一个","号;
  1.  
    legend = plt.legend(handles = [l1,l2],labels = ['hu','tang'],loc = 'upper center',shadow = True)
  2.  
    frame = legend.get_frame()
  3.  
    frame.set_facecolor('r')#或者0.9...

更改后的图例样式

6.在图片上加一些标注annotation

在图片上加注解有两种方式:

  1.  
    import matplotlib.pyplot as plt
  2.  
    import numpy as np
  3.  
     
  4.  
    x = np.linspace(-3,3,50)
  5.  
    y = 2*x + 1
  6.  
     
  7.  
    plt.figure(num = 1,figsize =(8,5))
  8.  
    plt.plot(x,y)
  9.  
     
  10.  
    ax = plt.gca()
  11.  
    ax.spines['right'].set_color('none')
  12.  
    ax.spines['top'].set_color('none')
  13.  
     
  14.  
    #将底下的作为x轴
  15.  
    ax.xaxis.set_ticks_position('bottom')
  16.  
    #并且data,以y轴的数据为基本
  17.  
    ax.spines['bottom'].set_position(('data',0))
  18.  
     
  19.  
    #将左边的作为y轴
  20.  
    ax.yaxis.set_ticks_position('left')
  21.  
    ax.spines['left'].set_position(('data',0))
  22.  
     
  23.  
    print("-----方式一-----")
  24.  
    x0 = 1
  25.  
    y0 = 2*x0 + 1
  26.  
    plt.plot([x0,x0],[0,y0],'k--',linewidth = 2.5)
  27.  
    plt.scatter([x0],[y0],s = 50,color='b')
  28.  
    plt.annotate(r'$2x+1 = %s$'% y0,xy = (x0,y0),xycoords = 'data',
  29.  
    xytext=(+30,-30),textcoords = 'offset points',fontsize = 16
  30.  
    ,arrowprops = dict(arrowstyle='->',
  31.  
    connectionstyle="arc3,rad=.2"))
  32.  
    plt.show()

第一种annotation

  1.  
    plt.annotate(r'$2x+1 = %s$'% y0,xy = (x0,y0),xycoords = 'data',
  2.  
    xytext=(+30,-30),textcoords = 'offset points',fontsize = 16
  3.  
    ,arrowprops = dict(arrowstyle='->',
  4.  
    connectionstyle="arc3,rad=.2"))

注意:

  1. xy就是需要进行注释的点的横纵坐标;
  2. xycoords = 'data'说明的是要注释点的xy的坐标是以横纵坐标轴为基准的;
  3. xytext=(+30,-30)和textcoords='data'说明了这里的文字是基于标注的点的x坐标的偏移+30以及标注点y坐标-30位置,就是我们要进行注释文字的位置;
  4. fontsize = 16就说明字体的大小;
  5. arrowprops = dict()这个是对于这个箭头的描述,arrowstyle='->'这个是箭头的类型,connectionstyle="arc3,rad=.2"这两个是描述我们的箭头的弧度以及角度的。
  1.  
    print("-----方式二-----")
  2.  
    plt.text(-3.7,3,r'$this\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
  3.  
    fontdict={'size':16,'color':'r'})

第二种标注方式

这里先介绍一下plot中的一个参数:

  1.  
    import matplotlib.pyplot as plt
  2.  
    import numpy as np
  3.  
     
  4.  
    x = np.linspace(-3,3,50)
  5.  
    y1 = 0.1*x
  6.  
    y2 = x**2
  7.  
     
  8.  
    plt.figure()
  9.  
    #zorder控制绘图顺序
  10.  
    plt.plot(x,y1,linewidth = 10,zorder = 2,label = r'$y_1\ =\ 0.1*x$')
  11.  
    plt.plot(x,y2,linewidth = 10,zorder = 1,label = r'$y_2\ =\ x^{2}$')
  12.  
     
  13.  
    plt.legend(loc = 'lower right')
  14.  
     
  15.  
    plt.show()

如果改成:

  1.  
    #zorder控制绘图顺序
  2.  
    plt.plot(x,y1,linewidth = 10,zorder = 1,label = r'$y_1\ =\ 0.1*x$')
  3.  
    plt.plot(x,y2,linewidth = 10,zorder = 2,label = r'$y_2\ =\ x^{2}$')

下面我们看一下这个图:

  1.  
    import matplotlib.pyplot as plt
  2.  
    import numpy as np
  3.  
     
  4.  
    x = np.linspace(-3,3,50)
  5.  
    y1 = 0.1*x
  6.  
    y2 = x**2
  7.  
     
  8.  
    plt.figure()
  9.  
    #zorder控制绘图顺序
  10.  
    plt.plot(x,y1,linewidth = 10,zorder = 1,label = r'$y_1\ =\ 0.1*x$')
  11.  
    plt.plot(x,y2,linewidth = 10,zorder = 2,label = r'$y_2\ =\ x^{2}$')
  12.  
     
  13.  
    plt.ylim(-2,2)
  14.  
     
  15.  
    ax = plt.gca()
  16.  
    ax.spines['right'].set_color('none')
  17.  
    ax.spines['top'].set_color('none')
  18.  
     
  19.  
    ax.xaxis.set_ticks_position('bottom')
  20.  
    ax.spines['bottom'].set_position(('data',0))
  21.  
    ax.yaxis.set_ticks_position('left')
  22.  
    ax.spines['left'].set_position(('data',0))
  23.  
     
  24.  
    plt.show()

执行效果

从上面看,我们可以看见我们轴上的坐标被掩盖住了,那么我们怎么去修改他呢?

  1.  
    print(ax.get_xticklabels())
  2.  
    print(ax.get_yticklabels())
  3.  
     
  4.  
    for label in ax.get_xticklabels() + ax.get_yticklabels():
  5.  
    label.set_fontsize(12)
  6.  
    label.set_bbox(dict(facecolor = 'white',edgecolor='none',alpha = 0.8,zorder = 2))
  7.  
     
  8.  
    <a list of 9 Text xticklabel objects>
  9.  
    <a list of 9 Text yticklabel objects>

让坐标轴显示出来

这里需要注意:

  1. ax.get_xticklabels()获取得到就是坐标轴上的数字;
  2. set_bbox()这个bbox就是那坐标轴上的数字的那一小块区域,从结果我们可以很明显的看出来;
  3. facecolor = 'white',edgecolor='none,第一个参数表示的这个box的前面的背景,边上的颜色。

7.画图的种类

1.scatter散点图

  1.  
    import matplotlib.pyplot as plt
  2.  
    import numpy as np
  3.  
     
  4.  
    n = 1024
  5.  
    X = np.random.normal(0,1,n)
  6.  
    Y = np.random.normal(0,1,n)
  7.  
    T = np.arctan2(Y,X)#for color later on
  8.  
     
  9.  
    plt.scatter(X,Y,s = 75,c = T,alpha = .5)
  10.  
     
  11.  
    plt.xlim((-1.5,1.5))
  12.  
    plt.xticks([])#ignore xticks
  13.  
    plt.ylim((-1.5,1.5))
  14.  
    plt.yticks([])#ignore yticks
  15.  
    plt.show()

散点图

2.柱状图

  1.  
    import matplotlib.pyplot as plt
  2.  
    import numpy as np
  3.  
     
  4.  
    n = 12
  5.  
    X = np.arange(n)
  6.  
    Y1 = (1 - X/float(n)) * np.random.uniform(0.5,1.0,n)
  7.  
    Y2 = (1 - X/float(n)) * np.random.uniform(0.5,1.0,n)
  8.  
    #facecolor:表面的颜色;edgecolor:边框的颜色
  9.  
    plt.bar(X,+Y1,facecolor = '#9999ff',edgecolor = 'white')
  10.  
    plt.bar(X,-Y2,facecolor = '#ff9999',edgecolor = 'white')
  11.  
    #描绘text在图表上
  12.  
    # plt.text(0 + 0.4, 0 + 0.05,"huhu")
  13.  
    for x,y in zip(X,Y1):
  14.  
    #ha : horizontal alignment
  15.  
    #va : vertical alignment
  16.  
    plt.text(x + 0.01,y+0.05,'%.2f'%y,ha = 'center',va='bottom')
  17.  
     
  18.  
    for x,y in zip(X,Y2):
  19.  
    # ha : horizontal alignment
  20.  
    # va : vertical alignment
  21.  
    plt.text(x+0.01,-y-0.05,'%.2f'%(-y),ha='center',va='top')
  22.  
     
  23.  
    plt.xlim(-.5,n)
  24.  
    plt.yticks([])
  25.  
    plt.ylim(-1.25,1.25)
  26.  
    plt.yticks([])
  27.  
    plt.show()

柱状图

3.Contours等高线图

  1.  
    import matplotlib.pyplot as plt
  2.  
    import numpy as np
  3.  
     
  4.  
    def f(x,y):
  5.  
    #the height function
  6.  
    return (1-x/2 + x**5+y**3) * np.exp(-x **2 -y**2)
  7.  
     
  8.  
    n = 256
  9.  
    x = np.linspace(-3,3,n)
  10.  
    y = np.linspace(-3,3,n)
  11.  
    #meshgrid函数用两个坐标轴上的点在平面上画网格。
  12.  
    X,Y = np.meshgrid(x,y)
  13.  
     
  14.  
    #use plt.contourf to filling contours
  15.  
    #X Y and value for (X,Y) point
  16.  
    #这里的8就是说明等高线分成多少个部分,如果是0则分成2半
  17.  
    #则8是分成10半
  18.  
    #cmap找对应的颜色,如果高=0就找0对应的颜色值,
  19.  
    plt.contourf(X,Y,f(X,Y),8,alpha = .75,cmap = plt.cm.hot)
  20.  
     
  21.  
    #use plt.contour to add contour lines
  22.  
    C = plt.contour(X,Y,f(X,Y),8,colors = 'black',linewidth = .5)
  23.  
     
  24.  
    #adding label
  25.  
    plt.clabel(C,inline = True,fontsize = 10)
  26.  
     
  27.  
    #ignore ticks
  28.  
    plt.xticks([])
  29.  
    plt.yticks([])
  30.  
     
  31.  
    plt.show()

等高线

4.image图片

  1.  
    import matplotlib.pyplot as plt
  2.  
    import numpy as np
  3.  
     
  4.  
    #image data
  5.  
    a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
  6.  
    0.365348418405, 0.439599930621, 0.525083754405,
  7.  
    0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)
  8.  
     
  9.  
    '''
  10.  
    for the value of "interpolation",check this:
  11.  
    http://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.html
  12.  
    for the value of "origin"= ['upper', 'lower'], check this:
  13.  
    http://matplotlib.org/examples/pylab_examples/image_origin.html
  14.  
    '''
  15.  
    #显示图像
  16.  
    #这里的cmap='bone'等价于plt.cm.bone
  17.  
    plt.imshow(a,interpolation = 'nearest',cmap = 'bone' ,origin = 'up')
  18.  
    #显示右边的栏
  19.  
    plt.colorbar(shrink = .92)
  20.  
     
  21.  
    #ignore ticks
  22.  
    plt.xticks([])
  23.  
    plt.yticks([])
  24.  
     
  25.  
    plt.show()

显示图片

5.3D数据

  1.  
    import numpy as np
  2.  
    import matplotlib.pyplot as plt
  3.  
    from mpl_toolkits.mplot3d import Axes3D
  4.  
     
  5.  
    fig = plt.figure()
  6.  
    ax = Axes3D(fig)
  7.  
    #X Y value
  8.  
    X = np.arange(-4,4,0.25)
  9.  
    Y = np.arange(-4,4,0.25)
  10.  
    X,Y = np.meshgrid(X,Y)
  11.  
    R = np.sqrt(X**2 + Y**2)
  12.  
    #hight value
  13.  
    Z = np.sin(R)
  14.  
     
  15.  
    ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
  16.  
    """
  17.  
    ============= ================================================
  18.  
    Argument Description
  19.  
    ============= ================================================
  20.  
    *X*, *Y*, *Z* Data values as 2D arrays
  21.  
    *rstride* Array row stride (step size), defaults to 10
  22.  
    *cstride* Array column stride (step size), defaults to 10
  23.  
    *color* Color of the surface patches
  24.  
    *cmap* A colormap for the surface patches.
  25.  
    *facecolors* Face colors for the individual patches
  26.  
    *norm* An instance of Normalize to map values to colors
  27.  
    *vmin* Minimum value to map
  28.  
    *vmax* Maximum value to map
  29.  
    *shade* Whether to shade the facecolors
  30.  
    ============= ================================================
  31.  
    """
  32.  
     
  33.  
    # I think this is different from plt12_contours
  34.  
    ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.get_cmap('rainbow'))
  35.  
    """
  36.  
    ========== ================================================
  37.  
    Argument Description
  38.  
    ========== ================================================
  39.  
    *X*, *Y*, Data values as numpy.arrays
  40.  
    *Z*
  41.  
    *zdir* The direction to use: x, y or z (default)
  42.  
    *offset* If specified plot a projection of the filled contour
  43.  
    on this position in plane normal to zdir
  44.  
    ========== ================================================
  45.  
    """
  46.  
    ax.set_zlim(-2, 2)
  47.  
    plt.show()

8.多图合并展示

1.使用subplot函数

  1.  
    import matplotlib.pyplot as plt
  2.  
     
  3.  
    plt.figure(figsize = (6,5))
  4.  
     
  5.  
    ax1 = plt.subplot(3,1,1)
  6.  
    ax1.set_title("ax1 title")
  7.  
    plt.plot([0,1],[0,1])
  8.  
     
  9.  
    #这种情况下如果再数的话以334为标准了,
  10.  
    #把上面的第一行看成是3个列
  11.  
    ax2 = plt.subplot(334)
  12.  
    ax2.set_title("ax2 title")
  13.  
     
  14.  
    ax3 = plt.subplot(335)
  15.  
    ax4 = plt.subplot(336)
  16.  
    ax5 = plt.subplot(325)
  17.  
    ax6 = plt.subplot(326)
  18.  
     
  19.  
    plt.show()

案例一

  1.  
    import matplotlib.pyplot as plt
  2.  
     
  3.  
    plt.figure(figsize = (6,4))
  4.  
    #plt.subplot(n_rows,n_cols,plot_num)
  5.  
    plt.subplot(211)
  6.  
    # figure splits into 2 rows, 1 col, plot to the 1st sub-fig
  7.  
    plt.plot([0, 1], [0, 1])
  8.  
     
  9.  
    plt.subplot(234)
  10.  
    # figure splits into 2 rows, 3 col, plot to the 4th sub-fig
  11.  
    plt.plot([0, 1], [0, 2])
  12.  
     
  13.  
    plt.subplot(235)
  14.  
    # figure splits into 2 rows, 3 col, plot to the 5th sub-fig
  15.  
    plt.plot([0, 1], [0, 3])
  16.  
     
  17.  
    plt.subplot(236)
  18.  
    # figure splits into 2 rows, 3 col, plot to the 6th sub-fig
  19.  
    plt.plot([0, 1], [0, 4])
  20.  
     
  21.  
    plt.tight_layout()
  22.  
    plt.show()

案例二

2.分格显示

  1.  
    #method 1: subplot2grid
  2.  
    import matplotlib.pyplot as plt
  3.  
    plt.figure()
  4.  
    #第一个参数shape也就是我们网格的形状
  5.  
    #第二个参数loc,位置,这里需要注意位置是从0开始索引的
  6.  
    #第三个参数colspan跨多少列,默认是1
  7.  
    #第四个参数rowspan跨多少行,默认是1
  8.  
    ax1 = plt.subplot2grid((3,3),(0,0),colspan = 3,rowspan = 1)
  9.  
    #如果为他设置一些属性的话,如plt.title,则用ax1的话
  10.  
    #ax1.set_title(),同理可设置其他属性
  11.  
    ax1.set_title("ax1_title")
  12.  
     
  13.  
    ax2 = plt.subplot2grid((3,3),(1,0),colspan = 2,rowspan = 1)
  14.  
    ax3 = plt.subplot2grid((3,3),(1,2),colspan = 1,rowspan = 2)
  15.  
    ax4 = plt.subplot2grid((3,3),(2,0),colspan = 1,rowspan = 1)
  16.  
    ax5 = plt.subplot2grid((3,3),(2,1),colspan = 1,rowspan = 1)
  17.  
     
  18.  
    plt.show()

method1 result

  1.  
    #method 2:gridspec
  2.  
    import matplotlib.pyplot as plt
  3.  
    import matplotlib.gridspec as gridspec
  4.  
     
  5.  
    plt.figure()
  6.  
    gs = gridspec.GridSpec(3,3)
  7.  
    #use index from 0
  8.  
    ax1 = plt.subplot(gs[0,:])
  9.  
    ax1.set_title("ax1 title")
  10.  
     
  11.  
    ax2 = plt.subplot(gs[1,:2])
  12.  
    ax2.plot([1,2],[3,4],'r')
  13.  
     
  14.  
    ax3 = plt.subplot(gs[1:,2:])
  15.  
    ax4 = plt.subplot(gs[-1,0])
  16.  
    ax5 = plt.subplot(gs[-1,-2])
  17.  
     
  18.  
    plt.show()

method2 result

  1.  
    #method 3 :easy to define structure
  2.  
    #这种方式不能生成指定跨行列的那种
  3.  
    import matplotlib.pyplot as plt
  4.  
    #(ax11,ax12),(ax13,ax14)代表了两行
  5.  
    #f就是figure对象,
  6.  
    #sharex:是否共享x轴
  7.  
    #sharey:是否共享y轴
  8.  
    f,((ax11,ax12),(ax13,ax14)) = plt.subplots(2,2,sharex = True,sharey = True)
  9.  
    ax11.set_title("a11 title")
  10.  
    ax12.scatter([1,2],[1,2])
  11.  
     
  12.  
    plt.show()

method3 result

3.图中图

  1.  
    import matplotlib.pyplot as plt
  2.  
     
  3.  
    fig = plt.figure()
  4.  
    x = [1,2,3,4,5,6,7]
  5.  
    y = [1,3,4,2,5,8,6]
  6.  
     
  7.  
    #below are all percentage
  8.  
    left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
  9.  
    #使用plt.figure()显示的是一个空的figure
  10.  
    #如果使用fig.add_axes会添加轴
  11.  
    ax1 = fig.add_axes([left, bottom, width, height])# main axes
  12.  
    ax1.plot(x,y,'r')
  13.  
    ax1.set_xlabel('x')
  14.  
    ax1.set_ylabel('y')
  15.  
    ax1.set_title('title')
  16.  
     
  17.  
    ax2 = fig.add_axes([0.2, 0.6, 0.25, 0.25]) # inside axes
  18.  
    ax2.plot(y, x, 'b')
  19.  
    ax2.set_xlabel('x')
  20.  
    ax2.set_ylabel('y')
  21.  
    ax2.set_title('title inside 1')
  22.  
     
  23.  
    # different method to add axes
  24.  
    ####################################
  25.  
    plt.axes([0.6, 0.2, 0.25, 0.25])
  26.  
    plt.plot(y[::-1], x, 'g')
  27.  
    plt.xlabel('x')
  28.  
    plt.ylabel('y')
  29.  
    plt.title('title inside 2')
  30.  
     
  31.  
    plt.show()

画中画

4.次坐标轴

  1.  
    # 使用twinx是添加y轴的坐标轴
  2.  
    # 使用twiny是添加x轴的坐标轴
  3.  
    import matplotlib.pyplot as plt
  4.  
    import numpy as np
  5.  
     
  6.  
    x = np.arange(0,10,0.1)
  7.  
    y1 = 0.05 * x ** 2
  8.  
    y2 = -1 * y1
  9.  
     
  10.  
    fig,ax1 = plt.subplots()
  11.  
     
  12.  
    ax2 = ax1.twinx()
  13.  
    ax1.plot(x,y1,'g-')
  14.  
    ax2.plot(x,y2,'b-')
  15.  
     
  16.  
    ax1.set_xlabel('X data')
  17.  
    ax1.set_ylabel('Y1 data',color = 'g')
  18.  
    ax2.set_ylabel('Y2 data',color = 'b')
  19.  
     
  20.  
    plt.show()

次坐标

9.animation动画

  1.  
    import numpy as np
  2.  
    from matplotlib import pyplot as plt
  3.  
    from matplotlib import animation
  4.  
     
  5.  
    fig,ax = plt.subplots()
  6.  
     
  7.  
    x = np.arange(0,2*np.pi,0.01)
  8.  
    #因为这里返回的是一个列表,但是我们只想要第一个值
  9.  
    #所以这里需要加,号
  10.  
    line, = ax.plot(x,np.sin(x))
  11.  
     
  12.  
    def animate(i):
  13.  
    line.set_ydata(np.sin(x + i/10.0))#updata the data
  14.  
    return line,
  15.  
     
  16.  
    def init():
  17.  
    line.set_ydata(np.sin(x))
  18.  
    return line,
  19.  
     
  20.  
     
  21.  
    # call the animator. blit=True means only re-draw the parts that have changed.
  22.  
    # blit=True dose not work on Mac, set blit=False
  23.  
    # interval= update frequency
  24.  
    #frames帧数
  25.  
    ani = animation.FuncAnimation(fig=fig, func=animate, frames=100, init_func=init,
  26.  
    interval=20, blit=False)
  27.  
     
  28.  
    plt.show()

Python-matplotlib画图(莫烦笔记)的更多相关文章

  1. python matplotlib画图产生的Type 3 fonts字体没有嵌入问题

    ScholarOne's 对python matplotlib画图产生的Type 3 fonts字体不兼容,更改措施: 在程序中添加如下语句 import matplotlib matplotlib. ...

  2. 用python matplotlib 画图

    state-machine environment object-oriente interface figure and axes backend and frontend user interfa ...

  3. python matplotlib 画图

    import numpy as np import matplotlib.pyplot as plt from pylab import * numpy 常用来组织源数据: 使用 plot 函数直接绘 ...

  4. tensorflow学习笔记-bili莫烦

    bilibili莫烦tensorflow视频教程学习笔记 1.初次使用Tensorflow实现一元线性回归 # 屏蔽警告 import os os.environ[' import numpy as ...

  5. scikit-learn学习笔记-bili莫烦

    bilibili莫烦scikit-learn视频学习笔记 1.使用KNN对iris数据分类 from sklearn import datasets from sklearn.model_select ...

  6. 稍稍乱入的CNN,本文依然是学习周莫烦视频的笔记。

    稍稍乱入的CNN,本文依然是学习周莫烦视频的笔记. 还有 google 在 udacity 上的 CNN 教程. CNN(Convolutional Neural Networks) 卷积神经网络简单 ...

  7. 使用python中的matplotlib 画图,show后关闭窗口,继续运行命令

    使用python中的matplotlib 画图,show后关闭窗口,继续运行命令 在用python中的matplotlib 画图时,show()函数总是要放在最后,且它阻止命令继续往下运行,直到1.0 ...

  8. 莫烦大大TensorFlow学习笔记(9)----可视化

      一.Matplotlib[结果可视化] #import os #os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import tensorflow as tf i ...

  9. python使用matplotlib画图

    python使用matplotlib画图 matplotlib库是python最著名的画图库.它提供了一整套和matlab类似的命令API.十分适合交互式地进行制图. 先介绍了怎样使用matplotl ...

随机推荐

  1. RedHat 6.3安装MySQL-server-5.6.13-1.el6.x86_64.rpm

     在RedHat 6.3下安装MySQL-server-5.6.13-1.el6.x86_64.rpm 首先下载下面三个文件: MySQL-client-5.6.13-1.el6.x86_64.rpm ...

  2. 解决通过vue-router打开tab页,下次进入还是上次history缓存的界面状态的问题

    一.问题描述: 1. 跳转模式:界面A-->界面B(界面A中通过 this.$router.push({name:'组件B名称', params: {参数}}) 通过打开新tab页的方式打开界面 ...

  3. abp学习(一)

    官网概念 ASP.NET样板是特别设计的新的现代Web应用程序的通用应用框架.它使用已经熟悉的工具并围绕这些工具实现最佳实践,从而为您提供一致的开发体验. 官网地址:https://aspnetboi ...

  4. 【转】解决maven无法加载本地lib/下的jar包问题(程序包XXX不存在)

    原文链接:https://www.cnblogs.com/adeng/p/7096484.html 这次一个项目用到maven编译,我在本地开发的时候jar包都是放在WEB-INF/lib目录下,通过 ...

  5. P2261 [CQOI2007]余数求和[整除分块]

    题目大意 给出正整数 n 和 k 计算 \(G(n, k)=k\ \bmod\ 1 + k\ \bmod\ 2 + k\ \bmod\ 3 + \cdots + k\ \bmod\ n\) 的值 其中 ...

  6. DT二次开发之-采购页面加入好看的倒计时

    加入采购页面倒计时,个人感觉挺漂亮的,做下笔记. <span id="timer" ></span> {if $totime} <script typ ...

  7. python 判断返回值是否是字典

    背景: 小鱼最近再调一个小工程时,需要对返回值进行处理(返回值如下),有的返回值 有data1 有的没有:需要做个判断,判断是否含有该key值 返回值: res1 = {"result&qu ...

  8. 为什么要使用ConcurrentHashMap

    好久没写过技术性文章了,还是要坚持下去.掌握的知识,能写出来或者是讲给别人听才是真正的掌握了知识,如果不善于给别人讲,实际上还是没有真正掌握相关的知识,挑个简单的写吧. 面试的时候经常会被问到hash ...

  9. nginx配置静态资源:配置绝对路径

    nginx配置静态资源:配置绝对路径 项目都是html格式的文件,我的项目路径:E:\javaservice\nginx-1.15.7\html assets:静态资源 html:站点文件 uploa ...

  10. 集合(Collection)类

    集合(Collection)类是专门用于数据存储和检索的类.这些类提供了对栈(stack).队列(queue).列表(list)和哈希表(hash table)的支持.大多数集合类实现了相同的接口. ...