John Crow John Crow - 1 year ago 99
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 Source

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)

rect = patches.Rectangle((100, 100), 100, 100, fill=False)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download