Skip to main content
 首页 » 编程设计

python之如何使用matplotlib获取包含多个图形的多个窗口

2024年12月31日7傻小

我有 200 种产品,我想绘制时间与参数图表。我想出了一个代码,可以绘制 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 个子图的窗口,如下所示

请您参考如下方法:

您只需将现有代码包装在一个 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