【问题标题】:matplotlib.pyplot: create a subplot of stored plotsmatplotlib.pyplot:创建存储图的子图
【发布时间】:2017-11-03 15:06:41
【问题描述】:

python 3.6 om mac matplotlib 2.1.0 使用 matplotlib.pyplot(作为 plt)

假设我有几个plt.figures(),我将它们附加到一个称为图形的列表中作为对象。当我在命令行中时:figures[0]it 为列表figures 的索引 0 生成图。 但是,我如何安排将图中的所有图都放在子图中。

# Pseudo code: 
plt.figure() 
for i, fig in enumerate(figures):   # figures contains the plots
    plt.subplot(2, 2, i+1)
    fig   # location i+1 of the subplot is filled with the fig plot element  

因此,我将创建一个 2 x 2 的网格,其中包含图中找到的每个图。

希望这是有道理的。

【问题讨论】:

    标签: python-3.x matplotlib plot


    【解决方案1】:

    图形就是图形。图形中不能有图形。通常的方法是创建一个图形,创建一个或多个子图,在子图中绘制一些东西。

    如果您想在不同的轴或图形上绘制某些东西,将绘图包装在一个以轴为参数的函数中可能是有意义的。

    然后您可以使用此函数绘制到新图形的轴或绘制到具有许多子图的图形的轴。

    import numpy as np
    import matplotlib.pyplot as plt
    
    def myplot(ax, data_x, data_y, color="C0"):
        ax.plot(data_x, data_y, color=color)
        ax.legend()
    
    x = np.linspace(0,10)
    y = np.cumsum(np.random.randn(len(x),4), axis=0)
    
    #create 4 figures
    for i in range(4):
        fig, ax = plt.subplots()
        myplot(ax, x, y[:,i], color="C{}".format(i))
    
    # create another figure with each plot as subplot
    fig, ax = plt.subplots(2,2)
    for i in range(4):
        myplot(ax.flatten()[i], x, y[:,i], color="C{}".format(i))
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2014-03-30
      • 1970-01-01
      • 2020-08-15
      • 2014-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      相关资源
      最近更新 更多