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
Line Plot
Plot lines with markers, colors, and styles.
Bar Chart
Draw vertical, horizontal, and grouped bars.
Scatter Plot
Visualize relationships with size and color encodings.
Subplots
Arrange multiple axes with subplots and GridSpec.
Labels and Legend
Annotate plots with text, arrows, and legend options.
Styles and Themes
Apply built-in styles and customize rcParams.