7

I'm trying to insert a png image in matplotlib figure (ref)

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.figure import Figure
from matplotlib.offsetbox import OffsetImage, AnnotationBbox


ax = plt.subplot(111)
ax.plot(
    [1, 2, 3], [1, 2, 3],
    'go-',
    label='line 1',
    linewidth=2
 )
arr_img = plt.imread("stinkbug.png")
im = OffsetImage(arr_img)
ab = AnnotationBbox(im, (1, 0), xycoords='axes fraction')
ax.add_artist(ab)
plt.show()

Inset image:

enter image description here

Output obtained:

enter image description here

I'd like to know how to resize the image that has to be inserted to avoid overlaps.

EDIT: Saving the figure

ax.figure.savefig("output.svg", transparent=True, dpi=600, bbox_inches="tight")

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Natasha
  • 1,111
  • 5
  • 28
  • 66

1 Answers1

8

You can zoom the image and the set the box alignment to the lower right corner (0,1) plus some extra for the margins:

im = OffsetImage(arr_img, zoom=.45)
ab = AnnotationBbox(im, (1, 0), xycoords='axes fraction', box_alignment=(1.1,-0.1))

enter image description here

You may also want to use data coordinates, which is the default, and use the default box_alignment to the center, e.g. ab = AnnotationBbox(im, (2.6, 1.45)). See the xycoords parameter doc for more information about various coordinate options.

Stef
  • 28,728
  • 2
  • 24
  • 52
  • Hi @Stef When I try to save this file `fig.savefig("output.svg", transparent=True, dpi=600, bbox_inches="tight")`, unfortunately I am not abele to find the inset in the output image – Natasha Dec 21 '20 at 08:58
  • `savefig` works for me correctly ( matplotlib version 3.3.1). What version are you using? – Stef Dec 21 '20 at 09:37
  • hm, all I can say is that it works for me without any problems, see https://i.stack.imgur.com/OtUKI.png, using exactly the command you gave in your comment or edit. – Stef Dec 21 '20 at 16:01
  • Sorry, I forgot to mention the version last time. I'm using matplotlib 3.3.3 – Natasha Dec 21 '20 at 16:08
  • [here](https://file.io/tJVMtVi0h4sE) is my output.svg as shown in the browser in the previous comment, does it look correctly when you open it? – Stef Dec 21 '20 at 16:15
  • Thanks a lot for sharing the image. I see the same problem when I download and open the image in the Pycharm window. When I open it in a browser it works without any problem. – Natasha Dec 21 '20 at 16:45