【问题标题】:Add a subplot within a figure using a for loop and python/matplotlib使用 for 循环和 python/matplotlib 在图中添加子图
【发布时间】:2015-06-22 22:38:47
【问题描述】:

我认为您不需要所有代码来帮助我解决这个问题,这在 3 个月前可以工作,但现在子图没有被添加到同一个图中。即,我想要一个 2 x 2 的图,为我表中的 4 个国家/地区中的每个国家/地区填充不同的折线图。我目前得到的是一个带有 4 个空图表和 4 个后续单独图表的数字。为什么现在不能正确添加到同一个图表中?

从那时起,我已经升级了 python 和 pandas 以及我使用的 anaconda(spyder)。我目前正在使用以下版本:

Python 2.7.5 |Anaconda 1.8.0(64 位) Matplotlib 1.3.1 熊猫 0.15.2

for i, group in df.groupby('Country'):
   chrt += 1 
   fig1.add_subplot(2,2, chrt)
   #fig1.subplots_adjust(hspace=1)
   group.plot(x='Month', y='Value (USD)',title= str(i))

【问题讨论】:

  • 组是什么对象? (对于 group.plot)我不是 python 专家,但通常我在绘图时所做的更像是 ax=fig1.add_subplot(...),然后是 ax.plot( ... 一些涉及 group ... )
  • 感谢 TravisJ,我想我在使用 ax=fig1....

标签: python pandas matplotlib


【解决方案1】:

我想到了一些事情。确保 fig1chrt 已正确初始化。然后,您可以使用 ax 关键字指定它绘制在哪个轴上。

import matplotlib.pyplot as plt
fig1 = plt.figure()
chrt = 0
for i, group in df.groupby('Country'):
    chrt += 1 
    ax = fig1.add_subplot(2,2, chrt)
    group.plot(x='Month', y='Value (USD)',title=str(i), ax=ax)

【讨论】:

  • 感谢@Julien Spronck ax=ax 是我没有尝试过的技巧,仍然不明白,但它有效。
猜你喜欢
  • 2022-07-07
  • 2018-07-25
  • 2021-08-02
  • 2020-02-12
  • 2020-07-23
  • 2020-07-21
  • 1970-01-01
  • 2019-05-13
  • 1970-01-01
相关资源
最近更新 更多