Saving all the open Matplotlib figures in one file at once

Matplotlib allows you to save multiple open figures into a single PDF file using the PdfPages class from matplotlib.backends.backend_pdf. This is useful when you want to create a multi-page report or documentation.

Basic Approach

To save all open Matplotlib figures in one PDF file, follow these steps:

  • Create multiple figures using plt.figure()
  • Plot data on each figure
  • Use PdfPages to create a PDF file
  • Get all figure numbers with plt.get_fignums()
  • Save each figure to the PDF file
  • Close the PDF file

Example

from matplotlib import pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

# Set figure size and layout
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create first figure
fig1 = plt.figure()
plt.plot([2, 1, 7, 1, 2], color='red', lw=5)
plt.title('Red Line Plot')

# Create second figure
fig2 = plt.figure()
plt.plot([3, 5, 1, 5, 3], color='green', lw=5)
plt.title('Green Line Plot')

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.pdf"
save_multi_image(filename)
print(f"All figures saved to {filename}")
All figures saved to multi.pdf

How It Works

The save_multi_image() function:

  • PdfPages(filename) creates a PDF file object
  • plt.get_fignums() returns a list of all open figure numbers
  • plt.figure(n) activates each figure by number
  • fig.savefig(pp, format='pdf') saves the figure to the PDF
  • pp.close() finalizes and closes the PDF file

Alternative Method with Context Manager

You can use a context manager for automatic file closing:

from matplotlib import pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

# Create figures
fig1 = plt.figure()
plt.plot([1, 2, 3, 4], [1, 4, 2, 3], 'b-', lw=3)
plt.title('Blue Line')

fig2 = plt.figure()
plt.plot([1, 2, 3, 4], [3, 1, 4, 2], 'r-', lw=3)
plt.title('Red Line')

# Save using context manager
filename = "figures_context.pdf"
with PdfPages(filename) as pdf:
    for fig_num in plt.get_fignums():
        fig = plt.figure(fig_num)
        pdf.savefig(fig)

print(f"Figures saved using context manager to {filename}")
Figures saved using context manager to figures_context.pdf

Key Points

  • The PDF will contain one page per figure
  • Figures are saved in the order they were created
  • The context manager approach automatically handles file closing
  • You can specify additional parameters like dpi and bbox_inches in savefig()

Conclusion

Use PdfPages with plt.get_fignums() to save all open Matplotlib figures to a single PDF file. The context manager approach is recommended for automatic resource management.

Updated on: 2026-03-25T23:20:44+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements