TExcelTAD
Home › Matplotlib › Saving Figures

Saving Figures

A chart is usually made to end up somewhere else: a report, a slide, a web page. fig.savefig() (or plt.savefig()) writes a figure to a file in formats such as PNG, SVG and PDF, with control over resolution, margins and background.

savefig() and file paths

On your own computer you pass a file name. The extension picks the format:

python
fig.savefig("sales.png")                  # raster image, good for the web
fig.savefig("sales.svg")                  # vector, scales without blurring
fig.savefig("sales.pdf")                  # vector, good for print and LaTeX
fig.savefig("plots/sales.png", dpi=200)   # relative path: the folder must exist
fig.savefig(r"C:\Users\ana\Desktop\sales.png")   # absolute path on Windows

A relative path like "plots/sales.png" is resolved from the current working directory, which is the folder you started Python from, not necessarily the folder of your script. If the folder doesn't exist you get a FileNotFoundError; create it first with os.makedirs("plots", exist_ok=True) or pathlib.Path("plots").mkdir(exist_ok=True).

Note: Call savefig() before plt.show(). In a script, show() blocks, and once the window is closed the figure may be destroyed, so saving afterwards produces an empty image.

Saving to memory with io.BytesIO

The playground has no file system to save into, but savefig also accepts any file-like object. An io.BytesIO buffer collects the bytes in memory. Web servers use exactly this to send a chart without touching the disk:

python · try it yourself
import io
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(5, 3))
ax.plot([1, 2, 3, 4], [3, 1, 4, 2], marker="o")
ax.set_title("Saved to memory")

buffer = io.BytesIO()
fig.savefig(buffer, format="png")
data = buffer.getvalue()

print("PNG size:", len(data), "bytes")
print("Starts with the PNG signature:", data[:8] == b"\x89PNG\r\n\x1a\n")
plt.show()
PNG size: 19625 bytes
Starts with the PNG signature: True

With a buffer there's no extension, so pass format= explicitly.

Resolution: dpi

A figure's size is set in inches; dpi (dots per inch) converts it to pixels. A 5 × 3 inch figure at 100 dpi is 500 × 300 pixels; at 200 dpi it is 1000 × 600. Higher dpi means sharper images and bigger files:

python · try it yourself
import io
import struct
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(5, 3))
ax.bar(["A", "B", "C"], [4, 7, 5])

for dpi in [72, 100, 200]:
    buf = io.BytesIO()
    fig.savefig(buf, format="png", dpi=dpi)
    png = buf.getvalue()
    width, height = struct.unpack(">II", png[16:24])   # read the size from the PNG header
    print(f"dpi={dpi:<3} -> {width} x {height} px")

plt.close(fig)
dpi=72  -> 360 x 216 px
dpi=100 -> 500 x 300 px
dpi=200 -> 1000 x 600 px

plt.close(fig) frees the figure; that's why no chart is shown under this example. Closing figures you only save is good practice in scripts that create many of them.

Formats compared

Vector formats store shapes instead of pixels, so they stay sharp at any zoom level. Their size depends on the number of drawn elements, not the dpi:

python · try it yourself
import io
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 200)
fig, ax = plt.subplots(figsize=(5, 3))
ax.plot(x, np.sin(x))
ax.plot(x, np.cos(x))

for fmt in ["png", "svg", "pdf"]:
    buf = io.BytesIO()
    fig.savefig(buf, format=fmt)
    print(f"{fmt}: saved, starts with {buf.getvalue()[:5]!r}")

plt.close(fig)
png: saved, starts with b'\x89PNG\r'
svg: saved, starts with b'<?xml'
pdf: saved, starts with b'%PDF-'
Format Type Best for
PNG raster web pages, slides, chat; use dpi=150–300
JPG raster, lossy photos, not recommended for charts (blurry edges)
SVG vector web pages that zoom, editing in Inkscape/Illustrator
PDF vector printing, LaTeX documents

Margins, background and transparency

Argument Effect
bbox_inches="tight" crop the extra white space around the figure
pad_inches=0.1 padding kept when cropping
transparent=True transparent background
facecolor="white" background colour of the saved figure
metadata={...} title, author, etc. stored in the file
python · try it yourself
import io
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(5, 3))
ax.plot([0, 1, 2], [0, 1, 0])
ax.set_title("Cropped vs. full")

sizes = {}
for name, kwargs in {"full": {}, "tight": {"bbox_inches": "tight"},
                     "transparent": {"transparent": True}}.items():
    buf = io.BytesIO()
    fig.savefig(buf, format="png", **kwargs)
    sizes[name] = len(buf.getvalue())

for name, size in sizes.items():
    print(f"{name:<12} {size:>6} bytes")
plt.show()
full          18271 bytes
tight         17971 bytes
transparent   13799 bytes

The exact byte counts depend on the Matplotlib version and fonts, but the pattern holds: cropping removes empty pixels, and a transparent background changes the colour data that has to be stored.

Tip: For publications, use fig.savefig("figure.pdf", bbox_inches="tight"). For the web, fig.savefig("figure.png", dpi=200, bbox_inches="tight") gives crisp images on high-resolution screens.

Test yourself

Why should savefig() come before plt.show() in a script?

  1. savefig is faster
  2. After show() returns, the figure may already be closed, so the saved image could be blank
  3. show() deletes the file
  4. It doesn't matter

A figure is 6 × 4 inches. How many pixels wide is the PNG saved with dpi=150?

  1. 600
  2. 900
  3. 150
  4. 1200

Which format stays sharp at any zoom level?

  1. PNG
  2. JPG
  3. SVG
  4. BMP