How to add a text into a Rectangle?

22,017

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

Share:
22,017

Related videos on Youtube

tm8cc
Author by

tm8cc

Updated on April 30, 2020

Comments

  • tm8cc
    tm8cc about 4 years

    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().

  • tm8cc
    tm8cc over 11 years
    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
  • Paul H
    Paul H over 11 years
    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.
  • tm8cc
    tm8cc over 11 years
    Sure I've thought about it, the difficulty being adjusting the font size with the size of the rectangle..
  • cgnorthcutt
    cgnorthcutt over 5 years
    What if the box needs to be out of the plot, like below the x-axis?