Save a Matplotlib plot to a file in Python

David Y.

The Problem

How can I save a plot created with Matplotlib to an image file instead of displaying it?

The Solution

We can do this using the savefig function:

from matplotlib import pyplot pyplot.savefig("myPlot.png", bbox_inches="tight")

This function will save the current plot as a PNG image file. By specifying a different file extension, we could instead save it as an SVG (.svg), PostScript file (.ps), or PDF (.pdf).

The argument bbox_inches="tight" ensures that the image is saved without surrounding whitespace. Additional arguments can be specified to change the colors and transparency of the saved image.

Note that clears the current plot, and should therefore only be called after pyplot.savefig, to avoid saving a blank image.

Join the discussionCome work with us
Share on Twitter
Bookmark this page
Ask a questionImprove this Answer

Related Answers

A better experience for your users. An easier life for your developers.

© 2023 • Sentry is a registered Trademark
of Functional Software, Inc.