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

วิธีสร้างลูกศรที่วนลูป (Loop Arrow) ใน Matplotlib

การสร้างลูกศรแบบวนลูปด้วย Patch Collection

รวม Wedge (แท่งโค้ง) และ Polygon (หัวลูกศร) ไว้ใน PatchCollection

ขั้นตอนหลัก

  • ตั้งค่าขนาดรูปและ padding
  • สร้างฟังก์ชัน make_loop() ที่รับ center, radius, theta1, theta2
  • สร้าง Wedge สำหรับวงแหวนโค้ง
  • คำนวณตำแหน่งหัวลูกศรจาก geometry
  • สร้าง Polygon สำหรับหัวลูกศร
  • รวมใน PatchCollection ตั้งสี edge และ face
  • เพิ่ม collection ลง axes
  • แสดงผลด้วย show()

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

from matplotlib import pyplot as plt, patches, collections

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

def make_loop(center, radius, theta1=-30, theta2=180):
    rwidth = 0.02
    ring = patches.Wedge(center, radius, theta1, theta2, width=rwidth)
    offset = 0.02
    xcent = center[0] - radius + (rwidth / 2)
    left = [xcent - offset, center[1]]
    right = [xcent + offset, center[1]]
    bottom = [(left[0] + right[0]) / 2., center[1] - 0.05]
    arrow = plt.Polygon([left, right, bottom, left])
    p = collections.PatchCollection(
        [ring, arrow],
        edgecolor='orange',
        facecolor='red'
    )
    ax.add_collection(p)

fig, ax = plt.subplots()
make_loop(center=(.5, .7), radius=.1)
plt.show()

คำอธิบาย

PatchCollection ใช้จัดกลุ่ม patches หลายชิ้นให้มี style เหมือนกัน