Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 57 ยท Saving and Production

Saving Figures

Export Matplotlib figures with savefig: formats, dpi, bbox_inches tight, transparent backgrounds, BytesIO and base64, metadata, file size and print-ready output.

A chart that only exists on your screen is a draft. To put it in a report, a web page, a slide deck or a journal, you save it to a file. Matplotlib does this with one call, fig.savefig(...), but the right options depend on where the picture is going: a sharp logo needs a vector format, a photo-like heatmap does not, a web page wants small files, and a printer wants a high resolution.

This lesson covers the formats, dpi, trimming margins with bbox_inches="tight", transparent backgrounds, saving to memory (BytesIO) and base64 (which is how the site shows you images), metadata, file size, and print-ready output. Sizing basics come from Figure Size, DPI and Layout.

The basic call

fig.savefig("name.png") writes the figure to a file. The format is chosen from the extension: .png, .pdf, .svg, .jpg, .webp and so on, or explicitly with format="svg". Call it on the Figure (fig.savefig) rather than relying on plt.savefig, which saves whichever figure is current. Do it before plt.show(): in a script, show() may close the figure, and a following savefig can write a blank image.

Python
fig.savefig("sales.png", dpi=200, bbox_inches="tight")

Raster or vector?

Raster PNG, JPG, WebP: a grid of pixels.
Vector SVG, PDF: shapes that scale forever.

Raster size is fixed by dpi; vector size is not.

1 / 2

Formats and when to use them

Format Type Good for Watch out for
PNG raster, lossless web, slides, anything with sharp lines and text big files at high dpi
SVG vector web diagrams, logos, editing in Inkscape or Illustrator huge files for plots with many points
PDF vector LaTeX papers, print not displayed directly by browsers inside img tags
JPG raster, lossy photographs, smooth heatmaps blurry halos around text and lines; no transparency
WebP raster, lossy or lossless small web images needs Pillow built with WebP; older tools cannot open it

A good default: PNG for the web and slides, PDF (or SVG) for papers and print. Matplotlib also supports eps and ps for old publishing pipelines, tiff (via Pillow) and pgf (for LaTeX). plt.gcf().canvas.get_supported_filetypes() lists what your install can write.

Saving to memory

You do not have to write files. Any file-like object works, such as io.BytesIO, which is how web apps send images to a browser and how this site shows figures. Give the format explicitly, because there is no extension to read.

Python Savefig into memory: formats and sizes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Every format starts with a recognisable "magic" signature: \x89PNG for PNG, <?xml for SVG, %PDF for PDF and \xff\xd8 for JPEG. At 6 by 3.5 inches and 100 dpi, the PNG is 600 by 350 pixels, which is what plt.imread reports.

dpi: how many pixels

For raster formats the pixel size is figsize times dpi: a (6, 3.5) figure saved at dpi=200 is 1200 by 700 pixels. dpi= in savefig overrides the figure's own dpi for that file only, and affects nothing on vector formats, whose dpi only decides the resolution of any embedded images. Typical choices:

  • 72 to 100 for web thumbnails
  • 150 to 200 for web pages that should look sharp on high-density screens, and for slides
  • 300 for print (journals often ask for 300 to 600 for photos, and vector for line art)

Text and line widths are measured in points (1/72 inch), so they scale with dpi. Doubling the dpi gives a bigger picture with the same layout, not a more detailed layout. To change the layout, change figsize.

bbox_inches, padding and transparency

By default savefig saves the whole figure box, including any empty margin and sometimes cropping things placed outside, like a legend you moved with bbox_to_anchor. bbox_inches="tight" computes the real extent of all artists and trims or expands to fit, and pad_inches=0.1 adds a small border back. Use it almost always for individual figures; do not use it when you need all your files to have exactly the same pixel size (it changes the size depending on content).

transparent=True makes the figure and Axes backgrounds transparent, which is useful for pasting a chart on a coloured slide. If you only want the figure background changed, use facecolor="none" or facecolor="#f4f4f4". Remember that JPG has no transparency: transparent areas become black or white.

Python bbox_inches, dpi and transparency compared

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The default image clips the legend because it lies outside the figure box. The tight version includes it, and the transparent version lets the grey background show through.

Base64 and data URIs

To embed an image directly into HTML, a Markdown file or an email, encode the PNG bytes with base64 and wrap them in a data URI. This is the same mechanism notebooks and this site use to display figures.

Python
import base64, io
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=150, bbox_inches="tight")
b64 = base64.b64encode(buf.getvalue()).decode("ascii")
html = f'<img alt="Sales chart" src="data:image/png;base64,{b64}">'

Data URIs make files about a third larger than the binary image and cannot be cached separately, so they suit small charts and self-contained reports, not big galleries. In a web app, serve the bytes with the right content type (image/png) instead.

Python PNG to base64 and back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Metadata

Files can carry information about their origin. Pass metadata={...} to savefig. The keys depend on the format: PNG accepts any text key (Title, Author, Description, Software); PDF has Title, Author, Subject, Keywords, Creator, CreationDate; SVG supports Dublin Core keys like Title, Creator, Date. Passing None as a value removes a default entry (for example, {"Software": None} drops the Matplotlib version), and fixing Date makes reproducible files whose bytes do not change from run to run. The PNG text chunks can be read back with Pillow's Image.open(...).text.

Several figures in one PDF: PdfPages

A report is rarely one chart. When you need one chart per region, per month or per customer, you do not want fifty separate files. The PdfPages class collects figures as pages of a single multi-page PDF. You open it once, call pdf.savefig(fig) for each figure, and the file is finished when the with block ends.

Python
from matplotlib.backends.backend_pdf import PdfPages

with PdfPages("report.pdf", metadata={"Title": "Monthly report", "Author": "Ada"}) as pdf:
    for region in regions:
        fig, ax = make_chart(region)
        pdf.savefig(fig, bbox_inches="tight")
        plt.close(fig)          # free the memory of every page

Each pdf.savefig(fig) accepts the same options as fig.savefig, such as bbox_inches="tight", and always writes one page. plt.close(fig) after each page matters: otherwise a hundred open figures stay in memory. The metadata argument sets the document properties of the whole file (Title, Author, Subject, Keywords), and pdf.attach_note("text") adds a note to the page you just saved.

The example below runs in the browser. It writes the PDF into a BytesIO buffer instead of a file, and then reads the page count and properties back. On your computer, replace the buffer with a file name.

Python A four-page PDF with PdfPages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

get_pagecount() tells you how many pages have been written so far. The page size comes from each figure's figsize, so mixing sizes gives pages of different sizes: use one size for a tidy report (for example A4 is 8.27 by 11.69 inches). To lay several small charts on one page, make a figure with plt.subplots(3, 2) and save that figure as one page.

Tip: The class also works as a plain object without with: call pdf = PdfPages(...), then pdf.savefig(...) as needed, and close it with pdf.close(). A PDF that was never closed is incomplete and many viewers cannot open it. The with statement does this for you, even when an error occurs.

The savefig parameters at a glance

fig.savefig(fname, **kwargs) takes one required argument, the file name or file-like object, and many optional ones. These are the ones you will actually use:

Parameter Meaning
fname a path (the extension picks the format) or an object with write(), such as BytesIO
format "png", "pdf", "svg", ...; required for file-like objects, overrides the extension
dpi resolution of raster output; "figure" uses the figure's own dpi
bbox_inches, pad_inches trim to content ("tight") and the border to keep around it
facecolor, edgecolor background and frame color of the Figure; "auto" keeps the current one
transparent clear the Figure and Axes backgrounds
metadata a dictionary written into the file (see above)
pil_kwargs options passed on to Pillow for raster formats, such as {"quality": 85} for JPEG

pil_kwargs is how you trade quality for size when the format is lossy. Everything else is passed to the backend that writes the format.

Python facecolor, pad_inches and JPEG quality

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The pixel from the margin is (1.0, 0.96, 0.84), which is the cream facecolor in the 0 to 1 scale Matplotlib uses for colors.

Saving an array as an image with imsave

Sometimes you do not want a figure at all: you have a 2D array (a heatmap, a mask, a simulation frame) and want it as an image file, one array cell per pixel, with no axes, no title and no margins. plt.imsave(fname, arr, cmap=..., vmin=..., vmax=..., format=...) does exactly that. It is faster than building a figure and then saving it with savefig, and the output size is exactly the array's shape.

arr can be a 2D array (mapped through cmap, scaled between vmin and vmax, which default to the array's minimum and maximum) or an array with a shape of height by width by 3 or 4 that already holds RGB(A) colors. As with savefig, a file-like object needs format=.

Python imsave: one array cell, one pixel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The left image uses the whole colormap because the data's own range is stretched over it; on the right the same numbers cover only the lower half of the colors, so the bump looks dimmer. Fix vmin and vmax whenever images must be comparable. Reading a file back is plt.imread(fname), which returns floats between 0 and 1 for PNG.

Vector versus raster, and file size

A vector file stores instructions (move here, draw a line to there), so it scales to any size and stays crisp. A raster file stores pixels. Vector is ideal for line charts, bar charts and diagrams; but a scatter plot with 500,000 points makes an enormous SVG or PDF, because each marker is stored. Options to keep size down:

  • Use rasterized=True on heavy artists (a big scatter, an imshow, a pcolormesh) so only that layer is a bitmap inside an otherwise vector file; set the layer's resolution with savefig(dpi=...).
  • Use fig.savefig(..., format="svg") with plt.rcParams["svg.fonttype"] = "none" so text stays as text (smaller and editable) instead of outlines. Make sure the viewer has the font.
  • For PDF, plt.rcParams["pdf.fonttype"] = 42 embeds TrueType fonts so that text is selectable and editable in other programs. Journals often require this.
  • For PNG, lower dpi, simplify the figure, and run a tool such as oxipng on the result. For JPG, pass pil_kwargs={"quality": 85}; for WebP, pil_kwargs={"quality": 80}.
  • Avoid saving the same figure many times at huge dpi "just in case".

The savefig.dpi, savefig.bbox and savefig.facecolor entries in rcParams set project-wide defaults, for example plt.rcParams["savefig.dpi"] = 200 and plt.rcParams["savefig.bbox"] = "tight" once.

For print, think in physical sizes. A journal column may be 3.4 inches wide, a full page 7 inches. Set figsize to exactly that width and save at 300 dpi (raster) or as PDF (vector), then fonts at 8 to 10 points will be 8 to 10 points on paper. Resizing a figure afterwards in a document changes the font size, so avoid it. Also check that colours work in grayscale (see Designing Clear Charts), use pdf.fonttype 42 as above, and keep lines at least 0.5 pt thick.

Always call savefig before plt.show(), and call plt.close(fig) after saving in loops. A figure that is shown and closed first may save as an empty white image.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A figure of figsize (6, 4) is saved as PNG with dpi=250. What is the image size in pixels?

    Pixel size is figsize times dpi: 6 x 250 = 1500 and 4 x 250 = 1000.
  2. 2. Which format is the best choice for a line chart in a LaTeX paper?

    Vector PDF scales to any size and keeps text and lines sharp. JPG would blur lines and WebP is not widely supported in LaTeX.
  3. 3. What does bbox_inches="tight" do?

    It measures the extent of everything drawn and saves exactly that, which also rescues legends placed outside the Axes.
  4. 4. Why use savefig(buf, format="png") with an io.BytesIO buffer?

    A buffer has no file name, so you pass format explicitly. The bytes can then be sent over HTTP or encoded as a data URI.
  5. 5. Which technique keeps a huge scatter plot small inside a PDF?

    rasterized=True stores that artist as a bitmap while the rest of the figure stays vector, avoiding hundreds of thousands of marker objects.

Summary

  • fig.savefig(path_or_buffer, ...) chooses the format from the extension or format=; call it before show().
  • PNG suits the web and slides, PDF or SVG suits print and papers, JPG suits photos, WebP gives small web images.
  • Raster pixel size is figsize times dpi; vector files ignore dpi except for embedded bitmaps.
  • bbox_inches="tight", pad_inches, transparent and facecolor control the saved area and background.
  • Buffers and base64 let you embed or serve images without files; data URIs cost about a third more bytes.
  • PdfPages writes many figures as pages of one PDF: with PdfPages(...) as pdf: pdf.savefig(fig), closing each figure afterwards.
  • Use metadata, rasterized=True, font-type settings and pil_kwargs quality to control reproducibility and size.
  • For print, set figsize to the final physical size, then save at 300 dpi or as PDF.

Next, handle big datasets in Plotting Large Data Fast.