Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving multiple figures to one pdf file in matplotlib

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.

like image 401
Stefano Potter Avatar asked Apr 03 '15 16:04

Stefano Potter


People also ask

How do I save a figure in matplotlib PDF?

To save the file in PDF format, use savefig() method where the image name is myImagePDF. pdf, format = ”pdf”. To show the image, use the plt. show() method.

How do you save multiple graphs in Python?

Create a user-defind function, save_multi_image, and call it to save all the open matplotlib figures in one file at once. Create a new PdfPages object, pp. Get the number of open figures. Iterate the opened figures and save them into a file.

How do I show multiple plots in matplotlib?

To draw multiple plots using the subplot() function from the pyplot module, you need to perform two steps: First, you need to call the subplot() function with three parameters: (1) the number of rows for your grid, (2) the number of columns for your grid, and (3) the location or axis for plotting.


1 Answers

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)
like image 169
Julien Spronck Avatar answered Oct 25 '22 13:10

Julien Spronck