24

I have a code that draws hundreds of small rectangles on top of an image :

example

The rectangles are instances of

    matplotlib.patches.Rectangle

I'd like to put a text (actually a number) into these rectangles, I don't see a way to do that. matplotlib.text.Text seems to allow one to insert text surrounded by a rectangle however I want the rectangle to be at a precise position and have a precise size and I don't think that can be done with text().

smci
  • 26,085
  • 16
  • 96
  • 138
MCF
  • 1,020
  • 2
  • 10
  • 24

1 Answers1

38

I think you need to use the annotate method of your axes object.

You can use properties of the rectangle to be smart about it. Here's a toy example:

import matplotlib.pyplot as plt
import matplotlib.patches as mpatch

fig, ax = plt.subplots()
rectangles = {'skinny' : mpatch.Rectangle((2,2), 8, 2),
              'square' : mpatch.Rectangle((4,6), 6, 6)}

for r in rectangles:
    ax.add_artist(rectangles[r])
    rx, ry = rectangles[r].get_xy()
    cx = rx + rectangles[r].get_width()/2.0
    cy = ry + rectangles[r].get_height()/2.0

    ax.annotate(r, (cx, cy), color='w', weight='bold', 
                fontsize=6, ha='center', va='center')

ax.set_xlim((0, 15))
ax.set_ylim((0, 15))
ax.set_aspect('equal')
plt.show()

annotated rectangles

Paul H
  • 52,530
  • 16
  • 137
  • 125
  • Thanks for the answer. Your technique works but requires the rectangle area to be larger than the width of the word you put in there. In my case the rectangles are really small (as can be seen in the original post image), here what your method gives : [very small rectangle](http://imgur.com/7ySs3eP) – MCF Jan 28 '13 at 13:13
  • 1
    OK. So adjust the size of the text in the `annotate` method with the `fontsize` kwarg and use appropriate strings. I edited the example to include a specified `fontsize`. – Paul H Jan 28 '13 at 18:29
  • 1
    Sure I've thought about it, the difficulty being adjusting the font size with the size of the rectangle.. – MCF Jan 28 '13 at 23:02
  • 1
    What if the box needs to be out of the plot, like below the x-axis? – cgnorthcutt Jan 12 '19 at 19:57