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

Python - วาด Scatter Plot สำหรับ Clustering ด้วย Matplotlib

สร้าง Scatter Plot แสดง Clustering โดยใช้ Matplotlib: สุ่มข้อมูล, กำหนด Cluster และ Centers แล้ว Plot พร้อม Marker ต่างกัน

ขั้นตอน

  1. ตั้งค่า Figure Size และ Layout
  2. สร้างข้อมูล X, Y, Cluster Labels, Centers ด้วย NumPy
  3. สร้าง Figure และ Subplot
  4. Plot Scatter ข้อมูล สีตาม Cluster
  5. Plot Centers ด้วย Marker '+' สีแดง
  6. แสดงด้วย plt.show()

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

import numpy as np
import matplotlib.pyplot as plt

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

x = np.random.randn(10)
y = np.random.randn(10)
Cluster = np.array([0, 1, 1, 1, 3, 2, 2, 3, 0, 2])
centers = np.random.randn(4, 2)

fig = plt.figure()
ax = fig.add_subplot(111)

scatter = ax.scatter(x, y, c=Cluster, s=50)

for i, j in centers:
    ax.scatter(i, j, s=50, c='red', marker='+')

plt.show()

คำอธิบาย

  • c=Cluster กำหนดสีตามค่า Cluster (Colormap Default)
  • s=50 ขนาด Marker
  • Centers: วนลูป Plot จุดกลางแต่ละ Cluster ด้วย Marker '+' สีแดง
  • เหมาะสำหรับ Visualize K-Means Clustering Results