首页 > 解决方案 > Matplolib 修复 pdf 文件的确切大小

问题描述

我有一个从文件创建条形图的代码。我将每个图保存在我使用 rcParams(横向 A4 格式)设置的固定大小的 pdf 文件中:

 fig_size = plt.rcParams["figure.figsize"]
 fig_size[0] = 11  # Landscape A4 format inches
 fig_size[1] = 8 
 plt.rcParams["figure.figsize"] = fig_size

这是将绘图保存为 pdf 的代码。

plt.savefig(filename, bbox_inches="tight", pad_inches=0.5, transparent=True, dpi=300)

我试过 dpi=100, dpi=600 没有变化。

我有大约 40 个 pdf 文件。但是,这些 pdf 的大小略有不同,从 10:35 x 8:36 到几乎 10:47x 8:47 英寸。我说的是页面本身的大小,而不是我理解的磁盘空间取决于用于绘制文件的像素数。我的文件在 13-17 kb 之间……没关系。

不好的是,由于 pdf 页面的大小不匹配,我无法将 pdf 文件合并到报告中。

如何将 pdf 页面的大小设置为完全相同?

在可重现的脚本下方:

"For StackOverFlow"


import matplotlib.pyplot as plt

SMALL_SIZE = 9
MEDIUM_SIZE = 14
BIGGER_SIZE = 18 #28

plt.rc('font', size=SMALL_SIZE)          # controls default text sizes
plt.rc('axes', titlesize=SMALL_SIZE)     # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE)    # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE)    # legend fontsize
plt.rc('axes', titlesize=BIGGER_SIZE)

#x1 = [14, 10, 61, 15, 22]
#y1 = [-10, -2, 1, 8, 12]

#x1 = [0, 1.4, 1.47, 2.3, 2.6]
#y1 = [-1.51, -0.03, 0.04, 0.92, 1.23]

x1=[0.795466667, 1.02, 1.12, 1.155, 1.22, 1.459, 1.47, 1.81]
y1=[-1.50, -0.77, -0.45, -0.34, -0.13, 0.64, 0.68, 1.77]

barWidth = 1.2

r1 = [1.5* i for i in range(0, len(y1))]

fig_size = plt.rcParams["figure.figsize"]
fig_size[0] = 11 #fig_size[0] = 11.69
fig_size[1] = 8 #fig_size[1] = 8.27
plt.rcParams["figure.figsize"] = fig_size

plt.margins(0.005, 0.005)

plt.bar(r1,y1, align='center', color='#9E0032', width=barWidth)

plt.xlabel('Z Code', fontweight='bold')

plt.ylabel('\n Z Value', fontweight='bold') 

# Create names on the x-axis
plt.xticks(r1, x1, fontweight='bold')

plt.yticks(fontweight='bold')

title = "Specimen1"

plt.title(title, fontweight='bold')

filename = title + ".pdf"


#plt.savefig(filename, bbox_inches="tight", pad_inches=0.5, transparent=True, dpi=300)
plt.savefig(filename, pad_inches=0.5, transparent=True, dpi=300)
plt.show()

感谢您的帮助

标签: matplotlib

解决方案


推荐阅读