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

การพลอตลูกศรแสดงระยะทางใน Technical Drawing ด้วย Matplotlib

ใช้ plt.annotate() พร้อม arrowprops วาดลูกศรสองหัวระหว่างสองเส้นแนวนอน (axhline) แล้วเพิ่มข้อความระยะทางด้วย annotate อีกครั้ง

ขั้นตอนการทำงาน

  1. ตั้งค่าขนาดรูปและเลย์เอาต์
  2. วาดเส้นแนวนอน 2 เส้นด้วย plt.axhline()
  3. วาดลูกศรด้วย plt.annotate('', xy=(x1,y1), xytext=(x2,y2), arrowprops=dict(arrowstyle='<->'))
  4. เพิ่มข้อความระยะทางด้วย annotate อีกครั้ง ตั้งตำแหน่งกลาง
  5. แสดงผล

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

from matplotlib import pyplot as plt

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

plt.axhline(3.5)
plt.axhline(2.5)

plt.annotate('', xy=(0.5, 3.5), xycoords='data',
             xytext=(0.5, 2.5), textcoords='data',
             arrowprops={'arrowstyle': '<->'})

plt.annotate(r'$\it{d=1}$', xy=(0.501, 3.0), xycoords='data',
             xytext=(0.5, 3.5), textcoords='offset points')

plt.show()

ผลลัพธ์

การพลอตลูกศรแสดงระยะทางใน Technical Drawing ด้วย Matplotlib