2

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
  • imshow returns an AxisImage not a Figure. A Figure object does not have an add_patch method, Axes objects do. Apparently AxisImage doesn't inherit from AxisBase however. You can get the axes of an AxisImage through the axes property. eg plt.imshow(arr).axes Commented Nov 14, 2016 at 2:08

1 Answer 1

3

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()
answered Nov 14, 2016 at 1:48

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.