How do you save a Matplotlib plot to an image file instead of displaying it? | A1Lab@MZeeshanM to PythonEnglish • 8 days ago

How do you save a Matplotlib plot to an image file instead of displaying it?

message-square
0

Use plt.savefig() before calling plt.show(), or simply omit plt.show() altogether.

Basic Example

import matplotlib.pyplot as plt

# 1. Create your plot
plt.plot([1, 2, 3, 4], [10, 20, 25, 30])
plt.title("Sample Plot")

# 2. Save the figure to a file (format is inferred from the extension)
plt.savefig("my_plot.png", dpi=300, bbox_inches="tight")

# 3. Close the figure to free up memory (recommended in loops/scripts)
plt.close()

Key Details & Parameters

  • Call order matters: Calling plt.show() clears the current figure in many backends. If you call plt.savefig() after plt.show(), you will get a blank white image.
  • Supported formats: Matplotlib automatically detects the format from the filename extension (.png, .jpg, .svg, .pdf, .eps).
  • Useful savefig() arguments:
    • dpi=300: Increases resolution for raster formats like PNG or JPG (default is 100).
    • bbox_inches="tight": Trims excess whitespace around the edges so labels and titles aren’t cut off.
    • transparent=True: Makes the figure and axes backgrounds transparent.

Object-Oriented Approach

If you are working with explicit Figure and Axes objects, call .savefig() directly on the fig instance:

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])

fig.savefig("oo_plot.pdf", bbox_inches="tight")
plt.close(fig)