Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 21

Saving Figures

Save a finished chart with savefig as PNG, SVG, or PDF, set its size and resolution, trim the margins, and close figures you no longer need.

Intermediate25 min
Saving Figures hero Module 25 Lesson 21Saving Figures hero Module 25 Lesson 21

A chart on screen is only half the job. Reports, slides, and web pages need a file. savefig writes the current figure to disk, and the file extension you choose decides the format.

The five steps from sizing a figure to saving and closing itThe five steps from sizing a figure to saving and closing it

Save the current figure

Call savefig with a file name. Call it before show, because once a window is closed the figure may be gone and the saved file comes out blank.

python
import os

import matplotlib.pyplot as plt

days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
signups = [42, 58, 51, 66, 73, 61, 47]

plt.plot(days, signups, marker="o")
plt.title("Signups this week")
plt.savefig("signups.png")
plt.show()

print(os.path.exists("signups.png"))

Output:

text
True

The extension picks the format

.png is a raster image, good for the web and slides. .svg and .pdf are vector formats that stay sharp at any zoom, which is what print and publications want. You can also pass format= explicitly.

python
import os

import matplotlib.pyplot as plt

plt.bar(["Python", "NumPy", "pandas"], [120, 86, 94], color="#7C3AED")
plt.title("Enrolments")
for name in ["tracks.png", "tracks.svg", "tracks.pdf"]:
    plt.savefig(name)
plt.close()

for name in ["tracks.png", "tracks.svg", "tracks.pdf"]:
    print(name, os.path.getsize(name) > 0)

Output:

text
tracks.png True
tracks.svg True
tracks.pdf True

Size and resolution

figsize is width and height in inches, set when the figure is made. dpi is dots per inch, set when it is saved. Pixels are the two multiplied, so an 8 by 4 inch figure at 150 dpi is 1200 by 600 pixels.

python
import matplotlib.pyplot as plt
from matplotlib.image import imread

plt.figure(figsize=(8, 4))
plt.plot([1, 2, 3, 4], [3, 5, 4, 6])
plt.savefig("wide.png", dpi=150)
plt.close()

height, width = imread("wide.png").shape[:2]
print(width, "x", height)

Output:

text
1200 x 600

Trim the margins

bbox_inches="tight" shrinks the saved area to fit the chart and its labels, so long titles are not clipped and there is no wide white border. transparent=True drops the white background for use on coloured slides.

python
import matplotlib.pyplot as plt
from matplotlib.image import imread

plt.figure(figsize=(6, 3))
plt.plot([1, 2, 3], [2, 4, 3])
plt.title("A long title that would sit close to the edge")
plt.savefig("loose.png", dpi=100)
plt.savefig("tight.png", dpi=100, bbox_inches="tight", transparent=True)
plt.close()

print("loose:", imread("loose.png").shape[:2])
print("tight:", imread("tight.png").shape[:2])

Output:

text
loose: (300, 600)
tight: (297, 516)

Close what you have saved

Every plt.figure stays in memory until it is closed. In a loop that saves many charts, call plt.close() after each save, or the program slowly fills up. plt.get_fignums() lists the figures still open.

python
import matplotlib.pyplot as plt

weeks = {"week 1": [3, 5, 4], "week 2": [4, 6, 5], "week 3": [5, 5, 7]}

for m, p in weeks.items():
    plt.figure()
    plt.plot(p)
    plt.title(m)
    plt.savefig(m.replace(" ", "_") + ".png")
    plt.close()

print("open figures:", plt.get_fignums())

Output:

text
open figures: []

In this page's playground, files are written to a temporary folder in your browser's memory, so they disappear when you reload. On your own computer they land next to your script.

Key takeaways

  • savefig writes the current figure, so call it before show

  • The extension picks the format: png for screens, svg or pdf for print

  • figsize is inches, dpi is pixels per inch, and pixels are the product

  • bbox_inches="tight" trims margins; plt.close() frees saved figures

  • Next: What Is Seaborn

  • Previous: Styling a Pie Chart

Loading playground…

Check your understanding

Saving Figures Quiz

Which function writes a chart to a file?

1 / 10