Question

How to Save a Matplotlib Plot to a File in Python

pythonmatplotlibsavefig

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:

  • .png for web images
  • .jpg for compressed images
  • .pdf for documents
  • .svg for 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("foo.png")

In many cases, you can save the file without ever calling plt.show(). If you do call show(), it is usually safer to save the figure before showing it.

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
Take Quiz

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

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 4))
plt.plot([1, 2, 3], [1, 4, 9])
plt.savefig("foo.png", dpi=150)
  • figsize=(6, 4) sets width and height in inches.
  • dpi=150 sets image resolution.

Save to different formats

import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [1, 4, 9])
plt.savefig("foo.pdf")
plt.savefig("foo.svg")

The format is usually inferred from the file extension.

Using the object-oriented style

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
fig.savefig("foo.png")

This style is very common in real projects because it gives you clearer control over which figure you are saving.

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:

  1. import matplotlib.pyplot as plt

    • Imports Matplotlib's plotting interface.
  2. 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.
  3. 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].
  4. fig.savefig("foo.png")

    • Writes the current figure contents to a file named foo.png.
    • If the file already exists, it is overwritten.

After this runs, you will have an image file in the current working directory.

Small execution trace

import matplotlib.pyplot as plt

x = [1, 2, 3]
y = [1, 4, 9]

fig, ax = plt.subplots()
ax.plot(x, y)
fig.savefig("chart.png")

Trace:

  • x becomes [1, 2, 3]
  • y becomes [1, 4, 9]
  • subplots() creates an empty figure
  • plot(x, y) adds a line to that figure
  • savefig("chart.png") stores the image on disk

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()
Take Quiz

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 save_line_chart(x, y, filename):
    fig, ax = plt.subplots()
    ax.plot(x, y)
    fig.savefig(filename)
    plt.close(fig)

This keeps plotting logic reusable.

Common pattern: layout cleanup

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
fig.tight_layout()
fig.savefig("clean-layout.png")

This helps prevent labels from being cut off.

Common pattern: error-safe generation

When generating files in production code, developers often ensure directories exist first.

from pathlib import Path
import matplotlib.pyplot as plt

output_dir = Path("charts")
output_dir.mkdir(exist_ok=True)

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
fig.savefig(output_dir / "example.png")
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

If your code creates multiple figures, plt.savefig(...) may save the current figure, which might not be the one you intended.

Safer approach:

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
fig.savefig("foo.png")

Labels getting cut off

If titles or axis labels are long, parts of the image may be clipped.

fig, ax = plt.subplots()
ax.set_title("A very long chart title")
ax.plot([1, 2, 3], [1, 4, 9])
fig.tight_layout()
fig.savefig("foo.png")

Creating many figures without closing them

In loops, this can use too much memory.

for i in range(100):
    fig, ax = plt.subplots()
    ax.plot([1, 2, 3], [i, i + 1, i + 2])
    fig.savefig(f"plot_{i}.png")
    plt.close(fig)

Assuming the file is saved somewhere else

Files are saved relative to the current working directory unless you provide a full or explicit path.

plt.savefig("output/foo.png")

Make sure that folder exists first.

Comparisons

ApproachWhat it doesBest use caseNotes
plt.show()Displays the figure on screenInteractive work, local explorationDoes not save a file by itself
plt.savefig("file.png")Saves the current figure to a fileQuick scripts and simple plotsUses Matplotlib's current active figure
fig.savefig("file.png")Saves a specific figure objectReal projects and multi-figure codeClearer and safer than relying on global state

plt.savefig() vs fig.savefig()

# Stateful style
plt.plot([1, 2, 3], [1, 4, 9])
plt.savefig("a.png")
# Object-oriented style
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
fig.savefig("a.png")

Use fig.savefig() when:

  • you create multiple figures
  • you want clearer code
  • you are writing reusable functions

Use plt.savefig() when:

  • you are writing a short script
  • there is only one simple plot
  • you are learning the basics
Take Quiz

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
  • .pdf — document-friendly, vector output
  • .svg — scalable vector graphics

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.

Why is my saved image blank?

Common reasons include:

  • calling show() before savefig()
  • saving the wrong figure
  • clearing or closing the figure before saving

How do I save a higher-quality image?

Increase the DPI:

plt.savefig("plot.png", dpi=200)
Take Quiz

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.
Take Quiz

Keep learning

Related questions

View more