0
0
MatplotlibHow-ToBeginner ยท 3 min read

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_inches to control bounding box and transparent for 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.savefig after plt.show() can save a blank image because plt.show() clears the figure by default.
  • Forgetting to include a file extension in filename may 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:

ParameterDescriptionExample
filenameName of the file to save the plot (with extension)'plot.png'
dpiResolution of the saved image in dots per inchdpi=300
formatFile format to save (overrides extension)format='pdf'
bbox_inchesAdjust bounding box to fit content tightlybbox_inches='tight'
transparentMake background transparenttransparent=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.