简体   繁体   English

绘制并按功能将多个图形分组保存为pdf

[英]Plot and save multiple figures of group by function as pdf

I would like to create one pdf file with 12 plots, in two options: 我想用两个选项创建一个包含12个图的pdf文件:

  • one plot per page, 每页一张图,
  • four plots per page. 每页四个图。

Using plt.savefig("months.pdf") saves only last plot. 使用plt.savefig("months.pdf")仅保存最后的绘图。

MWE: 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()

I also tried: 我也尝试过:

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(15, 10))

after the group.plot but this produced four blank plots... group.plot之后,但这产生了四个空白图...

I have found an example of PdfPages but I don't know how to implement this. 我已经找到了PdfPages的示例,但是我不知道如何实现。

To save a plot in each page use: 要在每个页面中保存图,请使用:

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)

In order to put 4 plots in a page you need to first build a fig with 4 plots and then save it: 为了在页面中放置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)

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

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