美文网首页
matplotlib看例子学画图

matplotlib看例子学画图

作者: Cloud_Boy | 来源:发表于2019-04-19 16:49 被阅读0次

    matplotlib画图简单例子学习

    Tips:该文带目录地址http://www.cloboy.top/index.php/archives/124/

    1. 看图识大局

    image

    首先看看一张图像的构成,上面一幅图足够解释各个部分的名称功能,下面解释几个不好理解的部分

    • Figure:可以看成一张幕布,在上面你可以画多张图像
    • Axes:当前画一张图像的区域
    • Spines:其实就是连接轴刻度标记的那些直线
    • Makers:标记点,用于只画点而不画线的图像

    该大图的每一部分在matplotlib中都可以进行修改调整。下面看几个例子学习把。。

    2.画一张功能齐全的图

    A.显示图像

    image

    B.对应代码

    import matplotlib.pyplot as plt #matplotlib画图函数
    import numpy as np #加载numpy模块
    
    x = np.linspace(0, 2, 100) #0到2之间取100个数
    
    plt.plot(x, x, label='linear') #(x坐标,y坐标,名称标记)
    plt.plot(x, x**2, label='quadratic')
    plt.plot(x, x**3, label='cubic')
    
    plt.xlabel('x label') #横轴名称
    plt.ylabel('y label') #纵轴名称
    
    plt.title("Simple Plot") #整张图像的title
    
    plt.legend()  #将plot函数中的label展示出来:展示图例,可加入参数对图例的位置等进行调整
    
    plt.show() #展示图像
    

    3.一张幕布下画两张图

    我们如果想在一张幕布下(fig下)画两张甚至更多不同的图像,就可参考一下案例
    A.显示图像

    image

    B.对应代码

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.arange(0, 10, 0.2)
    y = np.sin(x)
    
    fig, [ax1,ax2] = plt.subplots(2,1)  #幕布大小为2*1, [ax1,ax2] 可以用ax替代,相应的ax1和ax2可以分别用ax[0]和ax[1]替代
    
    ax1.plot(x, y)   #ax1 = ax[0]
    ax1.set_xlabel('time') #设置横轴名称
    ax1.set_ylabel('high') #设置纵轴名称
    
    ax2.plot(x,y)  #ax2 = ax[1]
    ax2.set_title('sinB') #设置标题
    ax2.set_ylabel('high')#设置横轴名称
    ax2.set_xlabel('time')#设置纵轴名称
    
    #注意两张图像描绘与单张图像时设置label和title的区别
    
    fig.tight_layout() #自动调整两种图像的距离,使得两者不出现重叠,可以自行去掉会发现两天出现重叠,不美观
    
    plt.show()
    

    4.给图像中的线加入散点

    我们经常会在论文里看到下面这样的图像,那这样的线得怎么画呢?


    image

    A.显示图像

    image

    B.对应代码

    import matplotlib.pyplot as plt #导入matplotlib函数
    import numpy as np
    
    
    def f(t):
        '一个阻尼系数函数' 
        s1 = np.cos(2 * np.pi * t)
        e1 = np.exp(-t)
        return s1 * e1
    
    
    t1 = np.arange(0.0, 5.0, .2) #时间轴
    
    da = plt.plot(t1, f(t1),marker = 'o',label = 'damp')#marker表示每个点在另外用'o'来标记,如果不加marker = ,那么该图像只有散点,没有线条
    
    plt.setp(da, markersize=10) #设置da对象中标记点的属性,将marker的大小设置为10
    
    plt.legend() #展示图例
    
    plt.show()
    

    附录:贴出部分marker的属性

    image

    5.设置坐标范围及开启网格线

    A.展示图像

    image

    B.对应代码

    import matplotlib.pyplot as plt #matplotlib画图函数
    import numpy as np #加载numpy模块
    
    x = np.arange(0, 10, 0.2)
    y = np.sin(x)
    plt.plot(x, y, label='linear') 
    
    plt.xlim([-1,11])  # 设置x轴边界范围
    plt.ylim([-2,2])  # 设置y轴边界范围
    
    plt.grid(True)
    plt.grid(color='r', linestyle='--', linewidth=1,alpha=0.3) #设置网格的一些参数,根据各个参数的英文可知其作用
    
    plt.legend(loc='lower right') #让图例的位置位于右下方
    
    plt.show()
    

    附录:贴出legend的位置设置

    image

    相关文章

      网友评论

          本文标题:matplotlib看例子学画图

          本文链接:https://www.haomeiwen.com/subject/zfrcgqtx.html