12

I have a code that creates about 50 graphs based on groupby. The code looks like this:

import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

with PdfPages('foo.pdf') as pdf:
   for i, group in df.groupby('station_id'):
       plt.figure()


fig=group.plot(x='year', y='Value',title=str(i)).get_figure()
pdf.savefig(fig)

This is saving only one figure, (the last one in my series) when I would like all of my figures to be stored into one pdf. Any help would be appreciated.

6
  • your indentation seems wrong ... i assume that fig=group... should go in your for loop Commented Apr 3, 2015 at 16:18
  • so do I understand that you want your pdf file to have about 50 pages, each page with a different figure? Commented Apr 3, 2015 at 16:18
  • That is correct. I guess I wouldn't mind having multiple figures per page either, but my intention with the code above is to have one figure per page. My indentation may be wrong, I am pretty new to python still. Commented Apr 3, 2015 at 16:21
  • it might run without error but it will only create the last plot if the plotting command is not in the loop Commented Apr 3, 2015 at 16:23
  • Thank you! I see what you mean about the indents, that also helps me with why my axis names were not working correctly. I need to read up more on loop structures. Commented Apr 3, 2015 at 16:28

1 Answer 1

13

There is an indentation error in your code. Since your plotting command was not in the loop, it will only create the last plot.

import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

with PdfPages('foo.pdf') as pdf:
   for i, group in df.groupby('station_id'):
       plt.figure()
       fig=group.plot(x='year', y='Value',title=str(i)).get_figure()
       pdf.savefig(fig)
Sign up to request clarification or add additional context in comments.

2 Comments

Dont we need to close the pdf for each iteration
No. The with statement is a control-flow structure whose basic structure is: with expression [as variable]: with-block This ensures that the file will be closed when control leaves the block. The with statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed.

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.