Saving Figures
Python · Data Visualization
Theory
fig.savefig('sales.png') writes the figure to a file, and the extension picks the format. PNG is a raster image of pixels, good for slides, web pages and chat. SVG and PDF are vector formats that stay sharp at any zoom, good for reports and print. dpi (dots per inch) sets the resolution of raster output: the pixel size is figsize x dpi, so a 6 x 4 inch figure at dpi=200 is 1200 x 800 pixels.
bbox_inches='tight' trims extra white space and keeps labels from being cut off, and transparent=True removes the background. Call savefig before plt.show(), because in a script show() can leave you with an empty figure afterwards. When creating many charts in a loop, call plt.close(fig) after saving to free memory. You can also save into memory with io.BytesIO, which is how web apps send charts without writing files.
Why we use it
Charts usually end up somewhere else: a report, a slide deck, a dashboard or an email. Saving at the right size, format and resolution keeps them sharp and readable wherever they go.
When to use it
Use PNG at dpi 150-300 for slides and documents, SVG or PDF for print and scalable graphics. Use bbox_inches='tight' when labels get clipped, and close each figure after saving when you generate charts in bulk.
How it works
- Finished figure
- Will it be printed or zoomed? Yes: Save as .svg or .pdf (vector). No: Save as .png (raster).
- Pick dpi: pixels = figsize x dpi
- Add bbox_inches='tight' if labels are cut off
- fig.savefig(...) then plt.close(fig)
- Image file ready to share
Syntax
fig.savefig('chart.png', dpi=200, bbox_inches='tight')
fig.savefig('chart.svg')
fig.savefig('chart.pdf', transparent=True)
plt.close(fig)Example
fig, ax = plt.subplots(figsize=(6, 4))
ax.bar(['Jaipur', 'Pune'], [120, 90])
fig.savefig('sales.png', dpi=200, bbox_inches='tight')Key points
- The file extension picks the format: .png, .svg, .pdf
- Pixels = figsize (inches) x dpi
- bbox_inches='tight' trims white space and stops clipping
- Call savefig before plt.show()
- plt.close(fig) after saving when making many charts