简体   繁体   English

Matplotlib png output 在报告实验室的 pdf 中出现“损坏”

[英]Matplotlib png output appears "broken" in reportlab's pdf

Does anyone know what could be the reason my matplotlib plot appears "broken" when I print it in PDF through reportlab.有谁知道当我通过 reportlab 在 PDF 中打印时,我的 matplotlib plot 出现“损坏”的原因是什么。

So, this is the Python code I am using:所以,这是我正在使用的 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()

The matplotlib test.png output looks fine: matplotlib test.png output 看起来不错:

在此处输入图像描述

However, the same image in the hello.pdf file looks quite bad:但是,hello.pdf 文件中的同一张图片看起来很糟糕:

在此处输入图像描述

You don't need to use canvas for pdf. You can save image as pdf with desired quality by just changing the extension .png to .pdf in your following line:您不需要将canvas用于 pdf。只需在以下行中将扩展名.png更改为 .pdf,即可将图像保存为具有所需质量的.pdf

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

Also, if you want to adjust the size of the image -as you have written in your code- you can also do something like this (increasing the dpi will increase the picture quality, so broken lines should disappear):此外,如果你想调整图像的大小 - 正如你在代码中所写的那样 - 你也可以这样做(增加dpi会提高图片质量,因此虚线应该消失):

fig = plt.gcf()
fig.set_size_inches(32, 18)
plt.savefig('hello.pdf', bbox_inches='tight', dpi=1000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM