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 callplt.savefig()afterplt.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 is100).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)
You must log in or register to comment.
