Saving plots lets you keep your work as images or documents. You can share or use them later without rerunning code.
0
0
Saving to PNG, SVG, PDF in Matplotlib
Introduction
You want to include a plot in a report or presentation.
You need to share a graph with someone who doesn't use Python.
You want to save your plot for future reference or comparison.
You need a high-quality image for printing or publication.
You want to save vector graphics for scaling without losing quality.
Syntax
Matplotlib
plt.savefig('filename.format')Replace 'filename.format' with your desired file name and extension like .png, .svg, or .pdf.
Call savefig before plt.show() to avoid saving a blank image.
Examples
Saves the current plot as a PNG image file.
Matplotlib
plt.savefig('plot.png')Saves the plot as an SVG vector graphic file.
Matplotlib
plt.savefig('plot.svg')Saves the plot as a PDF document.
Matplotlib
plt.savefig('plot.pdf')Sample Program
This code creates a simple line plot and saves it in three formats: PNG, SVG, and PDF. It prints a confirmation message after saving.
Matplotlib
import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [10, 20, 25, 30] plt.plot(x, y, marker='o') plt.title('Sample Line Plot') plt.xlabel('X axis') plt.ylabel('Y axis') plt.savefig('sample_plot.png') plt.savefig('sample_plot.svg') plt.savefig('sample_plot.pdf') print('Plots saved as PNG, SVG, and PDF files.')
OutputSuccess
Important Notes
PNG files are good for photos and web images but can lose quality if resized.
SVG and PDF are vector formats, so they keep quality when zoomed or printed.
You can add extra options to savefig like dpi=300 for higher resolution PNG images.
Summary
Use plt.savefig() to save your plots as files.
Choose file format by changing the file extension: .png, .svg, or .pdf.
Save before showing the plot to ensure the image is saved correctly.