Question
I have a Matplotlib plot in Python that currently displays in a GUI window:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()
How can I save this figure to an image file such as foo.png instead of displaying it on screen?
Short Answer
By the end of this page, you will understand how to save Matplotlib figures to image files using savefig(), when to call it, which formats are supported, and how to avoid common mistakes such as saving blank images or calling functions in the wrong order.
Concept
In Matplotlib, creating a plot and displaying a plot are two separate actions.
plt.plot(...)adds data to the current figure.plt.show()asks Matplotlib to display that figure in a window or notebook output.plt.savefig(...)writes the current figure to a file.
This matters because many Python programs do not run with a visible GUI:
- scripts running on servers
- automated reports
- data pipelines
- batch image generation
- testing and documentation tools
Saving a figure to a file lets your program produce reusable output such as:
.pngfor web images.jpgfor compressed images.pdffor documents.svgfor scalable vector graphics
The key idea is simple: build the figure, then save it with savefig().
Basic example:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.savefig()
Mental Model
Think of a Matplotlib figure like a drawing on a whiteboard.
plt.plot(...)draws on the whiteboard.plt.show()puts the whiteboard in front of you so you can see it.plt.savefig(...)takes a photo of the whiteboard and stores it in a file.
If your goal is to keep the drawing for later, you want the photo step: savefig().
In other words:
- draw the chart
- save the chart
- optionally display the chart
Syntax and Examples
The main syntax is:
plt.savefig("filename.png")
You can also save a specific figure object:
fig.savefig("filename.png")
Basic example
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.savefig("foo.png")
This creates a plot and saves it as foo.png in the current working directory.
Save before showing
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.savefig("foo.png")
plt.show()
This is a common pattern when you want both:
- a saved file
- a visible plot window
Save with custom size and resolution
Step by Step Execution
Consider this example:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
fig.savefig("foo.png")
Here is what happens step by step:
-
import matplotlib.pyplot as plt- Imports Matplotlib's plotting interface.
-
fig, ax = plt.subplots()- Creates a new figure (
fig) and one set of axes (ax). - The figure is the whole image.
- The axes are the plotting area inside the figure.
- Creates a new figure (
-
ax.plot([1, 2, 3], [1, 4, 9])- Draws a line on the axes.
- The x-values are
[1, 2, 3]. - The y-values are
[1, 4, 9].
-
fig.savefig("foo.png")- Writes the current figure contents to a file named .
Real World Use Cases
Saving plots to files is extremely common in real programs.
Automated reports
A script generates charts for sales, traffic, or analytics and saves them into files that are later inserted into PDFs or dashboards.
plt.savefig("monthly-sales.png")
Data science workflows
During analysis, you may save visualizations so teammates can review them without rerunning the notebook.
plt.savefig("correlation-heatmap.png", dpi=200)
Server-side scripts
A backend job may generate images on a server that has no display at all. In that case, saving is required, while showing is often impossible.
Documentation generation
Projects often build charts for READMEs, tutorials, or internal docs.
Batch processing
You might create many plots in a loop and save each one with a unique filename.
for i in range(3):
plt.figure()
plt.plot([1, 2, 3], [i, i + 1, i + 2])
plt.savefig(f"plot_{i}.png")
plt.close()
Real Codebase Usage
In real codebases, developers usually do more than just call savefig() once.
Common pattern: explicit figure objects
Instead of relying on the global plt state, many teams use the object-oriented style:
fig, ax = plt.subplots()
ax.plot(data)
fig.savefig("output.png")
This is easier to maintain when a file contains multiple figures.
Common pattern: save then close
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
fig.savefig("result.png")
plt.close(fig)
Closing the figure helps free memory, especially in loops or long-running scripts.
Common pattern: configurable output paths
output_path = "reports/charts/revenue.png"
fig.savefig(output_path, dpi=150)
Real projects often build file paths from configuration values, dates, user IDs, or report names.
Common pattern: helper functions
import matplotlib.pyplot as plt
def ():
fig, ax = plt.subplots()
ax.plot(x, y)
fig.savefig(filename)
plt.close(fig)
Common Mistakes
Calling show() before savefig()
In some environments, calling plt.show() may clear or close the figure. Saving afterward can produce an empty or incorrect image.
Broken pattern:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()
plt.savefig("foo.png")
Safer pattern:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.savefig("foo.png")
plt.show()
Forgetting the file extension
plt.savefig("foo")
This may not produce the format you expect. Prefer:
plt.savefig("foo.png")
Saving the wrong figure
Comparisons
| Approach | What it does | Best use case | Notes |
|---|---|---|---|
plt.show() | Displays the figure on screen | Interactive work, local exploration | Does not save a file by itself |
plt.savefig("file.png") | Saves the current figure to a file | Quick scripts and simple plots | Uses Matplotlib's current active figure |
fig.savefig("file.png") | Saves a specific figure object | Real projects and multi-figure code | Clearer and safer than relying on global state |
plt.savefig() vs fig.savefig()
# Stateful style
plt.plot([1, 2, ], [, , ])
plt.savefig()
Cheat Sheet
# Quick save
plt.savefig("plot.png")
# Save then display
plt.savefig("plot.png")
plt.show()
# Object-oriented style
fig, ax = plt.subplots()
ax.plot(x, y)
fig.savefig("plot.png")
# Higher resolution
plt.savefig("plot.png", dpi=200)
# Better layout
fig.tight_layout()
fig.savefig("plot.png")
# Save different formats
plt.savefig("plot.pdf")
plt.savefig("plot.svg")
# Save in a loop safely
fig.savefig(filename)
plt.close(fig)
Rules to remember
- Use
savefig()to write a plot to disk. - Save before
show()when possible. - Include a file extension like
.png. - Use
fig.savefig()for clearer code. - Use
tight_layout()if labels are clipped. - Close figures in loops to avoid memory issues.
Common formats
.png— raster image, great for web and screenshots.jpg— compressed image, less common for plots- — document-friendly, vector output
FAQ
How do I save a Matplotlib plot as a PNG?
Use savefig() with a .png filename:
plt.savefig("plot.png")
Should I call savefig() before or after show()?
Usually before show(). In some environments, saving after show() can produce a blank image.
Where is the image file saved?
It is saved in the current working directory unless you provide a path like "images/plot.png".
Can Matplotlib save formats other than PNG?
Yes. Common formats include pdf, svg, and jpg, depending on your setup.
What is the difference between plt.savefig() and fig.savefig()?
plt.savefig() saves the current active figure. fig.savefig() saves a specific figure object and is usually clearer in larger programs.
Mini Project
Description
Create a small Python script that generates a line chart of daily temperatures and saves it to a file. This demonstrates the full workflow of creating a plot, customizing it, saving it to disk, and cleaning up properly.
Goal
Build and save a Matplotlib chart as a PNG file without relying on a GUI display.
Requirements
- Create a line plot using a short list of day labels and temperature values.
- Add a title and axis labels.
- Save the chart as
temperature_report.png. - Use the object-oriented Matplotlib style.
- Close the figure after saving it.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.