How can I save figure in matplotlib to an image file instead of opening it in a GUI?

I can display a plot with plt.show() using matplotlib.

How can I save figure to an image file like foo.png instead of opening it in a GUI?

When I needed to export plots for a report, I discovered that the easiest way to matplotlib save figure is using plt.savefig('foo.png').

Just place it before plt.show(), otherwise, the figure might be cleared before saving. Works like a charm for PNGs, PDFs, even SVGs!

In one of my data pipelines, I didn’t want any GUI pop-ups. So I skipped plt.show() entirely and just used plt.savefig('output_chart.png').

That’s the cleanest way to matplotlib save figure silently, especially when running on servers or CI where no display is available.