【发布时间】:2019-06-22 12:53:19
【问题描述】:
我在 Python 中基于从 .txt 文件导入的数据构建了 Kmeans 聚类。我已经生成了 100 个质心,并且使用 Matplotlib 绘制了两个图形以显示这些质心:一个图形包含点云(源自 .txt 文件),代表数据之前聚类,以及另一个包含黑色星星的图形来标记每个质心。
我应该怎么做才能以随机选择的特定颜色而不是黑色星星来绘制每个质心?这意味着每个质心组的点将具有不同的颜色。
代码:
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.cluster import KMeans
#building the 22797x3 array:
#loading the first array from .txt file, 22797x400 long.
array = np.loadtxt('C:\Scripts/final_array_2.txt', usecols=range(400))
array = np.float32(array)
#plotting data before the clustering:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(result[:, 0], result[:, 1], result[:, 2], alpha = 0.1)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
# Initializing KMeans, plotting clusters
kmeans = KMeans(n_clusters=100)
# Fitting with inputs
kmeans = kmeans.fit(result)
# Predicting the clusters
labels = kmeans.predict(result)
# Getting the cluster centers
C = kmeans.cluster_centers_
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(result[:, 0], result[:, 1], result[:, 2])
ax.scatter(C[:, 0], C[:, 1], C[:, 2], marker='*', c='#050505', s=1000)
plt.show()
以上代码的结果
聚类前的数据: https://i.stack.imgur.com/IXa7R.png
黑星簇后的数据:https://i.stack.imgur.com/1u4JY.png
我需要得到什么(类似的例子,不是相同的点云): https://i.stack.imgur.com/K5oDT.png 在这种情况下,它将是 100 种颜色,而不仅仅是三种。
有什么帮助吗?
【问题讨论】:
-
您可以通过
c=z指定每个绘制点的颜色,其中z是与C[:,0]形状相同的某个数组。 AFAIK,KMeans 的标签是按中心的顺序枚举的,所以c=range(len(C[:,1]))。请注意,这不是随机的,但是您可以根据需要对数组进行洗牌。
标签: python matplotlib k-means