我有一个名为 afplot 的数据框:
apple_fplot = apple_f1.groupby(['Year','Domain Category'])['Value'].sum()
afplot = apple_fplot.unstack('Domain Category')
我现在需要为 afplot 的每一列生成一个图,并且需要将每个图保存到唯一的文件名。
我一直在尝试通过 for 循环来做到这一点,(我知道效率很低),但似乎无法做到正确。
for index, column in afplot.iteritems():
plt.figure(index); afplot[column].plot(figsize=(12,6))
plt.xlabel('Year')
plt.ylabel('Fungicide used / lb')
plt.title('Amount of fungicides used on apples in the US')
plt.legend()
plt.savefig('C:/Users/User/Documents/Work/Year 3/Project/Plots/apple_fplot{}'.format(index))
我不确定我是否以正确的方式处理这个问题,但整个想法是在每次迭代时重置绘图,仅绘制下一列的线图,然后将其保存为新文件名。
最佳答案
df.iteritems()
迭代器返回 (column name
, series
) 对([参见文档])1 。所以你可以简化:
for col, data in afplot.iteritems():
ax = data.plot(title='Amount of fungicides used on apples in the US'))
ax.set_ylabel('Fungicide used / lb')
plt.gcf().savefig('C:/Users/User/Documents/Work/Year 3/Project/Plots/apple_fplot{}'.format(col))
plt.close()
xlabel
应该已经是“年份”,因为这似乎是索引
的名称
。默认情况下,Legend
为True
。请参阅additional plot parameters .
关于python - 迭代 Groupby.unstack() 项以制作单独的图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34253547/