簡體   English   中英

遍歷Groupby.unstack()項以繪制單獨的圖

[英]Iterate through Groupby.unstack() items to make separate plots

我有一個稱為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 nameseries )對([請參閱文檔]) 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應該已經是“ Year”,因為這似乎是indexname Legend默認為True 請參閱其他圖參數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM