Saving figures lets you keep your charts as image files. You can share or use them later without rerunning code.
0
0
Saving figures to files in Matplotlib
Introduction
You want to include a chart in a report or presentation.
You need to save a plot for sharing with a teammate.
You want to keep a record of your data visualization results.
You want to create images for a website or blog.
You want to save multiple plots automatically in a script.
Syntax
Matplotlib
plt.savefig('filename.png', dpi=300, bbox_inches='tight')
filename.png is the name and format of the saved file.
dpi controls image quality (dots per inch).
bbox_inches='tight' trims extra white space around the figure.
Examples
Saves the current figure as a PNG file named 'plot.png' with default settings.
Matplotlib
plt.savefig('plot.png')Saves the figure as a PDF file, useful for high-quality print.
Matplotlib
plt.savefig('plot.pdf')Saves the figure as a JPEG with medium quality.
Matplotlib
plt.savefig('plot.jpg', dpi=150)
Saves the figure and removes extra white space around it.
Matplotlib
plt.savefig('plot.png', bbox_inches='tight')
Sample Program
This code creates a simple line plot and saves it as 'sample_plot.png' with good quality and no extra white space. It then prints a confirmation message.
Matplotlib
import matplotlib.pyplot as plt # Create simple data x = [1, 2, 3, 4] y = [10, 20, 25, 30] # Plot the data plt.plot(x, y, marker='o') plt.title('Sample Line Plot') plt.xlabel('X axis') plt.ylabel('Y axis') # Save the figure to a file plt.savefig('sample_plot.png', dpi=200, bbox_inches='tight') print('Figure saved as sample_plot.png')
OutputSuccess
Important Notes
Always call plt.savefig() before plt.show() because showing the plot can clear it.
You can save in many formats like PNG, JPG, PDF, SVG by changing the file extension.
Use dpi to control image clarity; higher means sharper but bigger files.
Summary
Use plt.savefig() to save your plots as image files.
Choose file format by the file extension you provide.
Adjust dpi and bbox_inches for quality and layout.