0

Using python, I want to place a small square on figure that I have. I am trying to do that using matplotlib.patches.Rectangle.

My problem is that I want it to appear outside the axes of the figure. So say my y axis runs from 0 to 100, I want my square to appear at, say, 110.

But currently, I create my rectangle (there are actually multiple), then create a PatchCollection object and finally add it to the axis:

ax.add_collection(my_collection).

So because this is an axis object, it doesn't make sense to ask the rectangle to appear outside the range of the axis. The code runs, but the rectangles are never visible (or maybe I can just see the edges peeking out if I want it to appear at a y axis of, say 95):

enter image description here

How can I place a rectangle that will appear outside the axes. Do I have to create another set of axes or something like that?

user1551817
  • 6,693
  • 22
  • 72
  • 109
  • 1
    It would be best to post a minimal reproducible question with some code. – Tom de Geus Dec 03 '18 at 14:26
  • 1
    First add your rectangle, then redefine the range of your yaxis using [ylim](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.ylim.html) –  Dec 03 '18 at 14:27
  • I don't see how changing my ylim will help. Either the rectangle will be inside my axes (which I don't want - I want it outside the axes), or the rectangle will not be visible. – user1551817 Dec 03 '18 at 14:41
  • I can try to add a mwe later if it helps. – user1551817 Dec 03 '18 at 14:42
  • 1
    Do you want the rectangle to be defined in data coordinates? Or maybe rather in coordinates relative to the axes? – ImportanceOfBeingErnest Dec 03 '18 at 14:46
  • 1
    @user1551817 you mean having a rectangle outside the **plot**? something like [this](https://stackoverflow.com/questions/41469207/how-to-draw-rectangle-outside-of-the-plot-frame-in-matplotlib)? –  Dec 03 '18 at 14:55

1 Answers1

1

Use addpatch:

ax.add_patch(patches.Rectangle((xpos, ypos), width, height,
                               facecolor='green', clip_on=False))

and set xpos, ypos, width and height to your desired values

  • If you can edit this to say that "clip_on=False" is required - as in the link you provided in your comment to the original question - I can accept this as the answer. Thank you. – user1551817 Dec 03 '18 at 16:34
  • added clip_on=False –  Dec 04 '18 at 12:01