简体   繁体   English

使用for循环和python / matplotlib在图中添加子图

[英]Add a subplot within a figure using a for loop and python/matplotlib

I dont think you need all the code to help me with this, this was working 3 months ago but now the subplots are not getting added to the same figure. 我认为您不需要所有代码来帮助我解决这个问题,这已经在3个月前开始工作了,但是现在子图并没有添加到同一图中。 ie I want one figure 2 by 2 populated with a different line chart for each of the 4 countries in my table. 即,我希望表格中的4个国家/地区中的每个图表都2比2填充不同的折线图。 what i currently get is one figure with 4 empty charts and 4 subsequent individual charts. 我目前得到的是一个带有4个空图表和4个后续单个图表的图形。 why is this not getting adding to the same chart correctly now? 为什么现在不能正确添加到同一图表?

I have upgraded python and pandas since that time and anaconda(spyder) which I use. 从那时起,我已经升级了python和pandas以及我使用的anaconda(spyder)。 I am currently using the following versions: 我目前正在使用以下版本:

Python 2.7.5 |Anaconda 1.8.0 (64-bit) Matplotlib 1.3.1 Pandas 0.15.2 Python 2.7.5 | Anaconda 1.8.0(64位)Matplotlib 1.3.1 Pandas 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))

A few things come to mind. 我想到了几件事。 Make sure fig1 and chrt are well initialized. 确保fig1chrt非常初始化。 Then, you can specify which axis it plots on with the ax keyword. 然后,您可以使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM