Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีเพิ่มข้อความภายในสี่เหลี่ยมผืนผ้าใน Matplotlib


วางข้อความตรงกลางสี่เหลี่ยมผืนผ้า

ใช้ annotate() วางข้อความที่จุดกึ่งกลางของ rectangle

ขั้นตอน

  1. สร้าง figure ด้วย figure()
  2. เพิ่ม subplot
  3. สร้าง rectangle ด้วยคลาส Rectangle()
  4. เพิ่ม rectangle patch ลง plot
  5. คำนวณจุดกึ่งกลาง cx, cy ของ rectangle
  6. ใช้ annotate() วางข้อความตรงกลาง
  7. จำกัดแกน x, y ให้เห็นสี่เหลี่ยมชัด
  8. แสดงด้วย 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()

ผลลัพธ์

วิธีเพิ่มข้อความภายในสี่เหลี่ยมผืนผ้าใน Matplotlib