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

การเพิ่ม Label ให้ Patch ใน Matplotlib

ใช้ patches.Rectangle สร้างสี่เหลี่ยม แล้วเพิ่ม Label ผ่านพารามิเตอร์ label และแสดง Legend

ขั้นตอน

  1. ตั้งค่าขนาด Figure
  2. สร้าง Figure และ Axes
  3. สร้าง Rectangle Patch พร้อม Label
  4. เพิ่ม Patch เข้า Axes
  5. แสดง Legend
  6. แสดงผล

ตัวอย่างโค้ด


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" ที่มุมขวาบน