zoukankan      html  css  js  c++  java
  • python之《matplotlib》

    # _*_coding:utf-8_*_
    # /usr/bin/env python3
    # Author:book Miki

    import matplotlib.pyplot as plt
    import numpy as np

    x = np.linspace(-5, 20, 20)
    y1 = x**2
    y2 = x*2+2
    # plt.figure(num=1)
    # plt.plot(x, y1)
    plt.figure(num=2)
    # set line label
    # plt.plot(x, y1, label='first line')
    plt.plot(x, y2, color='blue', linewidth=15, linestyle='-', label='second line', zorder=1)
    plt.ylim((-5, 5))
    plt.xlim((-5, 5))
    # plt.xticks(np.linspace(-2, 10, 7))
    # plt.yticks([-50, 0, 50, 100, 150, 200, 250, 300, 350],
    # ['is -50', 'none', 'is 50', 'is 100', 'is 150', 'is 200', 'is 250', 'is 300', 'is 350'])
    plt.ylabel('I am y')
    plt.xlabel('I am x')
    ax = plt.gca()
    ax.spines['right'].set_color('none') # 使用.spines设置边框
    ax.spines['top'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left') # 设置ticks标签 所有位置:left,right,both,default,none
    ax.spines['left'].set_position(('data', 0)) # 设置位置 位置所有属性:outward,axes,data
    ax.spines['bottom'].set_position(('data', 0))
    for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(12)
    # 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序
    label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7, zorder=2))
    plt.legend(loc='upper right')
    x0 = 1
    y0 = 2*x0+1
    plt.scatter(x0, y0, s=50, c='b')
    plt.plot([x0, x0], [0, y0], linestyle='--', color='blue')
    # 添加标注
    plt.annotate('2*%s + 1 = %s' % (x0, y0), xy=(x0, y0), xytext=(+30, -30),
    textcoords='offset points', fontsize=16,
    arrowprops=dict(arrowstyle='->',connectionstyle="arc3,rad=.2"))
    # 添加文本
    plt.text(-2, 2, 'this is function of matpoltlib.pypolt', fontdict={'size': '16', 'color': 'red'}, zorder=1)


    plt.show()


    '''
    1.plot 出图plot()先x 在y color linewidth 线宽 linestyle -是直线 --是虚线
    2.figure 一个figure就是一张图figure下面的plot 都在一张图上显示
    3.设置范围 xlim((star, end)) 或者ylim
    4.设置标签 xlabel() 或者ylabel()
    5.设置范围()原本范围不变与刻度 xticks([list]) 或者标签str代替number yticks([number list], [str list])
    6.ax.yaxis.set_ticks_position('left') # 设置ticks标签 所有位置:left,right,both,default,none
    7.在移动坐标之前我们要将top和right的设置成看不见
    ax.spines['top'].set_color('none')
    ax.spines['right'].set_color('none')
    8.移动x轴和y轴的位置 ax.spines['bottom'].set_position(('data', 0))# 设置位置 位置所有属性:outward,axes,data
    ax.spines['left'].set_position(('data', 0))
    9.标签使用,需要在polt的时候加入参数label 之后plt.legend(loc='upper right')
    我们在后面的时候难免要修改就可以 plt.legend(handles=[l1, l2], labels=['up', 'down'], loc='best')
    参数有 'best' : 0,
    'upper right' : 1,
    'upper left' : 2,
    'lower left' : 3,
    'lower right' : 4,
    'right' : 5,
    'center left' : 6,
    'center right' : 7,
    'lower center' : 8,
    'upper center' : 9,
    'center' : 10,
    10.plt.scatter(x0, y0, s=50, c='b') 画点
    plt.plot([x0, x0], [0, y0], linestyle='--', color='blue') 将点相连成线
    11.标注
    plt.annotate('2*%s + 1 = %s' % (x0, y0), xy=(x0, y0), xytext=(+30, -30),
    textcoords='offset points', fontsize=16,
    arrowprops=dict(arrowstyle='->',connectionstyle="arc3,rad=.2"))
    12.文本注释
    plt.text(x,y,text,fontdict={'size': 16, 'color': 'red'})
    13.图层的上下啥的,例如两根直线交织在一起,在什么的就会遮挡下面的显示
    自然,在我们的图中xaxis 与yxis上的label可能会被线遮住
    我们就可以通过改变zorder=1 或者 2 或者31这种输在来改变和设置透明度
    plt.plot(x, y2, color='blue', linewidth=15, linestyle='-', label='second line', zorder=1) 将plot出的线放在1
    plt.text(-2, 2, 'this is function of matpoltlib.pypolt', fontdict={'size': '16', 'color': 'red'}, zorder=1)
    for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(12)
    # 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序
    label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7, zorder=2))
    依次将x和y的label放在zorder = 2上
    14.画点,并为点符上颜色
    import matplotlib.pyplot as plt
    import numpy as np
    n = 10
    x = np.random.normal(0, 1, n)
    y = np.random.normal(0, 1, n)
    t = np.arctan2(x, y)
    plt.scatter(x, y, s=25, c=t, alpha=0.5)

    15. 等高线,
    等高线是在一个xy之上有高度,也就是z轴,并且这z是二维的,
    也就是说,x和y构成了一个网格,然后每个网格上的小正方形,都有了自己的高度凸起来了
    我们更具这个高度在x,y的平面上,先画等高线,然后上色。根
    据这个过程,
    1.构成网格 n = 256
    x = np.linspace(-3, 3, n)
    y = np.linspace(-4, 4, n)
    X, Y = np.meshgrid(x, y)
    2.对应的等分上色 plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.hot) 8的意思是将所有的高度分成8分,
    cmap是color map此时选择的是hot
    3.画线 C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidths=.5) 注: f(x,y)是早已设置好的函数
    4.在线的里面加标签(label) plt.clabel(C, inline=True, fontsize=10)

    16. 3D图
    3d图和等高线的原理是一样的在网格上有高度,但是我们要显示3D图就要借助matplotlib里面3d的显示库
    其次我们要将需要3D展示出来的figure传入Axes3D中生成实例
    fg = plt.figure()
    ax = Axes3D(fg)
    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)
    ax.plot_surface(X, Y, z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow')) # 此处的z也必须是meshgrid格式下生成的z
    # ax.contour(X, Y, z, zdir='z', offset=-1, camp=plt.get_cmap('rainbow')) # 等高线
    ax.contourf(X, Y, z, zdir='z', offset=-1, camp=plt.get_cmap('rainbow')) # 等高图
    注:rstride与cstride分别表示线的行幅度与列幅度
    并且我们根据生成的3d数据画出对应的等高线图也就是ax.contourf (填充颜色)
    17. subplot 多合一显示
    导入模块matplotlib之后我们可以在生成的figure里面将figure使用subplot将其分成多个层次几行几列
    需要注意的是 此时的subplot如plot一般一个figure下面的plot都在一个数据里面
    plt.figure()
    # 均匀显示
    plt.subplot(2, 2, 1)
    plt.plot([0, 5], [0, 5])
    plt.subplot(2, 2, 2)
    plt.plot([5, 5], [3, 1])
    # 不均匀显示
    plt.subplot(2, 3, 4)
    plt.plot([0, 5], [0, 5])
    plt.subplot(2, 3, 5)
    plt.plot([0, 5], [0, 5])
    plt.show()
    由此看来不均匀显示也是计算好的,并不是subplot就会将figure分割,而是在假设分割的基础上
    在贴图,所以后面2行3列,就是在4位置

    18. ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)
    ax1.plot([1, 2], [1, 2]) # 画小图
    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)) # 分区 (2,1)是起始位置,默认colspan和rowspan是1
    ax4.scatter([1, 2], [2, 2])
    ax4.set_xlabel('ax4_x')
    ax4.set_ylabel('ax4_y') # 设置xy的label
    plt.tight_layout()
    '''


    图中图
      
    '''
    1.设置[left, botton, width, height]的比例生成实例,此比例为百分比
    ax.add_axes([left, botton, width, height])
    然后就可以plot了 也可以 ax.set_xlabel() 也可以 ax.sel_title

    '''
    import matplotlib.pyplot as plt
    fig = plt.figure()
    
    left, botton, width, height = 0.1, 0.1, 0.8, 0.8
    x = [0, 1, 5, 6, 4, 9]
    y = [9, 10, 5, 8, 9, 6]
    
    ax = fig.add_axes([left, botton, width, height])
    ax.plot(x, y, 'r')
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_title('the one')
    left, botton, width, height = 0.2, 0.6, 0.2, 0.2
    ax1 = fig.add_axes([left, botton, width, height])
    ax1.plot(x, y, 'b')
    
    
    plt.show()
  • 相关阅读:
    标准C++中的string类的用法总结
    JSON用法简介
    拷贝构造函数的调用时机
    define中的:#,##,#@
    一个二维码支持支付宝和微信支付(下)
    一个二维码支持支付宝和微信支付(上)
    【JAVA笔记】JAVA后端实现统一扫码支付:微信篇
    java生成二维码,读取(解析)二维码图片
    Java程序员的日常—— IOUtils总结
    Java: Map里面的键和值可以为空吗?
  • 原文地址:https://www.cnblogs.com/BookMiki/p/10474088.html
Copyright © 2011-2022 走看看