Matplotlib生成的png图片在Reportlab的pdf中显示不正常

3

有人知道为什么当我通过reportlab将matplotlib图形打印成PDF时,这个图形看起来"损坏"了吗?

这是我使用的Python代码:

list = range(6)

fig = plt.figure(figsize=(10, 4))
ax = plt.subplot(111)

ax.plot(list, [2*x for x in list] , label='y = 2x')
ax.plot(list, [0.5*x for x in list], label='y = 0.5*x')
ax.plot(list, list, label='y = x')

plt.xlabel('x')
plt.ylabel('y')
plt.title("Sample Plot")

plt.grid(True, which='major', axis='y')

box = ax.get_position()
ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])

ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.1), ncol=3,
          fontsize='small')

plt.savefig('test.png',dpi=1000) 

c = canvas.Canvas("hello.pdf")
c.drawImage('test.png', 100, 600, width=4 * 100, height=4 * 40)
c.showPage()
c.save()

Matplotlib的test.png输出看起来很好:

在这里输入图片描述

然而,同一张图片在hello.pdf文件中看起来相当糟糕:

在这里输入图片描述


我猜将png文件导出为与报告内所需放置的空间完全相同的尺寸可能是有意义的。理想情况下,您可能更愿意以矢量格式包含图像; pdf 是可能的,但需要更多的代码。此外,使用svg也是一种选择。 - ImportanceOfBeingErnest
特别针对这种用例,我创建了一个名为autobasedoc的小包,它有文档。希望你觉得它有用! - skidzo
1个回答

0

你不需要使用canvas来处理PDF。只需将扩展名.png更改为.pdf,即可通过以下代码行以所需的质量保存图像为PDF:

plt.savefig('test.pdf',dpi=1000)

此外,如果您想调整图像的大小 - 如您在代码中所写 - 您也可以执行以下操作(增加 dpi 将提高图片质量,因此断线应该会消失):
fig = plt.gcf()
fig.set_size_inches(32, 18)
plt.savefig('hello.pdf', bbox_inches='tight', dpi=1000)

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