现在位置: 首页 > Matplotlib 教程 > 正文

Matplotlib savefig() 函数


Matplotlib 参考文档 Matplotlib 参考文档

savefig() 用于将当前 Figure 保存为图像文件,支持 PNG、PDF、SVG、EPS 等多种格式。

它是将 Matplotlib 图表导出为可分享、可嵌入文档的文件的核心方法。

函数定义

pyplot 接口

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 方法

Figure.savefig(fname, *, dpi='figure', format=None, metadata=None,
    bbox_inches=None, pad_inches=0.1, facecolor='auto',
    edgecolor='auto', backend=None, **kwargs)

参数说明

参数类型说明
fnamestr 或 Path 或 file-like输出文件名或文件对象。扩展名自动决定格式,如 'plot.png'、'plot.pdf'、'plot.svg'
dpifloat 或 'figure'输出分辨率(每英寸点数)。'figure' 使用 Figure 自身 dpi。常用:72(屏幕), 150(一般), 300(印刷)
formatstr输出格式,如 'png', 'pdf', 'svg', 'eps', 'jpg'。若未指定,由文件名推断
bbox_inchesstr 或 Bbox裁剪边界:'tight'(紧凑裁剪,去掉多余空白)、None(使用 Figure 原始大小)
pad_inchesfloatbbox_inches='tight' 时的内边距(英寸),默认 0.1
facecolorcolor 或 'auto'输出图像的背景色,'auto' 使用 Figure 的 facecolor
edgecolorcolor 或 'auto'输出图像的边框色
transparentbool若为 True,背景设为透明(仅 png/svg)
metadatadict写入文件的元数据(部分格式支持)

必须在 plt.show() 之前调用 savefig(),因为 show() 会清空 Figure。或者使用 fig.savefig() 指定 Figure 对象。

支持的文件格式

格式扩展名特点
PNG.png位图,支持透明,最常用
PDF.pdf矢量图,适合出版物,可嵌入 LaTeX
SVG.svg矢量图,可在浏览器/编辑器中编辑
EPS.eps矢量图,传统出版格式
JPEG.jpg / .jpeg位图,有损压缩,文件小但不支持透明
TIFF.tiff / .tif位图,无损,适合存档

使用示例

示例 1:基本保存

实例

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()

# 保存为 PNG
fig.savefig('runoob_plot.png')
print("runoob: saved as runoob_plot.png")

# 保存为 PDF(矢量)
fig.savefig('runoob_plot.pdf')
print("runoob: saved as runoob_plot.pdf")

plt.show()

示例 2:高清输出 + 紧凑裁剪

实例

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')  # 图例放在外侧

# dpi=300: 高清画质(适合印刷)
# bbox_inches='tight': 自动裁剪,确保图例不超出
fig.savefig('runoob_hires.png', dpi=300, bbox_inches='tight')
print("runoob: high-res image saved")

plt.show()

示例 3:透明背景 + 不同格式

实例

import matplotlib.pyplot as plt
import numpy as np

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

# 设置深色背景以展示透明效果
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')

# 透明背景 PNG
fig.savefig('runoob_transparent.png',
            transparent=True,          # 透明背景
            dpi=150, bbox_inches='tight')

# SVG 也可以透明
fig.savefig('runoob_transparent.svg',
            transparent=True,
            bbox_inches='tight')
print("runoob: transparent images saved")

plt.show()

示例 4:批量保存多子图

实例

import matplotlib.pyplot as plt
import numpy as np

# 创建一个大图,包含多种图表
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)

    # 批量保存,文件名含索引
    fig.savefig(f'runoob_series_{i+1}.png',
                dpi=200, bbox_inches='tight')
    plt.close(fig)  # 关闭以避免显示

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

常见问题

保存的图片一片空白?

检查 savefig() 是否在 show() 之后调用。show() 可能会清空 Figure。

解决方案:在 show() 之前调用 savefig(),或使用 fig.savefig() 指定 Figure 对象。

图片中的文字/标签被截断?

使用 bbox_inches='tight' 自动裁剪,确保所有元素都在图片内。

如果仍有问题,可增加 pad_inches 参数值。


Matplotlib 参考文档 Matplotlib 参考文档