Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a rectangle over a specific region in a matplotlib graph

I have a graph, computed from some data, drawn in matplotlib. I want to draw a rectangular region around the global maximum of this graph. I tried plt.axhspan, but the rectangle doesn't seem to appear when I call plt.show()

So, how can a rectangular region be drawn onto a matplotlib graph? Thanks!

like image 987
zebra Avatar asked Oct 22 '12 14:10

zebra


People also ask

How do I shade an area in Matplotlib?

You can use ax. axvspan , which apparently does exactely what you want. For better results, usa an alpha value below 0.5, and optionally set color and edge-color/width. If you want the shading to be in a different orientation (horizontal instead of vertical), there is also the ax.


1 Answers

The most likely reason is that you used data units for the x arguments when calling axhspan. From the function's docs (my emphasis):

y coords are in data units and x coords are in axes (relative 0-1) units.

So any rectangle stretching left of 0 or right of 1 is simply drawn off-plot.

An easy alternative might be to add a Rectangle to your axis (e.g., via plt.gca and add_patch); Rectangle uses data units for both dimensions. The following would add a grey rectangle with width & height of 1 centered on (2,3):

from matplotlib.patches import Rectangle import matplotlib.pyplot as plt  fig = plt.figure() plt.xlim(0, 10) plt.ylim(0, 12)  someX, someY = 2, 5 currentAxis = plt.gca() currentAxis.add_patch(Rectangle((someX - .5, someY - .5), 4, 6, facecolor="grey")) 

enter image description here

  • Without facecolor
currentAxis.add_patch(Rectangle((someX - .5, someY - .5), 4, 6, facecolor="none", ec='k', lw=2)) 

enter image description here

like image 97
Hans Avatar answered Sep 22 '22 11:09

Hans