John Crow John Crow - 26 days ago 12
Python Question

Adding patches to numpy array opened in matplotlib

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

, 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'

Answer

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()