How to Save Plot in Matplotlib: Simple Steps
To save a plot in matplotlib, use the
savefig() function after creating your plot. Call plt.savefig('filename.png') to save the plot as an image file like PNG or PDF.Syntax
The basic syntax to save a plot in matplotlib is:
plt.savefig(filename, dpi=None, format=None, bbox_inches=None)
Here:
filenameis the name of the file to save (with extension like .png, .pdf, .jpg).dpisets the resolution (dots per inch) of the saved image.formatforces the file format if not inferred from filename.bbox_inches='tight'trims extra whitespace around the plot.
python
plt.savefig('plot.png', dpi=300, bbox_inches='tight')
Example
This example shows how to create a simple line plot and save it as a PNG file with high resolution.
python
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2, 3, 5, 7, 11] plt.plot(x, y, marker='o') plt.title('Sample Line Plot') plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.savefig('line_plot.png', dpi=300, bbox_inches='tight') plt.show()
Output
A window opens showing the line plot with points connected by lines. The plot is saved as 'line_plot.png' in the current folder.
Common Pitfalls
Common mistakes when saving plots include:
- Calling
plt.savefig()afterplt.show()can save a blank image becauseplt.show()clears the figure by default. - Not specifying the file extension in
filenamecan cause errors or unexpected formats. - Forgetting
bbox_inches='tight'may save images with unwanted white space.
python
import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 6]) plt.show() plt.savefig('wrong_save.png') # This saves a blank image # Correct way: plt.plot([1, 2, 3], [4, 5, 6]) plt.savefig('correct_save.png', bbox_inches='tight') plt.show()
Output
First save creates a blank image file 'wrong_save.png'. Second save correctly saves the plot as 'correct_save.png'.
Quick Reference
Summary tips for saving plots in matplotlib:
- Always call
plt.savefig()beforeplt.show(). - Use file extensions like
.png,.pdf, or.jpgin the filename. - Set
dpifor better image quality (e.g., 300 for print). - Use
bbox_inches='tight'to reduce extra margins.
Key Takeaways
Use plt.savefig('filename.png') to save your matplotlib plot as an image file.
Call plt.savefig() before plt.show() to avoid saving blank images.
Include the file extension in the filename to specify the image format.
Use dpi and bbox_inches parameters to control image quality and layout.
Saving plots allows you to share or embed your visualizations easily.