Course contentsShow
← Data Science
Lesson 1262 of 2,14532. Visualization with Matplotlib and SeabornFree lesson

Saving Figures to Files

Exporting plots with savefig(), understanding file formats (PNG, PDF, SVG), and controlling resolution with dpi.

Saving Figures to Files

What you'll learn: How to export your Matplotlib visualizations to image files with the right format and quality settings.

Why Save Your Plots?

Creating great visualizations is only half the job—you need to share them! Whether it's for a report, presentation, web dashboard, or publication, saving your plots to files lets you use them outside of Python notebooks and scripts.

Using savefig()

Matplotlib's savefig() method exports your current figure to a file. It's straightforward: just call it before plt.show() with your desired filename:

import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [1, 4, 9])
plt.title('Simple Plot')
plt.savefig('my_plot.png')
plt.show()

The file extension in the filename tells Matplotlib which format to use.

Choosing File Formats

Different formats serve different purposes:

  • PNG (.png): Raster format, great for web use and presentations. Widely compatible, supports transparency.
  • PDF (.pdf): Vector format, perfect for publications and print. Scales infinitely without quality loss.
  • SVG (.svg): Vector format for web graphics and further editing in tools like Illustrator.

Think of raster formats like a fixed grid of pixels (zooming in makes them blurry), while vector formats are like mathematical instructions that redraw perfectly at any size.

Controlling Resolution with DPI

DPI (dots per inch) controls image sharpness. Higher DPI = sharper image but larger file size:

plt.savefig('low_res.png', dpi=72)   # Screen quality
plt.savefig('high_res.png', dpi=300) # Print quality

Default is typically 100 dpi. Use 300+ for professional printing, 72-150 for digital displays.

Key Takeaway: Use savefig() with appropriate file formats (PNG for web, PDF for print) and set dpi to control image resolution and file size.