สร้าง Scatter Plot แสดง Clustering โดยใช้ Matplotlib: สุ่มข้อมูล, กำหนด Cluster และ Centers แล้ว Plot พร้อม Marker ต่างกัน
ขั้นตอน
- ตั้งค่า Figure Size และ Layout
- สร้างข้อมูล X, Y, Cluster Labels, Centers ด้วย NumPy
- สร้าง Figure และ Subplot
- Plot Scatter ข้อมูล สีตาม Cluster
- Plot Centers ด้วย Marker '+' สีแดง
- แสดงด้วย
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