Module 2 · Beginner · Matplotlib basics

Save Matplotlib charts as PNG, SVG and PDF

Save Matplotlib charts with savefig: PNG vs SVG vs PDF, dpi and size, tight bounding boxes, transparent backgrounds, saving charts in a loop, and fixes.

By theprogrammers team · · 5 min read

A chart that only lives in your notebook can't go into a report, a slide, a website or a WhatsApp message. savefig writes a chart to an image file, and a few settings decide whether it comes out sharp or blurry, with labels or cut off, the right size or tiny.

This lesson explains which file format to choose, how size and resolution work, how to fix cut-off labels, transparent backgrounds, and how to save many charts automatically.

The basic call

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.bar(["Python", "Java", "C++"], [45, 30, 25])
ax.set_title("Favourite language")
fig.savefig("languages.png")
plt.show()

The file appears in your current working directory: next to your notebook, or wherever you ran the script. Give a path to save elsewhere: fig.savefig("charts/languages.png") (the folder must exist).

Two rules:

  • Save before plt.show(). In scripts, showing closes the figure, so saving afterwards produces a blank image.
  • Prefer fig.savefig over plt.savefig, so you always save exactly the figure you mean.

Choosing a format

The file extension chooses the format:

FormatTypeBest forNotes
.pngRaster (pixels)Websites, slides, documents, messagingThe safe default; set dpi for sharpness
.svgVectorWebsites, editing in design toolsSharp at any size; small for simple charts
.pdfVectorPrinted reports, LaTeX papersSharp when printed
.jpgRaster, lossyRarely for chartsBlurs sharp lines and text; avoid

Raster images are grids of pixels; zoom in and they get blocky. Vector images store shapes and text, so they stay perfectly sharp at any size. A scatter plot with 100,000 points, though, makes a huge vector file; save those as PNG.

Size and resolution

Two settings work together:

  • figsize=(width, height) in inches, set when you create the figure.
  • dpi (dots per inch) when saving.

The image in pixels is figsize × dpi:

fig, ax = plt.subplots(figsize=(8, 5))
ax.plot([1, 2, 3], [3, 1, 2])
fig.savefig("chart_100.png", dpi=100)   # 800 × 500 pixels
fig.savefig("chart_200.png", dpi=200)   # 1600 × 1000 pixels
plt.close(fig)
UseSuggested dpi
Quick look, notebooks100 (the default)
Websites and slides150 to 200
Print300

To make text bigger relative to the chart, use a smaller figsize (or bigger fonts), not a lower dpi. Text sizes are in points, which are fixed in inches, so a smaller figure makes the same text take up more of it.

Fix cut-off labels

Long tick labels, a title or a legend outside the axes often get cropped. bbox_inches="tight" shrinks or grows the saved area to fit everything:

fig, ax = plt.subplots()
ax.barh(["Computer Science and Engineering", "Electronics and Communication",
         "Mechanical Engineering"], [420, 380, 360])
fig.savefig("depts.png", dpi=200, bbox_inches="tight")
plt.show()
A horizontal bar chart of three engineering departments with their long names fully visible on the left.

Without bbox_inches="tight", the left part of the long department names would be cut off. Calling fig.tight_layout() before saving also helps, especially with several subplots, and pad_inches=0.1 controls the margin around a tight crop.

Transparent and coloured backgrounds

fig.savefig("logo_chart.png", transparent=True)        # no background
fig.savefig("dark_slide.png", facecolor="#1e1e1e")     # a set colour

Transparent PNGs blend into coloured slides and web pages. Check that the text is still readable on the final background: black text vanishes on a dark slide.

Save many charts in a loop

Automation is a big reason to chart with Python. Here's one chart per city, saved with the city's name, in a folder that's created if needed:

from pathlib import Path

sales = {
    "Kanpur": [42, 45, 51, 55],
    "Lucknow": [38, 41, 40, 47],
    "Pune": [60, 62, 66, 71],
}
out = Path("charts")
out.mkdir(exist_ok=True)

for city, values in sales.items():
    fig, ax = plt.subplots(figsize=(6, 4))
    ax.plot(["Q1", "Q2", "Q3", "Q4"], values, marker="o")
    ax.set_title(f"{city}: quarterly sales (₹ lakh)")
    fig.savefig(out / f"{city.lower()}.png", dpi=150, bbox_inches="tight")
    plt.close(fig)        # free the memory

print(sorted(p.name for p in out.iterdir()))
['kanpur.png', 'lucknow.png', 'pune.png']

plt.close(fig) is important in loops: every open figure uses memory, and after about 20 Matplotlib starts warning you. Run this monthly, and your report charts update themselves.

Several charts in one PDF

To put many charts into one multi-page PDF, use PdfPages:

from matplotlib.backends.backend_pdf import PdfPages

with PdfPages("report.pdf") as pdf:
    for city, values in sales.items():
        fig, ax = plt.subplots()
        ax.bar(["Q1", "Q2", "Q3", "Q4"], values)
        ax.set_title(city)
        pdf.savefig(fig)
        plt.close(fig)

Each pdf.savefig(fig) adds one page.

Common problems

ProblemCauseFix
The image is blankSaved after plt.show()Save first
Labels or legend cut offContent outside the figure areabbox_inches="tight"
Blurry on slidesLow dpidpi=200 or more, or SVG
Text tiny in the imageFigure too large for its fontsSmaller figsize or bigger fonts
FileNotFoundErrorThe folder doesn't existCreate it with Path(...).mkdir(exist_ok=True)
Huge SVG or PDFThousands of points saved as vectorsSave as PNG, or use rasterized=True on the scatter
"More than 20 figures" warningFigures not closed in a loopplt.close(fig)

Practice

  1. Save a chart as a 1,200 × 800 pixel PNG.
Show the answer

Use figsize=(6, 4) and dpi=200: 6 × 200 = 1,200 and 4 × 200 = 800.

fig, ax = plt.subplots(figsize=(6, 4))
ax.plot([1, 2, 3])
fig.savefig("chart.png", dpi=200)
  1. You need a chart for a printed A4 report. Which format and settings?
Show the answer

PDF or SVG (vector) for perfectly sharp lines and text, or PNG at 300 dpi, with bbox_inches="tight". Size the figure to the space it will fill on the page, such as figsize=(6, 4).

  1. Your saved image has the legend cut off on the right. Fix it.
Show the answer

Save with fig.savefig("chart.png", bbox_inches="tight"), which expands the saved area to include the legend.

Interview questions

How do you save a Matplotlib figure, and why call it before show?

fig.savefig("name.png", dpi=200, bbox_inches="tight"). plt.show() can close or clear the figure, especially in scripts, so saving afterwards may write a blank image.

What is the difference between PNG and SVG for charts?

PNG is a raster format of fixed pixels, so it's universally supported but blurs when enlarged. SVG is a vector format that stays sharp at any size and is usually small for simple charts, but gets very large for charts with many points.

What does dpi control?

Dots per inch: combined with the figure size in inches, it sets the pixel dimensions of raster output. Higher dpi gives sharper, larger images.

What to learn next

  1. Take more control of layouts in the Matplotlib in depth module, starting with the object-oriented interface.
  2. Review every chart type in the Matplotlib tutorial for beginners.