Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python saving multiple figures into one PDF file

In python (for one figure created in a GUI) I was able to save the figure under .jpg and also .pdf by either using:

plt.savefig(filename1 +  '.pdf') 

or

plt.savefig(filename1 +  '.jpg') 

Using one file I would like to save multiple figures in either .pdf or .jpg (just like its done in math lab). Can anybody please help with this?

like image 533
Ahmed Niri Avatar asked Jul 22 '13 13:07

Ahmed Niri


People also ask

How do I save multiple figures as one PDF in Python?

Create a new PdfPages object. Get the number of open figures. Iterate the opened figures and save them into the file. Close the created PDF object.

How do I save multiple figures 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 save a figure as a PDF in Python?

Plot the data frame with 'o' and 'rx' style. To save the file in PDF format, use savefig() method where the image name is myImagePDF. pdf, format = ”pdf”.


2 Answers

Use PdfPages to solve your problem. Pass your figure object to the savefig method.

For example, if you have a whole pile of figure objects open and you want to save them into a multi-page PDF, you might do:

import matplotlib.backends.backend_pdf pdf = matplotlib.backends.backend_pdf.PdfPages("output.pdf") for fig in xrange(1, figure().number): ## will open an empty extra figure :(     pdf.savefig( fig ) pdf.close() 
like image 75
Mind Mixer Avatar answered Sep 17 '22 14:09

Mind Mixer


Do you mean save multiple figures into one file, or save multiple figures using one script?

Here's how you can save two different figures using one script.

>>> from matplotlib import pyplot as plt >>> fig1 = plt.figure() >>> plt.plot(range(10)) [<matplotlib.lines.Line2D object at 0x10261bd90>] >>> fig2 = plt.figure() >>> plt.plot(range(10,20)) [<matplotlib.lines.Line2D object at 0x10263b890>] >>> fig1.savefig('fig1.png') >>> fig2.savefig('fig2.png') 

...which produces these two plots into their own ".png" files: enter image description here

enter image description here

To save them to the same file, use subplots:

>>> from matplotlib import pyplot as plt >>> fig = plt.figure() >>> axis1 = fig.add_subplot(211) >>> axis1.plot(range(10)) >>> axis2 = fig.add_subplot(212) >>> axis2.plot(range(10,20)) >>> fig.savefig('multipleplots.png') 

The above script produces this single ".png" file: enter image description here

like image 39
Brett Morris Avatar answered Sep 19 '22 14:09

Brett Morris