Insert a png image in a matplotlib figure
Asked Answered
T

1

8

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

Ticklish answered 21/12, 2020 at 4:20 Comment(0)
G
9

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.

Gschu answered 21/12, 2020 at 8:3 Comment(6)
Hi @Gschu 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 imageTicklish
savefig works for me correctly ( matplotlib version 3.3.1). What version are you using?Gschu
hm, all I can say is that it works for me without any problems, see i.sstatic.net/OtUKI.png, using exactly the command you gave in your comment or edit.Gschu
Sorry, I forgot to mention the version last time. I'm using matplotlib 3.3.3Ticklish
here is my output.svg as shown in the browser in the previous comment, does it look correctly when you open it?Gschu
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.Ticklish

© 2022 - 2024 — McMap. All rights reserved.