Natasha
Natasha

Reputation: 1521

Insert a png image in a matplotlib figure

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

Upvotes: 8

Views: 7951

Answers (1)

Stef
Stef

Reputation: 30579

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.

Upvotes: 9

Related Questions