Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a text into a Rectangle?

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

like image 368
tm8cc Avatar asked Jan 25 '13 22:01

tm8cc


People also ask

How do you add text to a rectangle?

To add a rectangle in the plot, use Rectangle() class to get the rectangle object. Add a rectangle patch on the plot. To add text label in the rectangle, we can get the center value of the rectangle, i.e., cx and cy. Use annotate() method to place text on the rectangle.


1 Answers

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

like image 88
Paul H Avatar answered Oct 16 '22 22:10

Paul H