我有一个基于groupby创建大约50个图形的代码。代码如下:

import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

with PdfPages('foo.pdf') as pdf:
   for i, group in df.groupby('station_id'):
       plt.figure()


fig=group.plot(x='year', y='Value',title=str(i)).get_figure()
pdf.savefig(fig)

当我希望所有的图形都存储在一个PDF中时,这只保存了一个图形(我系列中的最后一个)。任何帮助都将不胜感激。

最佳答案

您的代码中有一个缩进错误。由于绘图命令不在循环中,因此它将只创建最后一个绘图。

import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

with PdfPages('foo.pdf') as pdf:
   for i, group in df.groupby('station_id'):
       plt.figure()
       fig=group.plot(x='year', y='Value',title=str(i)).get_figure()
       pdf.savefig(fig)

09-17 12:48
查看更多