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:

  1. Import required modules: matplotlib.pyplot and PdfPages
  2. Create multiple figures: Use plt.figure() or plt.subplots()
  3. Plot your data: Add plots, titles, and labels to each figure
  4. Initialize PdfPages: Create a PDF file object
  5. Save figures: Use savefig() for each figure
  6. 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.

Updated on: 2026-03-26T15:01:48+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements