4

I want to plot rectangles in different subplots (find the code below), but it doesn't work. With arrays of numbers the code works (and I get the three subplots), however, with Rectangles is different, and I get two empty subplots and one with the rectangle. Any ideas about what's wrong? Thanks!

n = 3
fig = plt.figure()

for i in xrange(n):
    ax = fig.add_subplot(n, 1, i+1)
    ax.add_patch(matplotlib.patches.Rectangle((i,0), 100, 100, color="green"))

plt.show()

2 Answers 2

4

The mistake you are doing is adding (i,0) in the matplotlib.Patches.Rectangle section. When you do so:

For the first loop, i is 0 and the co-ordinates are (0,0).

In the second loop your i becomes 1, so the co-ordinates will becomes (1,0)! This makes the lower left of your rectangle to take co-ordinates (1,0).

This code will work:

import matplotlib.pyplot as plt
import matplotlib

n = 3
fig = plt.figure()

for i in range(n):
    ax = fig.add_subplot(n,1,i+1)
    ax.add_patch(matplotlib.patches.Rectangle((0,0), 100, 100, color="green"))

plt.show()

The reason this works is that the co-ordinates of your lower left of the rectangle is always (0,0). This produces enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

Interesting. I didn't think that the increasing x coordinates were a mistake. But your solution still only show a very small part of the rectangles.
@hitzg yes that's true. The OP wanted three subplots with rectangles in it in the first place!! So the mistake the OP was making was rectified
@ThePredator +1 for "rectified" pun.
2

Matplotlib does not automatically set the axes limits when drawing patches. The patches in your example are drawn, but the second and third have coordinates (1,0) and (2,0) and are out of the standard axes limits (0,1). You can let matplotlib do that for you with:

ax.relim()
ax.autoscale_view()

or do it manually:

ax.set_ylim((0,110))
ax.set_xlim((0,110))

In both cases you have to do in your loop (i.e. for each axes) and after your call to add_patch.

Comments

Your Answer

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.