In this article, we will discuss how to save multiple matplotlib figures in a single PDF file using Python. We can use the PdfPages class's savefig() method to save multiple plots in a single pdf.Matplotlib plots can simply be saved as PDF files with the .pdf extension. This saves Matplotlib-generated figures in a single PDF file named Save multiple plots as PDF.pdf in the current working directory.
Installation
pip install matplotlib
Stepwise Implementation
To come up with a solution, we will follow a few steps.
Step 1: Import necessary files.
Python3frommatplotlibimportpyplotaspltfrommatplotlib.backends.backend_pdfimportPdfPages
Step 2: Set up the figure size and adjust the padding between and around the subplots.
Python3plt.rcParams["figure.figsize"]=[7.00,3.50]plt.rcParams["figure.autolayout"]=True
Step 3:We will consider 3 plots, so let's name them fig1, fig2, and fig3 usingplt.figure().
Python3fig1=plt.figure()fig2=plt.figure()Fig3=plt.figure()
Step 4:Plot the first line using theplt.plot() method.
Python3plt.plot([17,45,7,8,7],color='orange')plt.plot([13,25,1,6,3],color='blue')plt.plot([22,11,2,1,23],color='green')
Step 5:Create a function to save multiple images in a PDF file let's say save_image().
Python3defsave_image(filename):# PdfPages is a wrapper around pdf# file so there is no clash and# create files with no error.p=PdfPages(filename)# get_fignums Return list of existing# figure numbersfig_nums=plt.get_fignums()figs=[plt.figure(n)forninfig_nums]# iterating over the numbers in listforfiginfigs:# and saving the filesfig.savefig(p,format='pdf')# close the objectp.close()
Complete Code
Python3importmatplotlibfrommatplotlibimportpyplotaspltfrommatplotlib.backends.backend_pdfimportPdfPages# customizing runtime configuration stored# in matplotlib.rcParamsplt.rcParams["figure.figsize"]=[7.00,3.50]plt.rcParams["figure.autolayout"]=Truefig1=plt.figure()plt.plot([17,45,7,8,7],color='orange')fig2=plt.figure()plt.plot([13,25,1,6,3],color='blue')Fig3=plt.figure()plt.plot([22,11,2,1,23],color='green')defsave_image(filename):# PdfPages is a wrapper around pdf# file so there is no clash and create# files with no error.p=PdfPages(filename)# get_fignums Return list of existing# figure numbersfig_nums=plt.get_fignums()figs=[plt.figure(n)forninfig_nums]# iterating over the numbers in listforfiginfigs:# and saving the filesfig.savefig(p,format='pdf')# close the objectp.close()# name your Pdf filefilename="multi_plot_image.pdf"# call the functionsave_image(filename)
Output:
Now after you run the code you can see on your local directory that a pdf containing all three plots will be saved in a pdf named "multi_plot_image.pdf".