【问题标题】:Make subplots using a for loop使用 for 循环制作子图
【发布时间】:2021-01-29 05:54:03
【问题描述】:

我正在尝试使用 matplotlib 子图将 6 个图形绘制到一个文件中。 我设法做到了这一点,但我的代码非常重复(见下文),所以我试图更改代码以适应 for 循环。我的 x 轴对于所有图都是相同的,我想遍历 y 值和标签的压缩列表中的 i,j,并绘制 6 个子图。

p1 = [p1_atm, p1_bio, p1_soil, p1_so, p1_do, p1_geo]
labels = ["Atmosphere", "Biosphere", "Soils", "Shallow Ocean", "Deep Ocean", "Geosphere"]
p1_labels = zip(p1, labels)
#%% 
filename1 = 'no_emissions_pools.png'

fig, axs = plt.subplots(6,1, figsize=(8,6))
for i,j in list(p1_labels):
    k = 0
    axs[k].plot(t_2020, i, color = '#6d9eeb', label = j)
    axs[k].set(xlim=[min(t_2020),max(t_2020)+1], ylim=[min(i), max(i)], ylabel = 'PgC')
    axs[k].legend()
    k = k + 1
    
fig.tight_layout()
plt.savefig(filename1,bbox_inches='tight')
plt.show()
plt.close()

我没有收到任何错误,我只是得到空图。任何有关如何解决此问题的想法将不胜感激。以下是有效的原始重复代码(颜色并不重要,图形绘制成 3x2 还是 6x1 形状也没有关系):

fig, axs = plt.subplots(3, 2, figsize = (8,8))
axs[0, 0].plot(t, atm, color = '#6d9eeb', label = 'Atmosphere')
axs[0,0].set(xlim=[min(t),max(t)+1], ylim=[min(atm), max(atm)], ylabel = 'PgC')
axs[0,0].legend()

axs[0,1].plot(t, bio, color = '#93c47d', label = 'Biosphere')
axs[0,1].set(xlim=[min(t),max(t)+1], ylim=[min(bio), max(bio)])
axs[0,1].legend()
                    
axs[1,0].plot(t, soil, color = '#dd7e6b', label = 'Soil')
axs[1,0].set(xlim=[min(t),max(t)+1], ylim=[min(soil), max(soil)],ylabel = 'PCg')
axs[1,0].legend()
    
axs[1,1].plot(t, so, color = '#9fc5e8', label = 'Shallow Ocean')
axs[1,1].set(xlim=[min(t),max(t)+1], ylim=[min(so), max(so)])
axs[1,1].legend()

axs[2,0].plot(t, do, color = '#45818e', label = 'Deep Ocean')
axs[2,0].set(xlim=[min(t),max(t)+1], ylim=[min(do), max(do)], xlabel = 'Year', ylabel = 'PCg')
axs[2,0].legend()

axs[2,1].plot(t, geo, color = '#906861', label = 'Geosphere')
axs[2,1].set(xlim=[min(t),max(t)+1],ylim=[min(geo), max(geo)], xlabel = 'Year')
axs[2,1].legend()
    
fig.tight_layout()
plt.savefig(filename,bbox_inches='tight')
plt.show()
plt.close()

【问题讨论】:

  • 提示:k 在循环中的每一轮都有什么价值?
  • 第二个@TurePålsson,想想你在哪里分配k的初始值
  • 谢谢,我将 k =0 移到了循环之外,但我仍然得到空图 @TurePålsson

标签: python for-loop matplotlib plot subplot


【解决方案1】:

我找到了一个解决方案,以防其他人想要参考这个。所以基本上 axs.flatten 通过使 axs 可迭代来工作,因此不需要 k 计数器。基本上我压缩了循环所需的所有变量,包括轴,并且循环工作:

    for p,l,c,ax in zip(px,labels,colors,axs.flatten()):
        ax.plot(t, p, color = c, label = l)
        ax.set(xlim=[min(t),max(t)+1], ylim=[min(p), max(p)], ylabel = 'PgC')
        ax.legend()

    fig.tight_layout()
    plt.figtext(0.55,0,'Year') 
    plt.savefig(filename,bbox_inches='tight')
    plt.show()

【讨论】:

    猜你喜欢
    • 2015-06-23
    • 2020-09-25
    • 2013-02-19
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    相关资源
    最近更新 更多