0
0
MatplotlibHow-ToBeginner ยท 3 min read

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:

  • filename is the name of the file to save (with extension like .png, .pdf, .jpg).
  • dpi sets the resolution (dots per inch) of the saved image.
  • format forces 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() after plt.show() can save a blank image because plt.show() clears the figure by default.
  • Not specifying the file extension in filename can 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() before plt.show().
  • Use file extensions like .png, .pdf, or .jpg in the filename.
  • Set dpi for 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.