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.

Community
  • 1
  • 1
Michal
  • 1,927
  • 5
  • 21
  • 27

1 Answers1

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)
elyase
  • 39,479
  • 12
  • 112
  • 119
  • Both options works very nice :) Do you know hot to apply your method to use secondary `y_axis` [example](http://stackoverflow.com/a/22448845/2669472) ? – Michal Mar 22 '14 at 09:09
  • If you wish @elyase I can post this as a separate question ? – Michal Mar 22 '14 at 13:29
  • 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. – elyase Mar 23 '14 at 00:02