Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Saving multiple figures to one PDF file in matplotlib
To save multiple matplotlib figures in one PDF file, we can use the PdfPages class from matplotlib.backends.backend_pdf. This approach allows you to create multiple plots and combine them into a single PDF document.
Basic Example
Here's how to create two figures and save them to one PDF file ?
from matplotlib import pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
# Set figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create first figure
fig1 = plt.figure()
plt.plot([2, 1, 7, 1, 2], color='red', lw=5, label='Figure 1')
plt.title('First Plot')
plt.legend()
# Create second figure
fig2 = plt.figure()
plt.plot([3, 5, 1, 5, 3], color='green', lw=5, label='Figure 2')
plt.title('Second Plot')
plt.legend()
# Save both figures to PDF
def save_multi_image(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()
filename = "multi_plots.pdf"
save_multi_image(filename)
print(f"PDF saved as: {filename}")
PDF saved as: multi_plots.pdf
Alternative Approach Using Context Manager
A cleaner approach using Python's context manager to ensure proper file closure ?
from matplotlib import pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import numpy as np
# Create sample data
x = np.linspace(0, 10, 100)
# Create multiple figures
fig1, ax1 = plt.subplots()
ax1.plot(x, np.sin(x), 'b-', label='sin(x)')
ax1.set_title('Sine Wave')
ax1.legend()
fig2, ax2 = plt.subplots()
ax2.plot(x, np.cos(x), 'r-', label='cos(x)')
ax2.set_title('Cosine Wave')
ax2.legend()
# Save to PDF using context manager
with PdfPages('functions.pdf') as pdf:
pdf.savefig(fig1)
pdf.savefig(fig2)
print("Multiple figures saved to functions.pdf")
Multiple figures saved to functions.pdf
Key Steps Summary
The process involves these main steps:
-
Import required modules:
matplotlib.pyplotandPdfPages -
Create multiple figures: Use
plt.figure()orplt.subplots() - Plot your data: Add plots, titles, and labels to each figure
- Initialize PdfPages: Create a PDF file object
-
Save figures: Use
savefig()for each figure - Close the PDF: Ensure proper file closure
Comparison of Methods
| Method | Advantage | Best For |
|---|---|---|
| Manual close | Direct control | Simple scripts |
| Context manager | Automatic cleanup | Production code |
| get_fignums() | Handles all figures | Dynamic figure count |
Conclusion
Use PdfPages with a context manager for the cleanest approach to save multiple matplotlib figures in one PDF. This ensures proper file handling and creates professional multi-page documents.
Advertisements
