Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách tìm tâm của tập điểm bằng Python

Tâm (centroid) = trung bình tọa độ x và y của tất cả điểm.

  • Tạo lists x, y.
  • plt.plot(x, y).
  • center = (sum(x)/len(x), sum(y)/len(y)).
  • plt.plot(center[0], center[1], marker='o').
  • annotate "center" với mũi tên và box vàng.
  • show().

Ví dụ

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()

Kết quả

Đồ thị 5 điểm, điểm tâm (centroid) được đánh dấu và chú thích.