Skip to main content
 首页 » 编程设计

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

2024年10月24日11sharpest

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