Saving figures
savefig writes the current figure to a PNG, PDF or SVG file.
In this page:
Syntax
import matplotlib.pyplot as plt
df.plot()
plt.savefig("chart.png", dpi=150)
plt.show()
Saving figures
plt.savefig("chart.png", dpi=150) saves the active figure; call it before plt.show, which clears the figure. The format follows the file extension. bbox_inches="tight" trims extra whitespace. Here we save into memory instead of disk.
Note:
Use transparent=True for PNGs on coloured backgrounds.
Example: Saving figures
import io
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pandas as pd
ax = pd.Series([1, 3, 2]).plot(title="Demo")
for fmt in ["png", "svg"]:
buf = io.BytesIO()
plt.savefig(buf, format=fmt, dpi=100, bbox_inches="tight")
print(fmt, "saved:", buf.getbuffer().nbytes > 0)
# Output:
# png saved: True
# svg saved: True
Related Topics
Common Mistakes
- Calling savefig after show
- Low dpi producing blurry images
- Cropped labels without bbox_inches
Chapter Summary
- savefig writes files
- Format follows the extension
- dpi sets resolution
- Call it before show
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: