2

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

  • one plot per page,
  • four plots per page.

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.

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Both options works very nice :) Do you know hot to apply your method to use secondary y_axis example ?
If you wish @elyase I can post this as a separate question ?
I would recommend that, I don't know when I will be in a computer again and in the mid time somebody else could help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.