按功能绘制多个分组图并将其保存为pdf [英] Plot and save multiple figures of group by function as pdf

查看:62
本文介绍了按功能绘制多个分组图并将其保存为pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个包含 12 个图的 pdf 文件,有两种选择:

I would like to create one pdf file with 12 plots, in two options:

  • 每页一个图,
  • 每页四幅图.

使用 plt.savefig("months.pdf") 仅保存最后一个绘图.

Using plt.savefig("months.pdf") saves only last plot.

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 之后,但这产生了四个空白图...

after the group.plot but this produced four blank plots...

我找到了一个 PdfPages 的示例,但我不知道如何实现.

I have found an example of PdfPages but I don't know how to implement this.

推荐答案

要在每个页面中保存一个绘图,请使用:

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)

为了在一个页面中放置 4 个图,您需要先构建一个带有 4 个图的无花果,然后保存它:

In order to put 4 plots in a page you need to first build a fig with 4 plots and then save it:

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)

这篇关于按功能绘制多个分组图并将其保存为pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆