October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

Save Matplotlib Figures as PDF in Python: The Exact Code

Use Figure.savefig("graph.pdf") for a single plot, or PdfPages to add multiple Matplotlib figures as pages in one PDF.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For one graph, call fig.savefig("graph.pdf") on its Matplotlib Figure. The .pdf extension tells Matplotlib to write a PDF. Use PdfPages when you want several figures in one multi-page PDF.

Save one Matplotlib graph as a PDF

Create a figure and axes, draw the graph, then save the figure:

As an Amazon Associate I earn from qualifying purchases.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [2, 4, 3])
ax.set(title="Example graph", xlabel="X", ylabel="Y")
fig.savefig("graph.pdf")

This writes graph.pdf in the program’s current working directory. To save elsewhere, pass a path, such as "reports/graph.pdf"; the directory must exist.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The documented Figure.savefig API infers the output format from a filename extension when you omit format. You can also specify it explicitly:

fig.savefig("graph.pdf", format="pdf")

When you set format="pdf", Matplotlib uses the filename verbatim: it does not add an extension or change one to match the format. Include .pdf in the filename if that is the intended path. A filename without an extension does not imply PDF; the current configuration reference lists PNG as the default save format.

Keep labels from being cropped

If a title, axis label, or legend sits close to the figure edge, request a tight bounding box:

fig.savefig("graph.pdf", bbox_inches="tight")

This asks Matplotlib to save the tight bounding box around the figure. Use pad_inches to adjust the padding around that box; its documented default is 0.1 inches. For example:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
fig.savefig("graph.pdf", bbox_inches="tight", pad_inches=0.2)

These options are documented in the savefig API and the Matplotlib configuration reference.

Put several figures in one PDF

Use Matplotlib’s PdfPages context manager to make a multi-page PDF. Each call to pdf.savefig(fig) adds the supplied figure as a page:

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

with PdfPages("graphs.pdf") as pdf:
    for values in ([1, 2, 3], [3, 2, 1]):
        fig, ax = plt.subplots()
        ax.plot(values)
        pdf.savefig(fig, bbox_inches="tight")
        plt.close(fig)

The with block closes the PDF when finished. The example closes each figure after adding it to help release resources, which is useful when creating many pages. The PDF backend documentation also describes optional document metadata. Its supported information keys include Title, Author, Subject, Keywords, Creator, and Producer.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose the save method by the document you need

  • One figure, one PDF: call fig.savefig("graph.pdf").
  • Several figures, several PDF pages: open PdfPages and call pdf.savefig(fig) for each figure.

savefig accepts a path-like name, a file-like object, or a backend-dependent object. Which formats are available depends on the active backend; see the API reference for details.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.