How to Use plt.savefig in Matplotlib to Save Plots
Use
plt.savefig(filename, dpi=, format=) to save your current matplotlib plot to a file. Specify the file name with extension (like .png or .pdf) and optional parameters like dpi for resolution and format to set the file type explicitly.Syntax
The basic syntax of plt.savefig is:
filename: The name of the file where the plot will be saved. Include the file extension like.png,.jpg, or.pdf.dpi(optional): Controls the resolution (dots per inch) of the saved image. Higher means sharper image.format(optional): Forces the file format if the extension is missing or you want a different format.- Other optional parameters include
bbox_inchesto control bounding box andtransparentfor background transparency.
python
plt.savefig(fname, dpi=None, format=None, bbox_inches=None, transparent=False)
Example
This example creates a simple line plot and saves it as a PNG file with 300 dpi resolution.
python
import matplotlib.pyplot as plt # Create some data x = [1, 2, 3, 4, 5] y = [2, 3, 5, 7, 11] # Plot the data plt.plot(x, y, marker='o') plt.title('Simple Line Plot') plt.xlabel('X axis') plt.ylabel('Y axis') # Save the plot to a file plt.savefig('line_plot.png', dpi=300) # Show the plot plt.show()
Output
A window opens showing the line plot with points connected by lines.
Common Pitfalls
- Calling
plt.savefigafterplt.show()can save a blank image becauseplt.show()clears the figure by default. - Forgetting to include a file extension in
filenamemay cause errors or unexpected formats. - Not setting
bbox_inches='tight'can result in clipped labels or titles in the saved image.
python
import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 6]) plt.savefig('plot_without_extension') # May cause format issues plt.show() # Correct way: plt.plot([1, 2, 3], [4, 5, 6]) plt.savefig('plot_with_extension.png', bbox_inches='tight') plt.show()
Quick Reference
Here is a quick summary of common plt.savefig parameters:
| Parameter | Description | Example |
|---|---|---|
| filename | Name of the file to save the plot (with extension) | 'plot.png' |
| dpi | Resolution of the saved image in dots per inch | dpi=300 |
| format | File format to save (overrides extension) | format='pdf' |
| bbox_inches | Adjust bounding box to fit content tightly | bbox_inches='tight' |
| transparent | Make background transparent | transparent=True |
Key Takeaways
Always call plt.savefig before plt.show to ensure the plot is saved correctly.
Include a file extension in the filename to specify the image format automatically.
Use dpi parameter to control the image resolution for better quality.
Set bbox_inches='tight' to avoid clipping labels and titles in the saved image.
plt.savefig supports many formats like PNG, JPG, PDF, SVG depending on the filename extension.