Matplotlib Saving & Exporting
💾 Basic save
fig.savefig("plot.png")
fig.savefig("plot.pdf") # vector format, scales infinitely
fig.savefig("plot.svg") # vector, editable in Illustrator/Inkscape
fig.savefig("plot.jpg") # lossy, avoid for line art/text-heavy plotsUse PNG for raster (photos, complex plots), PDF/SVG for vector (papers, print, anything that needs to scale without pixelation).
🎯 Resolution (DPI)
fig.savefig("plot.png", dpi=300) # print-quality
fig.savefig("plot.png", dpi=72) # screen/web quality300 DPI is the standard minimum for print/publication. 72-150 DPI is plenty for web/screen use.
✂️ Trimming whitespace
fig.savefig("plot.png", bbox_inches="tight") # crop to content, removes excess margin
fig.savefig("plot.png", bbox_inches="tight", pad_inches=0.1) # tight + small paddingWithout
bbox_inches="tight", legends or labels placed outside the axes (e.g. viabbox_to_anchor) can get cut off in the saved file even though they display fine inplt.show().
🎨 Background / transparency
fig.savefig("plot.png", transparent=True) # transparent background — good for overlaying on slides/docs
fig.savefig("plot.png", facecolor="white") # explicit background color📐 Size control
fig, ax = plt.subplots(figsize=(10, 6)) # set size BEFORE plotting, in inches
fig.set_size_inches(12, 8) # or resize an existing figure🧮 Full production-quality example
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(x, y)
ax.set_title("Report Chart")
fig.tight_layout()
fig.savefig("report_chart.png", dpi=300, bbox_inches="tight", transparent=False)🖼️ Saving before show()
fig.savefig("plot.png") # save FIRST
plt.show() # then show — plt.show() can clear the figure on some backendsCalling
plt.show()beforesavefig()can occasionally result in a blank saved file, depending on the backend. Save first as a safe default habit.
🔗 Next
Matplotlib Advanced (3D Animation Style Sheets) · Matplotlib