ใช้ patches.Rectangle สร้างสี่เหลี่ยม แล้วเพิ่ม Label ผ่านพารามิเตอร์ label และแสดง Legend
ขั้นตอน
- ตั้งค่าขนาด Figure
- สร้าง Figure และ Axes
- สร้าง Rectangle Patch พร้อม Label
- เพิ่ม Patch เข้า Axes
- แสดง Legend
- แสดงผล
ตัวอย่างโค้ด
import matplotlib.pyplot as plt
import matplotlib.patches as patches
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = y = 0.1
fig = plt.figure()
ax = fig.add_subplot(111)
# สร้าง Rectangle พร้อม Label
patch = ax.add_patch(patches.Rectangle(
(x, y), 0.5, 0.5,
alpha=0.5, facecolor='red', label='Rectangle'
))
plt.legend(loc='upper right')
plt.show()
Patch Types อื่นๆ
# Circle
circle = patches.Circle((0.5, 0.5), 0.3, label='Circle')
# Ellipse
ellipse = patches.Ellipse((0.5, 0.5), 0.6, 0.3, label='Ellipse')
# Polygon
poly = patches.Polygon([[0,0], [1,0], [0.5,1]], label='Triangle')
# FancyBboxPatch (มุมโค้ง)
fancy = patches.FancyBboxPatch((0.1, 0.1), 0.5, 0.5,
boxstyle="round,pad=0.1", label='Rounded')
ผลลัพธ์
กราฟแสดงสี่เหลี่ยมสีแดงโปร่งใส พร้อม Legend "Rectangle" ที่มุมขวาบน