10

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.

Stefano Potter
  • 3,467
  • 10
  • 45
  • 82
  • your indentation seems wrong ... i assume that `fig=group...` should go in your for loop – Julien Spronck Apr 03 '15 at 16:18
  • so do I understand that you want your pdf file to have about 50 pages, each page with a different figure? – Julien Spronck Apr 03 '15 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. – Stefano Potter Apr 03 '15 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 – Julien Spronck Apr 03 '15 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. – Stefano Potter Apr 03 '15 at 16:28
  • You're welcome ... Indentation is everything in python ... what is or is not in for loops, while loops, functions, classes, if statements ... is only defined by indentation. – Julien Spronck Apr 03 '15 at 16:30

1 Answers1

11

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)
Julien Spronck
  • 15,069
  • 4
  • 47
  • 55
  • Dont we need to close the pdf for each iteration – vinayak_narune Feb 09 '20 at 11:58
  • 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. – Q2Learn May 28 '20 at 16:42