使用 matplotlib 将图形保存到文件时为空 pdf 文件

Empty pdf file when saving figure to file using matplotlib

我正在尝试使用 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 时,我最终得到一个空白文件。有谁知道如何解决这个问题?

您只需在脚本末尾添加以下内容:

with PdfPages('discard1.pdf') as pdf:
    pdf.savefig(fig1)

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

为了他人的教育:

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

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

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

也许这应该作为错误报告?