How to Save Matplotlib Plots#

This guide shows how to save hvPlot plots created with the Matplotlib backend as static images (PNG, PDF, SVG), and how to control their resolution. Matplotlib renders images directly in Python, which makes it a good fit for scripts and batch jobs that save many plots.

Tip

Not sure whether to save with Bokeh or Matplotlib? See How to Choose a Backend for Saving Plots.

Save as a PNG image#

Load the Matplotlib backend with hvplot.extension('matplotlib'), then save the plot with hvplot.save, the format is inferred from the file extension:

import hvplot.pandas  # noqa

hvplot.extension('matplotlib')

penguins = hvplot.sampledata.penguins("pandas")

plot = penguins.hvplot.scatter(
    x='bill_length_mm',
    y='bill_depth_mm',
    by='species',
    title="Penguin Bill Dimensions",
    xlabel="Bill length (mm)",
    ylabel="Bill depth (mm)",
)
plot
hvplot.save(plot, 'penguins.png')

Set the resolution (DPI)#

Images are saved at 72 DPI by default, which is fine on screen but too low for print. Pass dpi to hvplot.save to change it:

hvplot.save(plot, 'penguins_300dpi.png', dpi=300)

The figure keeps the same layout, only the number of pixels changes:

from PIL import Image

for filename in ['penguins.png', 'penguins_300dpi.png']:
    print(filename, Image.open(filename).size)
penguins.png (629, 263)
penguins_300dpi.png (2633, 1092)

To set the DPI once for all the plots saved (and displayed) in a session, use hvplot.output(dpi=300).

Save in a vector format#

PDF and SVG files can be scaled without losing quality, which is usually preferred for papers and reports:

hvplot.save(plot, 'penguins.pdf')
hvplot.save(plot, 'penguins.svg')

Layouts like plot1 + plot2 are saved in the same way.

See also

See also

Hide code cell content

from pathlib import Path

for filename in ['penguins.png', 'penguins_300dpi.png', 'penguins.pdf', 'penguins.svg']:
    Path(filename).unlink(missing_ok=True)
This web page was generated from a Jupyter notebook and not all interactivity will work on this website.