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

I’m working with Matplotlib in Python and usually use plt.show() to display plots in a GUI window. However, now I want to save my plots directly to image files so I can include them in reports or share them without opening a window.

Here’s a simple example of what I normally do:

import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [1, 4, 9])
plt.show()  # Currently displays the plot in a window

Instead of showing the plot, I want to save it to a file, for example foo.png.

What’s the correct way to matplotlib save image from a plot? Are there any important options I should know about, like resolution or file format?

Sometimes I like to both display and save the plot in the same script. In that case, just call savefig() before plt.show(). If you call it after show(), some backends may not save the figure correctly, especially in interactive environments like Jupyter Notebook:

import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [1, 4, 9])
plt.savefig("foo.pdf")  # Save as PDF first
plt.show()  # Then display in a window

This way, you get a saved copy without affecting the interactive plot.

If you’re working with multiple figures or subplots, I found it cleaner to use Matplotlib’s object-oriented approach. It gives you more control and avoids accidentally saving an empty plot:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
fig.savefig("foo.svg", format="svg")  # Save explicitly as SVG

This is especially handy when you want to save multiple figures with different settings in the same script.

In short, plt.savefig() is your friend, and remember you can tweak dpi, format, and figure size to match your needs. I usually pick PNG for general use and PDF or SVG for vector graphics in reports.

From my own experience, the simplest way is to call plt.savefig() with your desired filename. You don’t even need to call plt.show() if you only want to save the plot. You can also control the image resolution with dpi. For example:

import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [1, 4, 9])
plt.savefig("foo.png", dpi=300)  # Saves the plot as a PNG file at 300 dpi

This works great for creating high-resolution images for reports or publications. You can also change the format by using extensions like .jpg, .pdf, or .svg.