使用matplotlib将图形保存到文件时,生成的PDF文件为空。

3

我正在尝试使用matplot、Python 2.7和Windows 7将图形保存为pdf格式。我可以将图形保存为.png格式,但是当我尝试将其保存为.pdf格式时,文件为空白。以下是一些示例代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

x = [1, 2, 3, 4, 5]
y = [6, 7, 8, 9, 10]

linewidthPlot = '2'
linestylePlot = '-'
markerPlot = 'o'
colorPlot = 'b'

xlabel = 'x'
ylabel = 'y'
title = 'x v y'

# Plot the data using matplot.
fig1 = plt.figure()
ax1 = fig1.gca()
line1, = plt.plot(x, y, linewidth=linewidthPlot,
                  linestyle=linestylePlot, marker=markerPlot, color=colorPlot)

axisScale = 0.05
xmin = min(x) - (axisScale * (max(x) - min(x)))
xmax = max(x) + (axisScale * (max(x) - min(x)))
ymin = min(y) - (axisScale * (max(y) - min(y)))
ymax = max(y) + (axisScale * (max(y) - min(y)))
plt.axis([xmin, xmax, ymin, ymax])
ax1.ticklabel_format(useOffset=False)
plt.grid()

# Add a legend.
first_legend = plt.legend([line1], ["data"], loc=1, numpoints=1)

# Label the axes.
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(title)

#pp = PdfPages("discard1.pdf")
#plt.savefig(pp, format='pdf')
#pp.close()
plt.savefig('discard1.png')
plt.show()

这段代码是有效的,但当我将文件名更改为discard1.pdf或使用PdfPages函数生成multipage PDF时,我得到的是一个空白文件。有人知道如何解决这个问题吗?
2个回答

1
你只需要将以下内容添加到脚本的末尾即可:
with PdfPages('discard1.pdf') as pdf:
    pdf.savefig(fig1)

这将生成一个您的图形的PDF文件。

这个建议没有成功。我也看不出来这与我上面提到的注释代码有什么不同。 - grover
这对我来说不起作用,使用Windows 7,Matplotlib 1.4.3,TkAgg和Python 2.7.10。我还尝试了在matplotlib中使用Qt4Agg后端。 - grover
这很奇怪,你创建的空白PDF有多大?我的是9,419字节。 - Martin Evans
这与我的输出文件大小相同....也许是pdf浏览器的问题?我正在使用Adobe Reader XI。 如果是这样的话,我不明白为什么Adobe不能呈现该图。 - grover
看起来你并不孤单 matplotlib 生成的 PDF 无法在 Acrobat Reader 中查看 - Martin Evans
显示剩余3条评论

1

为了他人的教育:

正如Martin Evans所指出的那样,这是Adobe Reader和一些其他pdf阅读器无法查看matplotlib创建的pdf图形的问题。

解决方案是将linewidthPlot ='2'更改为linewidthPlot = 2,即:

line1, = plt.plot(x, y, linewidth=linewidthPlot,
              linestyle=linestylePlot, marker=markerPlot, color=colorPlot)

也许应该将此报告为错误?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接