Matplotlib Ref Savefig
* * *
[ Matplotlib Reference Documentation](https://example.com/matplotlib/matplotlib-apiref.html)
`savefig()` is used to save the current Figure as an image file, supporting multiple formats such as PNG, PDF, SVG, EPS, etc.
It is the core method for exporting Matplotlib charts into shareable and embeddable document files.
## Function Definition
### pyplot Interface
matplotlib.pyplot.savefig(fname, *, dpi='figure', format=None, metadata=None, bbox_inches=None, pad_inches=0.1, facecolor='auto', edgecolor='auto', backend=None, **kwargs)
### Figure Method
Figure.savefig(fname, *, dpi='figure', format=None, metadata=None, bbox_inches=None, pad_inches=0.1, facecolor='auto', edgecolor='auto', backend=None, **kwargs)
## Parameter Description
| Parameter | Type | Description |
| --- | --- | --- |
| fname | str or Path or file-like | Output filename or file object. Extension automatically determines the format, e.g., 'plot.png', 'plot.pdf', 'plot.svg' |
| dpi | float or 'figure' | Output resolution (dots per inch). 'figure' uses the Figure's own dpi. Common values: 72(screen), 150(general), 300(print) |
| format | str | Output format, such as 'png', 'pdf', 'svg', 'eps', 'jpg'. If not specified, inferred from filename |
| bbox_inches | str or Bbox | Crop boundary: 'tight' (compact crop, removes extra whitespace), None (uses Figure's original size) |
| pad_inches | float | Padding when bbox_inches='tight' (in inches), default 0.1 |
| facecolor | color or 'auto' | Background color of output image, 'auto' uses Figure's facecolor |
| edgecolor | color or 'auto' | Border color of output image |
| transparent | bool | If True, background becomes transparent (png/svg only) |
| metadata | dict | Metadata to write into file (supported by some formats) |
> Must call `savefig()` before `plt.show()`, because show() clears the Figure. Or use `fig.savefig()` to specify the Figure object.
## Supported File Formats
| Format | Extension | Features |
| --- | --- | --- |
| PNG | .png | Bitmap, supports transparency, most commonly used |
| PDF | .pdf | Vector graphics, suitable for publications, can embed in LaTeX |
| SVG | .svg | Vector graphics, can be edited in browser/editor |
| EPS | .eps | Vector graphics, traditional publishing format |
| JPEG | .jpg / .jpeg | Bitmap, lossy compression, smaller file size but no transparency support |
| TIFF | .tiff / .tif | Bitmap, lossless, suitable for archiving |
* * *
## Usage Examples
### Example 1: Basic Save
## Instance
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,10,100)
fig, ax = plt.subplots(figsize=(6,4))
ax.plot(x, np.sin(x), label='sin(x)')
ax.set_title('Save Figure Demo')
ax.legend()
# Save as PNG
fig.savefig('tutorial_plot.png')
print("tutorial: saved as tutorial_plot.png")
# Save as PDF (vector)
fig.savefig('tutorial_plot.pdf')
print("tutorial: saved as tutorial_plot.pdf")
plt.show()
### Example 2: High Resolution Output + Tight Crop
## Instance
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(8,4))
x = np.linspace(0,2*np.pi,100)
ax.plot(x, np.sin(x), label='sin(x)')
ax.plot(x, np.cos(x), label='cos(x)')
ax.set_title('High Resolution Output')
ax.set_xlabel('Angle (rad)')
ax.legend(loc='outside')# Legend placed outside
# dpi=300: High resolution (suitable for printing)
# bbox_inches='tight': Auto crop to ensure legend doesn't exceed
fig.savefig('tutorial_hires.png', dpi=300, bbox_inches='tight')
print("tutorial: high-res image saved")
plt.show()
### Example 3: Transparent Background + Different Formats
## Instance
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(6,4))
# Set dark background to demonstrate transparency effect
fig.patch.set_facecolor('#2c3e50')
ax.set_facecolor('#34495e')
ax.plot(np.random.randn(100).cumsum(),
color='#1abc9c', linewidth=2)
ax.set_title('Transparent Background',
color='white', fontsize=14)
ax.tick_params(colors='white')
# Transparent background PNG
fig.savefig('tutorial_transparent.png',
transparent=True,# Transparent background
dpi=150, bbox_inches='tight')
# SVG can also be transparent
fig.savefig('tutorial_transparent.svg',
transparent=True,
bbox_inches='tight')
print("tutorial: transparent images saved")
plt.show()
### Example 4: Batch Save Multiple Subplots
## Instance
import matplotlib.pyplot as plt
import numpy as np
# Create a large figure containing multiple charts
data = np.random.randn(4,100)
for i in range(4):
fig, ax = plt.subplots(figsize=(6,4))
ax.plot(data.cumsum(), color=f'C{i}', linewidth=2)
ax.set_title(f'Series {i+1}')
ax.set_xlabel('Step')
ax.set_ylabel('Cumulative Sum')
ax.grid(True, alpha=0.3)
# Batch save, filename contains index
fig.savefig(f'tutorial_series_{i+1}.png',
dpi=200, bbox_inches='tight')
plt.close(fig)# Close to avoid display
print("tutorial: 4 figures saved (series_1 to series_4)")
* * *
## FAQ
### Saved image is completely blank?
Check if savefig() is called after show(). show() may clear the Figure.
Solution: Call savefig() before show(), or use `fig.savefig()` to specify the Figure object.
### Text/labels in image are cropped?
Use `bbox_inches='tight'` for auto crop to ensure all elements are within the image.
If the problem persists, increase the `pad_inches` parameter value.
[ Matplotlib Reference Documentation](https://example.com/matplotlib/matplotlib-apiref.html)
YouTip