Save plot to image file instead of displaying it
This displays the figure in a GUI:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()
But how do I instead save the figure to a file (e.g. foo.png)?
The primary method to save a matplotlib plot to a file instead of displaying it is using the savefig() function. You can save your plot directly by calling plt.savefig('filename.png') instead of plt.show(), which will create an image file on your disk without opening any GUI windows.
Contents
- Basic Savefig Method
- Preventing Display in Interactive Mode
- Advanced Savefig Parameters
- Supported File Formats
- Complete Examples
Basic Savefig Method
The simplest way to save a plot to a file is to replace plt.show() with plt.savefig(). This function saves the current figure to a file and doesn’t display it:
import matplotlib.pyplot as plt
# Create your plot
plt.plot([1, 2, 3], [1, 4, 9])
# Save instead of display
plt.savefig('foo.png') # Creates foo.png in current directory
The savefig() function automatically detects the file format from the extension you provide. Common file extensions include .png, .jpg, .pdf, .svg, and .eps.
You can also use the figure object directly:
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
fig.savefig('foo.png')
This approach gives you more control over the figure and is particularly useful when working with multiple figures.
Preventing Display in Interactive Mode
In some environments like Spyder with interactive mode enabled (plt.ion()), matplotlib might automatically display figures even when you use savefig(). To prevent this, you need to explicitly close the figure:
import matplotlib.pyplot as plt
# Create plot
plt.plot([1, 2, 3], [1, 4, 9])
# Save to file
plt.savefig('foo.png')
# Close the figure to prevent display
plt.close()
The Stack Overflow community notes that this approach is especially useful in large loops where you don’t want multiple figure windows to accumulate.
For cases where you’re working in Jupyter notebooks or IPython and want to avoid any display, you can use the ioff() method:
import matplotlib.pyplot as plt
plt.ioff() # Turn off interactive mode
plt.plot([1, 2, 3], [1, 4, 9])
plt.savefig('foo.png')
Advanced Savefig Parameters
The savefig() function accepts numerous parameters that allow you to control the output quality and appearance:
plt.savefig('filename.png',
dpi=300, # Resolution in dots per inch
facecolor='white', # Background color
edgecolor='white', # Border color
bbox_inches='tight', # Remove whitespace around plot
pad_inches=0.1, # Padding around figure
transparent=True, # Transparent background
format='png') # Explicit format specification
Key parameters include:
dpi: Controls resolution, with values like 100, 300, or 600 for higher qualitybbox_inches: Set to'tight'to remove excess whitespace around the plottransparent: UseTruefor transparent backgroundsquality: For JPEG format, specify quality (0-100)metadata: Add metadata to the image
As noted in the official matplotlib documentation, the dpi parameter can be set to 'figure' to use the figure’s native DPI value.
Supported File Formats
Matplotlib supports various file formats, each with different characteristics:
| Format | Extension | Use Case | Vector/Raster |
|---|---|---|---|
| PNG | .png | Web graphics, general use | Raster |
| JPEG | .jpg/.jpeg | Photos, web images | Raster |
| Documents, print-ready | Vector | ||
| SVG | .svg | Web graphics, scalable | Vector |
| EPS | .eps | Scientific publishing | Vector |
| TIFF | .tiff | High-quality images | Raster |
To specify a format explicitly, use the format parameter:
plt.savefig('plot.pdf', format='pdf') # Force PDF format
plt.savefig('image.png', format='png', dpi=300) # PNG with high resolution
The GeeksforGeeks tutorial explains that you can change the format simply by modifying the file extension, though explicit format specification can be helpful for clarity.
Complete Examples
Example 1: Basic Plot Saving
import matplotlib.pyplot as plt
# Create sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Create and save plot
plt.plot(x, y, marker='o', linestyle='-', color='blue')
plt.title('Simple Line Plot')
plt.xlabel('X values')
plt.ylabel('Y values')
# Save with high quality
plt.savefig('simple_plot.png', dpi=300, bbox_inches='tight')
Example 2: Multiple Plots with Different Formats
import matplotlib.pyplot as plt
import numpy as np
# Create sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Create subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
# First subplot
ax1.plot(x, y1, 'b-', label='sin(x)')
ax1.set_title('Sine Wave')
ax1.legend()
# Second subplot
ax2.plot(x, y2, 'r-', label='cos(x)')
ax2.set_title('Cosine Wave')
ax2.legend()
# Save in multiple formats
fig.savefig('trig_functions.png', dpi=300, bbox_inches='tight')
fig.savefig('trig_functions.pdf', format='pdf', bbox_inches='tight')
fig.savefig('trig_functions.svg', format='svg', bbox_inches='tight')
plt.close(fig) # Close to prevent display
Example 3: Batch Processing without Display
import matplotlib.pyplot as plt
import os
# Create output directory if it doesn't exist
output_dir = 'plots'
os.makedirs(output_dir, exist_ok=True)
# Generate multiple plots
for i in range(5):
plt.figure()
x = range(i+1, i+6)
y = [j**2 for j in x]
plt.plot(x, y, 'o-')
plt.title(f'Plot {i+1}')
plt.grid(True)
# Save plot
filename = os.path.join(output_dir, f'plot_{i+1}.png')
plt.savefig(filename, dpi=150, bbox_inches='tight')
plt.close() # Important: close to prevent display
print(f"Saved 5 plots to {output_dir}/")
This approach is essential for automated workflows, batch processing, or when you need to generate many plots without manual intervention.
Sources
- Stack Overflow - Save plot to image file instead of displaying it
- Matplotlib Official Documentation - savefig function
- GeeksforGeeks - Matplotlib.pyplot.savefig() in Python
- Delft Stack - How to Save Plots as an Image File Without Displaying in Matplotlib
- Problem Solving with Python - Saving Plots
- Better Stack Community - Save Plot to Image File Instead of Displaying It
- Chartio Resources - How to Save a Plot to a File Using Matplotlib
Conclusion
Saving matplotlib plots to files instead of displaying them is straightforward using the savefig() function. The key takeaways are:
- Use
plt.savefig('filename.png')instead ofplt.show()to save plots to files - Always call
plt.close()after saving to prevent display in interactive environments - Leverage parameters like
dpi,bbox_inches, andformatto control output quality - Different file formats serve different purposes: PNG/JPEG for web, PDF/SVG for documents
- For batch processing, use
plt.close()in loops to prevent memory issues
By mastering these techniques, you can automate your plotting workflows, generate high-quality graphics for publications, and integrate matplotlib into larger Python applications without GUI dependencies.