我想创建一个包含12个图的pdf文件,分为两个选项:
使用plt.savefig("months.pdf")
仅保存最后一个图。
MWE:
import pandas as pd
index=pd.date_range('2011-1-1 00:00:00', '2011-12-31 23:50:00', freq='1h')
df=pd.DataFrame(np.random.randn(len(index),3).cumsum(axis=0),columns=['A','B','C'],index=index)
df2 = df.groupby(lambda x: x.month)
for key, group in df2:
group.plot()
我也尝试过:
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(15, 10))
在group.plot
之后,但这产生了四个空白图......
我找到了PdfPages的示例,但我不知道如何实现这一点。
答案 0 :(得分:1)
要在每个页面中保存图表,请使用:
from matplotlib.backends.backend_pdf import PdfPages
# create df2
with PdfPages('foo.pdf') as pdf:
for key, group in df2:
fig = group.plot().get_figure()
pdf.savefig(fig)
为了在页面中放置4个图,您需要首先构建一个带有4个图的图,然后保存它:
import matplotlib.pyplot as plt
from itertools import islice, chain
def chunks(n, iterable):
it = iter(iterable)
while True:
chunk = tuple(islice(it, n))
if not chunk:
return
yield chunk
with PdfPages('foo.pdf') as pdf:
for chunk in chunks(4, df2):
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(12, 4))
axes = chain.from_iterable(axes) # flatten 2d list of axes
for (key, group), ax in zip(chunk, axes):
group.plot(ax=ax)
pdf.savefig(fig)