3

Does anyone know what could be the reason my matplotlib plot appears "broken" when I print it in PDF through reportlab.

So, this is the Python code I am using:

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:

enter image description here

However, the same image in the hello.pdf file looks quite bad:

enter image description here

Milan
  • 285
  • 3
  • 8
  • I guess it would make sense to export the png file with the exact same dimensions as the space inside the report where you want to place it. Ideally you would probably rather include the image in vector format; pdf [is possible](https://stackoverflow.com/questions/4690585/is-there-a-matplotlib-flowable-for-reportlab/13870512#13870512), but requires a bit more code. Also [using svg](https://stackoverflow.com/questions/5835795/generating-pdfs-from-svg-input) is an option. – ImportanceOfBeingErnest Feb 28 '19 at 10:40
  • especially for that usecase I created [a small package called autobasedoc][1], it has documentation. I hope you find it useful! [1]: https://autobasedoc.readthedocs.io/en/latest/ – skidzo Sep 16 '19 at 11:59

1 Answers1

0

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:

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):

fig = plt.gcf()
fig.set_size_inches(32, 18)
plt.savefig('hello.pdf', bbox_inches='tight', dpi=1000)
Celuk
  • 561
  • 7
  • 17