美文网首页
matplotlib一张画布中有多个子图的绘图实践

matplotlib一张画布中有多个子图的绘图实践

作者: LabVIEW_Python | 来源:发表于2021-01-31 05:40 被阅读0次

    上一节了解了一张画布中只有一个子图绘图方法后,现在来讨论一张画布中有多个子图的绘图实践,是实现方式也是分:

    • Pyplot风格,用plot.subplot()函数实现
    • OO风格,用对应子图axes的方法实现
      pyplot风格范例代码如下所示
    import matplotlib.pyplot as plt 
    import numpy as np 
    
    x = np.linspace(0,2,200)
    
    fig, ax = plt.subplots(2,2) # 手动创建一个figure和四个ax对象
    
    plt.subplot(2,2,1) # Add a subplot to the current figure
    plt.plot(x, x, color='blue', label='Linear') # 绘制第一个子图
    plt.xlabel('x-axis')
    plt.ylabel('y-axis')
    plt.legend() # 开启图例
    
    plt.subplot(2,2,2)
    plt.plot(x, x**2, color='red', label='Quadratic') # 绘制第二个子图
    plt.xlabel('x-axis')
    plt.ylabel('y-axis')
    plt.legend() # 开启图例
    
    plt.subplot(2,2,3)
    plt.plot(x, x**3, color='green', label='Cubic') # 绘制第三个子图
    plt.xlabel('x-axis')
    plt.ylabel('y-axis')
    plt.legend() # 开启图例
    
    plt.subplot(2,2,4)
    plt.plot(x, np.log(x), color='purple', label='log') # 绘制第四个子图
    plt.xlabel('x-axis')
    plt.ylabel('y-axis')
    plt.legend() # 开启图例
    
    fig.suptitle("Simple plot demo with one figure and one axes")
    
    plt.show() # 展示绘图
    

    OO风格范例代码如下所示

    import matplotlib.pyplot as plt 
    import numpy as np 
    
    x = np.linspace(0,2,200)
    
    fig, ax = plt.subplots(2,2) # 手动创建一个figure和四个ax对象
    
    ax[0,0].plot(x, x, color='blue', label='Linear') # 绘制第一个子图
    ax[0,0].set_xlabel('x-axis')
    ax[0,0].set_ylabel('y-axis')
    ax[0,0].legend() # 开启图例
    
    ax[0,1].plot(x, x**2, color='red', label='Quadratic') # 绘制第二个子图
    ax[0,1].set_xlabel('x-axis')
    ax[0,1].set_ylabel('y-axis')
    ax[0,1].legend() # 开启图例
    
    ax[1,0].plot(x, x**3, color='green', label='Cubic') # 绘制第三个子图
    ax[1,0].set_xlabel('x-axis')
    ax[1,0].set_ylabel('y-axis')
    ax[1,0].legend() # 开启图例
    
    ax[1,1].plot(x, np.log(x), color='purple', label='log') # 绘制第四个子图
    ax[1,1].set_xlabel('x-axis')
    ax[1,1].set_ylabel('y-axis')
    ax[1,1].legend() # 开启图例
    
    fig.suptitle("Simple plot demo with one figure and one axes")
    
    plt.show() # 展示绘图
    
    运行结果: 多个子图的绘图实践

    相关文章

      网友评论

          本文标题:matplotlib一张画布中有多个子图的绘图实践

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