Đặt text ở tâm hình chữ nhật bằng annotate() với tọa độ center.
- Tạo figure, ax = add_subplot(111).
- rect = patches.Rectangle((0,0), 3, 3, edgecolor='orange', facecolor='green', linewidth=7).
- ax.add_patch(rect).
- rx, ry = rect.get_xy(); cx = rx + width/2; cy = ry + height/2.
- ax.annotate("Rectangle", (cx, cy), color='black', weight='bold', fontsize=10, ha='center', va='center').
- xlim, ylim, show().
Ví dụ
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)
rectangle = patches.Rectangle((0, 0), 3, 3, edgecolor='orange', facecolor="green", linewidth=7)
ax.add_patch(rectangle)
rx, ry = rectangle.get_xy()
cx = rx + rectangle.get_width()/2.0
cy = ry + rectangle.get_height()/2.0
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()
Kết quả
Hình chữ nhật xanh lá viền cam, chữ "Rectangle" đen in đậm chính giữa.