在python中保存绘图只会创建一个空的pdf文档

时间:2014-06-26 03:57:26

标签: python pdf matplotlib charts pdf-generation

我正在使用官方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")

这是我做错了吗?

2 个答案:

答案 0 :(得分:3)

plt.savefig("result.pdf")之前移动plt.show()行应该将图正确保存为pdf文件。

您可能正在使用交互式后端。在plt.show()之后,弹出一个包含该图的窗口。如果然后关闭窗口,则图表消失(类似于plt.close()调用)。因此,如果在关闭绘图窗口后执行此操作,则plt.savefig()无需保存。

答案 1 :(得分:0)

感谢您的澄清,它也为我工作。我正在绘制实时数据,因此我必须将其包含在循环中,然后才开始工作。

def animate(i):     全球arg1     Path =' C:/ Python36 / Somendra /' + arg1 +' .csv'     name = arg1 +' .csv'     pullData = open(Path," r")     dataArray = csv.reader(pullData,delimiter =',')     xar = []     yar = []     对于dataArray中的行:         xar.append(行[0])         yar.append(行[1])     #ax1.clear()     LABELS = [z表示范围内的z(len(xar)]]     ax1.plot(标签,亚尔)     #ax1.plot(XAR,亚尔)     ax1.set_xticks(标签)     ax1.set_xticklabels(xar,rotation =' vertical',fontsize = 10)     plt.savefig(' fig11.png&#39)

如果名称 ==" 主要":     arg1 = str(sys.argv [1])

style.use('fivethirtyeight')
fig = plt.figure(figsize=(8,6))
ax1 = fig.add_subplot(1,1,1)
time.sleep(1)
plt.grid(True)
ani = animation.FuncAnimation(fig, animate, interval=1000)
#plt.savefig('fig11.png')
plt.show()