Skip to content
Matplotlib

Save Figure

Export figures to PNG, PDF, and SVG with DPI control.

By EZ4Code Team
saveexport

Code

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 50)
plt.plot(x, x ** 2)

plt.title("Saved figure")

# Raster formats
plt.savefig("out.png", dpi=150, bbox_inches="tight", facecolor="white")
plt.savefig("out.jpg", dpi=120)

# Vector formats (scalable, good for print)
plt.savefig("out.pdf")
plt.savefig("out.svg")

# Transparent background
plt.savefig("overlay.png", transparent=True)

# Save the current figure as an array
buf = np.asarray(plt.gcf().canvas.buffer_rgba())
print(buf.shape)

Explanation

savefig() writes the current figure to a file, choosing format from the extension. dpi controls resolution for raster outputs, and bbox_inches='tight' trims whitespace around the plot. Vector formats like PDF and SVG scale without pixelation for print or web embedding.

More Matplotlib Snippets