savefig() (Matplotlib)
fig.savefig() (or plt.savefig()) writes a Matplotlib figure to an image file such as PNG, PDF, or SVG. It is how you export a plot for a report, slide, or webpage instead of showing it on screen.
Matplotlib
The file format is inferred from the extension you give: 'chart.png' makes a raster image, 'chart.pdf' or 'chart.svg' make scalable vector graphics that stay crisp at any zoom. For print-quality raster output, raise dpi (dots per inch) to 300 or more.
Two arguments solve the most common complaints: bbox_inches='tight' trims excess whitespace around the figure, and transparent=True drops the background so the plot blends into a slide or page. The figure's physical size comes from its figsize, set when you created it.
Call savefig before show() in scripts, because some backends clear the figure once it is displayed. savefig saves the whole Figure, including every Axes and the suptitle, not just the current panel.
Syntax
fig.savefig(fname, dpi=None, bbox_inches=None, transparent=False)Examples
Python — Saves to an in-memory buffer; True means bytes were written.
import matplotlib.pyplot as plt
import io
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
buf = io.BytesIO()
fig.savefig(buf, format="png")
print(buf.getbuffer().nbytes > 0)Output:
True