Python saving multiple figures into one PDF file
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()
Saving multiple figures to one pdf file in matplotlib
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)
Saving multiple combined-swarm-&-box plots into one pdf file
If you would like to save them together in a panel, replace the for-loop with the following:
fig, axs = plt.subplots(len(col_ids), 1)
sns.set(style="darkgrid")
for i in range(len(col_ids)):
sns.boxplot(x='Groups', y=df[col_ids[i]], data=df, ax=axs[i])
sns.swarmplot(x='Groups', y=df[col_ids[i]], data=df, color="grey", ax=axs[i])
plt.show()
After that you should be able to save them to one PDF.
Jupyter Notebook Save Multiple Plots As One PDF
For matplotlib
you can create subplots
inside the same figure
and use plt.savefig
to save as PDF or PNG. Based on this documentation you can:
import matplotlib.pyplot as plt
import numpy as np
# Some example data to display
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
fig, axs = plt.subplots(2, 2, figsize=(30, 15))
axs[0, 0].plot(x, y)
axs[0, 0].set_title('Axis [0, 0]', fontsize = 20)
axs[0, 0].set_xlabel('x-label for [0,0] plot', fontsize=18)
axs[0, 0].set_ylabel('y-label for [0,0] plot', fontsize=18)
axs[0, 1].plot(-x, y, 'tab:orange')
axs[0, 1].set_title('Axis [0, 1]', fontsize = 20)
axs[1, 0].plot(x, -y, 'tab:green')
axs[1, 0].set_title('Axis [1, 0]', fontsize = 20)
axs[1, 1].plot(x, 2*y, 'tab:red')
axs[1, 1].set_title('Axis [1, 1]', fontsize = 20)
# .pdf for your case, default .png
plt.savefig(r'yourpath\fig1.pdf', bbox_inches='tight', dpi=300)
Rearrange your plots how you like and set figsize
and fontsize
to make the output PDF readable. Here you'd have this downloaded as single-paged PDF:
Check here for sns.subplot
and use savefig
again.
If you want to save figures created in different cells inside your notebook (in seperate PDF pages) try something like this:
fig1= plt.figure(...)
plt.plot(...)
fig2= plt.figure(...)
plt.plot(...)
from matplotlib.backends.backend_pdf import PdfPages
def multiple_figues(filename):
pp = PdfPages(filename)
fig_nums = plt.get_fignums()
figs = [plt.figure(n) for n in fig_nums]
for fig in figs:
fig.savefig(pp, format='pdf')
pp.close()
Writing multiple matplotlib figures to PDF file
All the figures are being written to the file but only the last page was being displayed. I had to use a PyPDF2 to save and display all the pages.
The implementation is below:
from PyPDF2 import PdfFileReader, PdfFileWriter
writer = PdfFileWriter()
for fig in f_list:
decoded_data = base64.b64decode(fig)
reader = PdfFileReader(io.BytesIO(decoded_data)) # convert the figure to a stream object
writer.addPage(reader.getPage(0))
with open('result.pdf', 'wb') as pdf_file:
writer.write(pdf_file)
Related Topics
Why Doesn't 2._Add_(3) Work in Python
How to Run a Python Script in a Web Page
Sys.Argv[1], Indexerror: List Index Out of Range
Trying to Delay a Specific Function for Spawning Enemy After a Certain Amount of Time
Python: Sort Function Breaks in the Presence of Nan
Convert Bytes to Bits in Python
How to Print Utf-8 Encoded Text to the Console in Python < 3
How to Open a File Through Python
How to Add Hours to Current Time in Python
Catch Exception and Continue Try Block in Python
How to Use 'Cv2.Findcontours' in Different Opencv Versions
Add Column with Number of Days Between Dates in Dataframe Pandas