Michal
Michal

Reputation: 2007

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:

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

I also tried:

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

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

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

Upvotes: 2

Views: 2859

Answers (1)

elyase
elyase

Reputation: 40973

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:

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)

Upvotes: 1

Related Questions