How to Save a Plot in Plotnine (ggsave and .save())

Save Plotnine charts to PNG, SVG, PDF, or JPEG with .save() or ggsave, and control the size, DPI, transparency, and multi-page output.

Save a Plotnine chart with its .save() method: plot.save("chart.png", width=7, height=4, dpi=200). The file extension picks the format, and width and height are in inches unless you set units. The examples use plotnine 0.15.

Quick Example

import numpy as np
import pandas as pd
from plotnine import aes, geom_area, geom_line, ggplot, labs, theme_minimal

rng = np.random.default_rng(45)
distance = np.linspace(0, 12, 160)
climb = 520 * np.exp(-((distance - 7.2) / 2.8) ** 2)
trail = pd.DataFrame({
    "km": distance,
    "elevation": 840 + climb + np.cumsum(rng.normal(0, 3, 160)),
})

plot = (
    ggplot(trail, aes("km", "elevation"))
    + geom_area(fill="#588157", alpha=0.35)
    + geom_line(color="#344e41", size=1)
    + labs(title="Ridge trail elevation", x="Distance (km)", y="Elevation (m)")
    + theme_minimal()
)

plot.save("trail.png", width=7, height=4, dpi=200)

Plotnine area chart of trail elevation over 12 kilometers, peaking near the 7 kilometer mark

The result is a 1400 × 800 pixel PNG: 7 inches × 200 DPI by 4 inches × 200 DPI.

.save() vs ggsave()

They are the same function. ggsave is an alias for ggplot.save, so the plot is the first argument, the reverse of R's ggsave(filename, plot).

from plotnine import ggsave

plot.save("trail.png", verbose=False)
ggsave(plot, "trail.png", verbose=False)
Argument Default What it does
filename plotnine-save-<hash>.pdf path of the output file
format from the extension needed for file-like objects and names without an extension
path none folder to put the file in
width, height figure_size from the theme, 6.4 × 4.8 size, and you must give both or neither
units "in" "in", "cm", or "mm"
dpi theme dpi, 100 resolution of raster formats
limitsize True refuse sizes over 25 inches
verbose True warn with the size and filename

Each save prints two PlotnineWarning lines, "Saving 7 x 4 in image." and the filename. Pass verbose=False to silence them. The folder must already exist, so create it first with Path("charts").mkdir(exist_ok=True).

How do width, height, and DPI change the chart?

width and height set the physical size, and dpi sets how many pixels go into each inch. Text and lines are measured in points, so on a smaller figure they take up more of the image. These two files are both 800 × 480 pixels:

plot.save("small.png", width=4, height=2.4, dpi=200, verbose=False)
plot.save("large.png", width=8, height=4.8, dpi=100, verbose=False)

Two exports with equal pixel dimensions: the 4 inch figure at 200 DPI has text twice as large as the 8 inch figure at 100 DPI

To make text bigger, shrink width and height and raise dpi. To get more pixels without changing the look, raise dpi alone. For print, journals commonly ask for 300 DPI at the final width, which you can give in centimeters:

plot.save("print.png", width=17, height=9, units="cm", dpi=300, verbose=False)

Passing pixel values as width raises an error such as Dimensions (width=1400, height=800) exceed 25 inches. Divide by the DPI instead.

You can also store the size on the plot, which applies to saving and to notebook display:

from plotnine import theme

wide = plot + theme(figure_size=(9, 3.5), dpi=150)
wide.save("wide.png", verbose=False)

Which file format should I use?

Format Use it for
PNG web pages, slides, documents
SVG web graphics that must scale, or editing in a design tool
PDF LaTeX and print
JPEG only when a service requires it, since compression blurs text and thin lines
plot.save("trail.svg", verbose=False)
plot.save("trail.pdf", verbose=False)
plot.save("trail.jpg", dpi=200, pil_kwargs={"quality": 95}, verbose=False)

Extra keyword arguments such as pil_kwargs go to Matplotlib's savefig(). By default the SVG stores text as outlines. To keep it as editable text, set Matplotlib's svg.fonttype:

import matplotlib as mpl

with mpl.rc_context({"svg.fonttype": "none"}):
    plot.save("trail-text.svg", verbose=False)

Save with a Transparent Background

Pass transparent=True, and use a theme without a filled panel, such as theme_minimal().

plot.save("trail-transparent.png", dpi=200, transparent=True, verbose=False)

The trail chart saved with a transparent background, placed on a checkerboard that shows through

Setting plot_background=element_rect(fill="none") in the theme still produced a white PNG in 0.15.7, so use the argument.

Save to Memory Instead of a File

A web app can send the image without writing to disk. Give format explicitly.

from io import BytesIO

buffer = BytesIO()
plot.save(buffer, format="png", dpi=150, verbose=False)
png_bytes = buffer.getvalue()

Save Several Plots to One PDF

save_as_pdf_pages() writes one plot per page. It has no width or height arguments, so set figure_size in each plot's theme.

from plotnine import geom_histogram, save_as_pdf_pages

histogram = (ggplot(trail, aes("elevation"))
             + geom_histogram(bins=20, fill="#588157") + theme_minimal())
pages = [p + theme(figure_size=(8, 5)) for p in (plot, histogram)]
save_as_pdf_pages(pages, "report.pdf", verbose=False)

To put charts side by side in a single image, plotnine 0.15 can compose them: (plot | histogram).save("both.png"). Use / to stack them.

Edit the Matplotlib Figure Before Saving

draw() returns a Matplotlib figure. Make your changes, then call the figure's savefig().

figure = (plot + theme()).draw()
figure.text(0.99, 0.01, "Draft", ha="right", color="#999999")
figure.savefig("trail-draft.png", dpi=200)

Note the plot + theme(), which draws a copy. In 0.15.7, calling draw() on the plot object itself leaves the figure attached to it, and a later plot.save(..., dpi=300) ignores the dpi.

Practical Tips

  • Always pass width, height, and dpi in scripts, so output doesn't depend on a theme set elsewhere.
  • Check text size at the size the image will be shown, not zoomed in.
  • In notebooks, ending a cell with the plot displays it. In a script, call plot.show() or save it.

Similar Topics