How to insert an image (a picture or a photo) in a matplotlib figure

Published: January 27, 2019

DMCA.com Protection Status

To insert an image in matplotlib figure, there is the annotation function. Example, using Lena picture:

Insérer une image dans une figure matplotlib
Insérer une image dans une figure matplotlib

from matplotlib.offsetbox import TextArea, DrawingArea, OffsetImage, AnnotationBbox

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

fig, ax = plt.subplots()

ax.set_xlim(0, 1)
ax.set_ylim(0, 1)

arr_lena = mpimg.imread('Lenna.png')

imagebox = OffsetImage(arr_lena, zoom=0.2)

ab = AnnotationBbox(imagebox, (0.4, 0.6))

ax.add_artist(ab)

plt.grid()

plt.draw()
plt.savefig('add_picture_matplotlib_figure.png',bbox_inches='tight')
plt.show()

References

Image

of