python-3.x - 为集群着色。克米恩斯
问题描述
我目前有以下代码:
我还导入了库 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)
我希望集群中的每个点都被分配了一个索引来相应地改变颜色,但似乎不起作用。
解决方案
该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'
。
推荐阅读
- python - 如何在 PyQt 中创建一个类似于 messageBox 的窗口
- javascript - Vue.js open link in new window
- html - 像 Whatsapp 一样,如何在您键入时进行向上延伸的输入?
- tizen - Tizen Web SDK:如何远程调试(Web 检查器)在手表(Galaxy)上运行的 Web 应用程序?
- c - strcmp 的段错误
- android - 我垂直分配底部的 StackLayout 下面有一个间隙?
- go - 为什么我会从这个简单的 Go 代码中得到这样的输出?
- javascript - javascript 函数只能在页面上运行一次
- r - 名称错误(x)<-值:“名称”属性 [8] 必须与向量 [2] 的长度相同
- c# - 如何在 C# 控制台应用程序中异步运行多个事件处理程序