【问题标题】:How to obtain multiple windows containing multiple graphs using matplotlib?如何使用 matplotlib 获取包含多个图形的多个窗口?
【发布时间】:2019-06-09 15:04:40
【问题描述】:

我有 200 种产品,我想绘制 time vs parameter 图表。我想出了一个代码,它可以为 20 种产品绘制图表并将它们显示在一个窗口中。

我想知道是否有办法在 10 个不同的窗口中绘制 200 个图作为子图,每个窗口包含 20 个图。

我的代码

grouped = dataset.groupby('product_number')
ncols = 4
nrows = int(np.ceil(grouped.ngroups/40))
fig, axes = plt.subplots(figsize=(12,4), nrows = nrows, ncols = ncols)

for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
    grouped.get_group(key).plot(x='TimeElapsed', y='StepID', ax=ax, sharex = True, sharey = True)
    ax.set_title('product_number=%d'%key)
ax.legend()
plt.show()

这段代码给了我一个包含 20 个子图的窗口,如下所示

【问题讨论】:

    标签: python python-3.x pandas matplotlib pandas-groupby


    【解决方案1】:

    您只需将现有代码包装在一个 for 循环中,以遍历不同的图形,每个图形包含 20 个子图形。然后这里的技巧是使用索引(20*i)+key 修改键值以获取所有 200 个键。对于i=0(第一个数字),您将获得 1、2、3、... 19、20。对于 i=1(第二个数字),您将获得 21、22、23、...39、40 和以此类推。

    以下是您的代码的修改版本。我没有数据,所以我无法尝试。如果它不起作用,请告诉我。正如@DavidG 所指出的,plt.show() 应该在 for 循环之外。

    grouped = dataset.groupby('product_number')
    ncols = 4
    nrows = int(np.ceil(grouped.ngroups/40))
    
    for i in range(10):
        fig, axes = plt.subplots(figsize=(12,4), nrows = nrows, ncols = ncols)
    
        for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
            grouped.get_group((20*i)+key).plot(x='TimeElapsed', y='StepID', ax=ax, sharex = True, sharey = True)
            ax.set_title('product_number=%d'%((20*i)+key))
        ax.legend()
    plt.show() # Mind the indentation
    

    【讨论】:

    • 也许不缩进 plt.show() 以便所有数字都出现?
    猜你喜欢
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 2018-03-31
    相关资源
    最近更新 更多