Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to add a text into a Rectangle in Matplotlib?
To add text into a rectangle in Matplotlib, you can use the annotate() method to place text at the center point of the rectangle. This technique is useful for creating labeled diagrams, flowcharts, or annotated visualizations.
Steps
Create a figure using
figure()methodAdd a subplot to the current figure
Create a rectangle using
patches.Rectangle()classAdd the rectangle patch to the plot
Calculate the center coordinates of the rectangle
Use
annotate()method to place text at the centerSet axis limits and display the plot
Example
Here's how to create a rectangle with centered text ?
from matplotlib import pyplot as plt, patches
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot(111)
# Create a rectangle
rectangle = patches.Rectangle((0, 0), 3, 3, edgecolor='orange',
facecolor="green", linewidth=7)
ax.add_patch(rectangle)
# Calculate center coordinates
rx, ry = rectangle.get_xy()
cx = rx + rectangle.get_width()/2.0
cy = ry + rectangle.get_height()/2.0
# Add text at the center
ax.annotate("Rectangle", (cx, cy), color='black', weight='bold',
fontsize=10, ha='center', va='center')
plt.xlim([-5, 5])
plt.ylim([-5, 5])
plt.show()
Output
The code creates a green rectangle with orange border and "Rectangle" text centered inside it.
Multiple Rectangles with Text
You can also create multiple rectangles with different text labels ?
from matplotlib import pyplot as plt, patches
fig, ax = plt.subplots(figsize=(8, 6))
# Rectangle data: (x, y, width, height, text, color)
rectangles = [
(1, 1, 2, 1.5, "Box 1", "lightblue"),
(4, 2, 2.5, 1, "Box 2", "lightgreen"),
(2, 4, 3, 1.2, "Box 3", "lightcoral")
]
for x, y, width, height, text, color in rectangles:
# Create rectangle
rect = patches.Rectangle((x, y), width, height,
edgecolor='black', facecolor=color, linewidth=2)
ax.add_patch(rect)
# Calculate center and add text
cx = x + width/2.0
cy = y + height/2.0
ax.annotate(text, (cx, cy), ha='center', va='center',
fontsize=12, weight='bold')
ax.set_xlim(0, 8)
ax.set_ylim(0, 6)
ax.set_aspect('equal')
plt.title("Multiple Rectangles with Text")
plt.show()
Key Parameters
| Parameter | Description | Example |
|---|---|---|
ha |
Horizontal alignment | 'center', 'left', 'right' |
va |
Vertical alignment | 'center', 'top', 'bottom' |
fontsize |
Text size | 10, 12, 'large' |
weight |
Font weight | 'bold', 'normal' |
Conclusion
Use annotate() with calculated center coordinates to add text inside rectangles. The ha='center' and va='center' parameters ensure perfect text alignment within the rectangle bounds.
