Save plot to image file instead of displaying it

Save plot to image file instead of displaying it

技术背景

在数据可视化过程中,我们常常需要将绘制好的图形保存为文件,而不是直接显示在屏幕上。Matplotlib 是 Python 中常用的绘图库,提供了多种保存图形的方法。此外,不同的开发环境(如 Spyder、Jupyter Notebook)和需求场景(如避免图形窗口弹出、保存多页 PDF、批量保存图形等)可能会影响保存图形的具体实现。

实现步骤

1. 使用 plt.savefig 保存图形

可以通过指定文件扩展名来确定保存的文件格式,例如 .png.pdf

1
2
3
4
from matplotlib import pyplot as plt

plt.savefig('foo.png')
plt.savefig('foo.pdf')

2. 去除图像周围的空白

使用 bbox_inches='tight' 参数可以去除图像周围不必要的空白。

1
plt.savefig('foo.png', bbox_inches='tight')

3. 避免图形显示

在某些情况下,我们不希望图形显示出来。可以使用非交互式后端(如 Agg),或者在保存图形后关闭图形窗口。

1
2
3
4
5
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
plt.savefig('myfig')

或者使用 plt.close(figure_object) 关闭图形窗口:

1
2
3
4
5
import matplotlib.pyplot as plt
fig, ax = plt.subplots(nrows=1, ncols=1)
ax.plot([0, 1, 2], [10, 20, 3])
fig.savefig('path/to/save/image/to.png')
plt.close(fig)

4. 保存多页 PDF

使用 matplotlib.backends.backend_pdf.PdfPages 可以将多个图形保存到一个 PDF 文件中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

with PdfPages('multipage_pdf.pdf') as pdf:
plt.figure(figsize=(3, 3))
plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
plt.title('Page One')
pdf.savefig()
plt.close()

plt.rc('text', usetex=True)
plt.figure(figsize=(8, 6))
x = np.arange(0, 5, 0.1)
plt.plot(x, np.sin(x), 'b-')
plt.title('Page Two')
pdf.savefig()
plt.close()

plt.rc('text', usetex=False)
fig = plt.figure(figsize=(4, 5))
plt.plot(x, x * x, 'ko')
plt.title('Page Three')
pdf.savefig(fig)
plt.close()

d = pdf.infodict()
d['Title'] = 'Multipage PDF Example'
d['Author'] = u'Jouni K. Seppänen'
d['Subject'] = 'How to create a multipage pdf file and set its metadata'
d['Keywords'] = 'PdfPages multipage keywords author title subject'
d['CreationDate'] = datetime.datetime(2009, 11, 13)
d['ModDate'] = datetime.datetime.today()

核心代码

基本保存图形

1
2
3
4
import matplotlib.pyplot as plt

plt.plot([1, 2, 3])
plt.savefig('basic_plot.png')

保存图形并去除空白

1
2
3
4
import matplotlib.pyplot as plt

plt.plot([1, 2, 3])
plt.savefig('tight_plot.png', bbox_inches='tight')

保存多页 PDF

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

with PdfPages('multipage_pdf.pdf') as pdf:
plt.figure(figsize=(3, 3))
plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
plt.title('Page One')
pdf.savefig()
plt.close()

plt.rc('text', usetex=True)
plt.figure(figsize=(8, 6))
x = np.arange(0, 5, 0.1)
plt.plot(x, np.sin(x), 'b-')
plt.title('Page Two')
pdf.savefig()
plt.close()

plt.rc('text', usetex=False)
fig = plt.figure(figsize=(4, 5))
plt.plot(x, x * x, 'ko')
plt.title('Page Three')
pdf.savefig(fig)
plt.close()

d = pdf.infodict()
d['Title'] = 'Multipage PDF Example'
d['Author'] = u'Jouni K. Seppänen'
d['Subject'] = 'How to create a multipage pdf file and set its metadata'
d['Keywords'] = 'PdfPages multipage keywords author title subject'
d['CreationDate'] = datetime.datetime(2009, 11, 13)
d['ModDate'] = datetime.datetime.today()

最佳实践

1. 避免图形显示

在服务器环境或批量处理图形时,使用非交互式后端(如 Agg)可以避免图形窗口弹出,提高处理效率。

2. 清除图形

在保存图形后,使用 plt.clf()fig.clf() 清除图形,避免后续绘图受到影响。

3. 使用 teeplot 管理图形输出

对于需要组织可视化输出的场景,可以使用 teeplot 库,它可以自动管理图形文件输出,根据语义绘图变量生成有意义的文件名。

1
2
3
4
5
6
import seaborn as sns
from teeplot import teeplot as tp

tp.tee(sns.lmplot,
sns.load_dataset("tips"), col="time", hue="sex", x="total_bill", y="tip",
teeplot_show=False, teeplot_verbose=True)

常见问题

1. 保存的图像为空白

如果在 plt.show() 之后调用 plt.savefig(),可能会导致保存的图像为空白。正确的做法是先保存图像,再显示图像。

1
2
3
4
5
import matplotlib.pyplot as plt

plt.plot([1, 2, 3])
plt.savefig('plot.png')
plt.show()

2. Spyder 环境下图形仍会显示

在 Spyder 环境中,默认设置可能会导致图形显示。可以使用 plt.ioff() 禁用交互模式,或者使用 plt.switch_backend('Agg') 切换到非交互式后端。

1
2
3
4
5
import matplotlib.pyplot as plt

plt.ioff()
plt.plot([1, 2, 3])
plt.savefig('spyder_plot.png')

3. 保存的图像尺寸过小

可以使用 fig.set_size_inches((w, h)) 调整图像的尺寸。

1
2
3
4
5
6
import matplotlib.pyplot as plt

fig = plt.figure()
fig.set_size_inches((8, 6))
plt.plot([1, 2, 3])
plt.savefig('large_plot.png')

Save plot to image file instead of displaying it
https://119291.xyz/posts/save-plot-to-image-file-instead-of-displaying-it/
作者
ww
发布于
2025年5月26日
许可协议