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

标签 python pdf matplotlib plot figure

我正在尝试使用 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 文件。

关于python - 使用 matplotlib 将图形保存到文件时为空 pdf 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33139658/

相关文章:

python - Pandas - 规范化 Json 列表

Android 在线 PDF 加载 - 通过 Google 文档预览不可用错误

java - 如何将 PDF 转换为 JSON/EXCEL/WORD 文件?

r - 如何以较小的 R 大小将 ggplots 保存为 PDF?

python - 手动图例中的自定义标记边缘样式

python - Linux 中的 ImageGrab 替代方案

python - 使用 tf slim 重新训练预训练的 ResNet-50 模型以进行分类

python - 如何在Python中将两个变量绘制为直方图?

python - 我可以将参数添加到 python 属性以减少代码重复吗?

python - 计算范围内的出现次数