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

วิธีหาจุดกึ่งกลางของชุดจุดใน Python


คำนวณ centroid ของชุดจุด

หาจุดกึ่งกลางโดยเฉลี่ยค่า x และค่า y แยกกัน

ขั้นตอน

  1. สร้าง list ข้อมูล x และ y
  2. วาดจุดด้วย plot()
  3. คำนวณจุดกึ่งกลาง: (sum(x)/len(x), sum(y)/len(y))
  4. วาดจุดกึ่งกลางบนกราฟ
  5. เพิ่ม annotation ป้ายกำกับจุดกึ่งกลาง
  6. แสดงด้วย show()

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

from matplotlib import pyplot as plt

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

x = [5, 1, 3, 2, 8]
y = [3, 6, 1, 0, 5]

plt.plot(x, y)
center = sum(x)/len(x), sum(y)/len(y)
plt.plot(center[0], center[1], marker='o')

plt.annotate("center", xy=center, xytext=(-20, 20),
             textcoords='offset points', ha='right', va='bottom',
             bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
             arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'))

plt.show()

ผลลัพธ์

วิธีหาจุดกึ่งกลางของชุดจุดใน Python