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()
Related videos on Youtube
Author by
tm8cc
Updated on April 30, 2020Comments
-
tm8cc about 4 years
I have a code that draws hundreds of small rectangles on top of an image :
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 over 11 yearsThanks 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 over 11 yearsOK. So adjust the size of the text in the
annotate
method with thefontsize
kwarg and use appropriate strings. I edited the example to include a specifiedfontsize
. -
tm8cc over 11 yearsSure I've thought about it, the difficulty being adjusting the font size with the size of the rectangle..
-
cgnorthcutt over 5 yearsWhat if the box needs to be out of the plot, like below the x-axis?