首页 > 解决方案 > 为集群着色。克米恩斯

问题描述

我目前有以下代码:

我还导入了库 numpy 和 matplotlib。

def colorTheCluster(data,centroidCoordinates):
index = AssignPointsToCluster(data,centroidCoordinates) #index contains an 1d array of size 1000 of values [0 1 2 1 3 0....]
indexList = list(index) # i wanted to make it into a list so i can use a for loop
colorMap = {0:'r', 1 : 'b', 2:"y", 3: 'p', 4 :'g'} 
for num in indexList: #[0,1,1,2,3,0,0...]
    for keys in colorMap.keys(): #{1, 2, 0 , 4}
        if keys == num:
            plt.scatter(data[:,0], data[:,1], marker = '+', c = colorMap[0])
        elif keys == num:
            plt.scatter(data[:,0], data[:,1], marker = '+', c = colorMap[1])
        elif keys == num:    
            plt.scatter(data[:,0], data[:,1], marker = '+', c = colorMap[2])
        elif keys == num:
            plt.scatter(data[:,0], data[:,1], marker = '+', c = colorMap[3])
        elif keys == num:
            plt.scatter(data[:,0], data[:,1], marker = '+', c = colorMap[4])
return plt.show()

print(colorTheCluster(data(), centroidCoordinates()))

data()是一个包含 1000 x 2 数组的函数

centroidCoordinates()是一个 m x2 的数组(在这种情况下,我使用了 m = 4)

我希望集群中的每个点都被分配了一个索引来相应地改变颜色,但似乎不起作用。

标签: python-3.xk-means

解决方案


plt.scatter函数接受一个参数c——这可以是与您的数据长度相同的列表/数组。

# make some fake data
data = np.random.random([1000,2])
index = np.random.choice([0,1,2,3], size=len(data))

# scatter plot the data, using `index` to indicate color
plt.scatter(data[:,0], data[:,1], c=index)
# or alternatively:
plt.scatter(*data.T, c=index)

要定义特定颜色,您需要制作一个颜色图:

import matplotlib.colors as mcols

# define a colormap using a list of custom colors
cmap = mcols.ListedColormap(['r','b','y','purple','g'])

# scatter plot the data using your new colormap
plt.scatter(*data.T, c=index, cmap=cmap)

请注意,我用'p', 替换了 matplotlib 无法理解的颜色代码'purple'


推荐阅读