Matplotlib savefig() Function


Matplotlib 参考文档Matplotlib Reference Documentation

savefig()Used to save the current Figure as an image file, supporting PNG, PDF, SVG, EPS and other formats.

It is the core method for exporting Matplotlib charts to files that can be shared and embedded in documents.

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

ParameterTypeDescription
fnamestr or Path or file-likeOutput filename or file object. The extension automatically determines the format, e.g., 'plot.png', 'plot.pdf', 'plot.svg'
dpifloat or 'figure'Output resolution (dots per inch). 'figure' uses the Figure's own dpi. Common values: 72 (screen), 150 (general), 300 (print)
formatstrOutput format, e.g., 'png', 'pdf', 'svg', 'eps', 'jpg'. If not specified, inferred from the filename
bbox_inchesstr or BboxCropping bounds: 'tight' (tight cropping, removes excess whitespace), None (uses Figure's original size)
pad_inchesfloatPadding (in inches) when bbox_inches='tight', default 0.1
facecolorcolor or 'auto'Background color of the output image; 'auto' uses the Figure's facecolor
edgecolorcolor or 'auto'Border color of the output image
transparentboolIf True, the background is set to transparent (png/svg only)
metadatadictMetadata written to the file (supported by some formats)

Must beplt.show()called beforesavefig(), because show() clears the Figure. Or usefig.savefig()Specify the Figure object.

Supported File Formats

FormatExtensionFeatures
PNG.pngBitmap, supports transparency, most commonly used
PDF.pdfVector graphic, suitable for publications, can be embedded in LaTeX
SVG.svgVector graphic, editable in browsers/editors
EPS.epsVector graphic, traditional publishing format
JPEG.jpg / .jpegBitmap, lossy compression, small file size but does not support transparency
TIFF.tiff / .tifBitmap, lossless, suitable for archiving

Usage Examples

Example 1: Basic Saving

Example

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('example_plot.png')
print("example: saved as example_plot.png")

# Save as PDF (vector)
fig.savefig('example_plot.pdf')
print("example: saved as example_plot.pdf")

plt.show()

Example 2: High-Definition Output + Tight Cropping

Example

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')  # Place the legend outside

# dpi=300: high-definition quality (suitable for printing)
# bbox_inches='tight': automatic cropping to ensure the legend does not exceed the boundary
fig.savefig('example_hires.png', dpi=300, bbox_inches='tight')
print("example: high-res image saved")

plt.show()

Example 3: Transparent Background + Different Formats

Example

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(6, 4))

# Set a dark background to demonstrate the transparency effect
fig.patch.set_facecolor('#2c3e50')
ax.set_facecolor('#34495e')

ax.plot(np.random.randn(100).cumsum(),
        color='#1A6BBC', linewidth=2)
ax.set_title('Transparent Background',
             color='white', fontsize=14)
ax.tick_params(colors='white')

# Transparent background PNG
fig.savefig('example_transparent.png',
            transparent=True,          # Transparent background
            dpi=150, bbox_inches='tight')

# SVG can also be transparent
fig.savefig('example_transparent.svg',
            transparent=True,
            bbox_inches='tight')
print("example: transparent images saved")

plt.show()

Example 4: Batch Saving Multiple Subplots

Example

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[i].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'example_series_{i+1}.png',
                dpi=200, bbox_inches='tight')
    plt.close(fig)  # Close to avoid display

print("example: 4 figures saved (series_1 to series_4)")

FAQ

The saved image is blank?

Check whether savefig() is called after show(). show() may clear the Figure.

Solution: call savefig() before show(), or usefig.savefig()Specify the Figure object.

The text/labels in the image are cut off?

Usebbox_inches='tight'automatic cropping to ensure all elements are within the image.

If the problem persists, you can increase thepad_inchesparameter value.


Matplotlib 参考文档Matplotlib Reference Documentation

Other Extensions