I want to draw boxes on an image opened from an array in matplotlib. One way I have found to draw boxes is by using add_patch
, but I can't find the way to use it on an image loaded from an array.
This code
arr = np.random.rand(400,400)
fig = plt.imshow(arr)
fig.add_patch(patches.Rectangle((100, 100), 100, 100, fill=False))
produces the error: AttributeError: 'AxesImage' object has no attribute 'add_patch'
asked Nov 14, 2016 at 1:31
1 Answer 1
You have to add your patch to the matplotlib Axes :
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
arr = np.random.rand(400,400)
fig,ax = plt.subplots(1)
ax.imshow(arr)
rect = patches.Rectangle((100, 100), 100, 100, fill=False)
ax.add_patch(rect)
plt.show()
Comments
lang-py
imshow
returns anAxisImage
not aFigure
. AFigure
object does not have anadd_patch
method,Axes
objects do. ApparentlyAxisImage
doesn't inherit fromAxisBase
however. You can get the axes of anAxisImage
through theaxes
property. egplt.imshow(arr).axes