3

I want to insert a scaled image on a figure and align it to right figure border. The following works fine in the interactive windows and when saving as png, but when saving as a pdf the image is too to the left. How can i get the correct behavior for both cases? This happens also if the savefig and figure settings are identical.

import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage
import numpy as np
fig = plt.figure(dpi=100)
image = np.ones((200, 200))
ob = OffsetImage(image, zoom=0.5)
rend = fig.canvas.get_renderer()
w, h, x, d =  ob.get_extent(rend)
fig.images.append(ob)
ob.set_offset((fig.bbox.xmax-w, 0))
plt.show()
fig.savefig("bla.pdf", dpi=100)
tillsten
  • 14,491
  • 5
  • 32
  • 41

1 Answers1

-1

The following code, being more explicit about padding and bounding box, gives the same for png and pdf for me (matplotlib 1.4.3, python 2.7).

import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage
import numpy as np

fig = plt.figure(figsize=(8,6))
image = np.ones((200, 200))
ob = OffsetImage(image, zoom=0.5)
rend = fig.canvas.get_renderer()
w, h, x, d =  ob.get_extent(rend)
fig.images.append(ob)
ob.set_offset((fig.bbox.xmax-w, 0))
fig.savefig("bla.pdf",figsize=(8,6),
                       bbox_inches='tight', 
                       pad_inches=0)

The version of your code (even with plt.show() removed) gave an empty pdf document for me. As to why the above works, I guess it may be a bug with matplotlib or possibility a difference in coordinate system used in saving the pdf vs. the more wysiwyg display/png figure. Could also be matplotlib template, in which case this answer may help...

Community
  • 1
  • 1
Ed Smith
  • 12,716
  • 2
  • 43
  • 55
  • It only seems to work on the first glance: the image is still misplaced, but due to `bbox_inches = 'tight'` it will be included by increasing the size of the pdf. – tillsten Sep 21 '15 at 18:00
  • 1
    The actual problem seem to be caused by the fact that pdfs are always calculated with 72 dpi and OffsetImage ignores that. – tillsten Sep 21 '15 at 18:17
  • Sorry, didn't realise it still wasn't right. PDF apparently doesn't use the dpi setting except for resolution of raster graphics. Does setting `plt.figure(figsize=(width, height))` help as this should impact the PDF. – Ed Smith Sep 22 '15 at 08:03