singularli
singularli

Reputation: 225

Is it allowed to draw a matplotlib.patches.Rectangle on a blank figure with matplotlib?

This code adds an rectangle on the Lenna image.

imgurl = 'https://upload.wikimedia.org/wikipedia/en/thumb/7/7d/Lenna_%28test_image%29.png/330px-Lenna_%28test_image%29.png'
f = urllib.request.urlopen(imgurl)
img = plt.imread(f)
fig,ax = plt.subplots(1)
ax.imshow(img)
rect = patches.Rectangle((50, 50), 50, 30, linewidth=1, edgecolor='b', facecolor='w')
ax.add_patch(rect)
plt.show()

while this code cannot do the job on a blank figure

fig,ax = plt.subplots(1)
rect = patches.Rectangle((50, 50), 50, 30, linewidth=1, edgecolor='b', facecolor='r')
ax.add_patch(rect)
plt.show()

why is that?

Upvotes: 0

Views: 474

Answers (1)

dm2
dm2

Reputation: 4275

Running your second part of code I get:

enter image description here

Please notice the x and y axis scale. They each go up to 1.0, but your rectangle patch has coordinates of (50,50). Let's expand the axis limits:

fig,ax = plt.subplots(1)
rect = mpl.patches.Rectangle((50,50), 50, 30, linewidth=1, edgecolor='b', facecolor='r')
ax.add_patch(rect)
ax.set_xlim(left = 0, right = 150)
ax.set_ylim(bottom = 0, top = 150)
plt.show()

And you get:

enter image description here

As you can see, it is plotting the rectangle onto an empty axis, it's just that you couldn't see it the first time around, due to rectangle being out of the view of the axis.

Upvotes: 2

Related Questions