在Python中保存图形只生成一个空的PDF文档

3 投票
1 回答
6103 浏览
提问于 2025-04-18 11:07

我正在使用官方matplotlib页面上的示例代码,地址是 http://matplotlib.org/examples/api/barchart_demo.html

#!/usr/bin/env python
# a bar plot with errorbars
import numpy as np
import matplotlib.pyplot as plt

N = 5
menMeans = (20, 35, 30, 35, 27)
menStd =   (2, 3, 4, 1, 2)

ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd)

womenMeans = (25, 32, 34, 20, 25)
womenStd =   (3, 5, 2, 3, 3)
rects2 = ax.bar(ind+width, womenMeans, width, color='y', yerr=womenStd)

# add some
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5') )

ax.legend( (rects1[0], rects2[0]), ('Men', 'Women') )

def autolabel(rects):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height),
                ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)

plt.show()

这个图表显示得非常正确。不过,如果我想保存它,在代码的最底部使用以下命令时,它并没有保存这个图表。

plt.savefig("result.pdf")

这是我做错了什么吗?

1 个回答

6

plt.savefig("result.pdf") 这一行放在 plt.show() 之前,这样就能正确地把图保存为 PDF 文件。

你可能在使用一个交互式的后端。调用 plt.show() 后,会弹出一个包含图表的窗口。如果你关闭了这个窗口,图就没了(这和调用 plt.close() 是一样的)。所以,如果你在关闭图表窗口之后再调用 plt.savefig(),就没有东西可以保存了。

撰写回答