วางข้อความตรงกลางสี่เหลี่ยมผืนผ้า
ใช้ annotate() วางข้อความที่จุดกึ่งกลางของ rectangle
ขั้นตอน
- สร้าง figure ด้วย figure()
- เพิ่ม subplot
- สร้าง rectangle ด้วยคลาส Rectangle()
- เพิ่ม rectangle patch ลง plot
- คำนวณจุดกึ่งกลาง cx, cy ของ rectangle
- ใช้ annotate() วางข้อความตรงกลาง
- จำกัดแกน x, y ให้เห็นสี่เหลี่ยมชัด
- แสดงด้วย show()
ตัวอย่างโค้ด
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()
ผลลัพธ์
