我用的是jupyter笔记本,这是核心信息
Python3.5.2 Anaconda 4.1.1 (64位)x(缺省值,2016年7月2日,17:53:06) GCC 4.4.7 20120313 (红帽4.4.7-1)
我在使用k-均值聚类。当我聚在一起时,唯一使用的颜色是蓝色。这并不是一个大的问题,它是如何设置在目前,但我需要扩大它,所以颜色需要不同。我遵循了一个教程,所以我不能百分之百地理解所有的代码。代码在下面。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use("ggplot")
from sklearn.cluster import KMeans
x = [1,5,1.5,8,1,9]
y = [2,8,1.8,8,.6,11]
plt.scatter(x,y)
plt.show()
X = np.array([[1,2],[5,8],[1.5,1.8],[8,8],[1,.6],[9,11]])
kmeans = KMeans(n_clusters=2)
kmeans.fit(X)
centroids = kmeans.cluster_centers_
labels = kmeans.labels_
print(centroids)
print(labels)
colors = ['r','b','y','g','c','m']
for i in range(len(X)):
print("coordinate:",X[i], "label:", labels[i])
plt.plot(X[i][0], X[i][1], colors[labels[i]], markersize = 10)
plt.scatter(centroids[:, 0],centroids[:, 1], marker = "x", s=150, linewidths = 5, zorder = 10)
plt.show()
plt.scatter(x,y)
plt.scatter(centroids[:, 0],centroids[:, 1], marker = "x", s=150, linewidths = 5, zorder = 10)
plt.show()我想我的问题就在于这件事。
colors = ['r','b','y','g','c','m']
for i in range(len(X)):
print("coordinate:",X[i], "label:", labels[i])
plt.plot(X[i][0], X[i][1], colors[labels[i]], markersize = 10)发布于 2016-11-09 20:40:59
我确实弄错了。我以前的解决方案是不正确的。我终于可以好好看看标签和质心的回归了,我认为这应该符合你的要求。
您可以给出一个序列作为color=参数的参数,因此不需要‘s循环
colors = ['r','b','y','g','c','m']
plt.scatter(x,y, color=[colors[l_] for l_ in labels], label=labels)
plt.scatter(centroids[:, 0],centroids[:, 1], color=[c for c in colors[:len(centroids)]], marker = "x", s=150, linewidths = 5, zorder = 10)发布于 2021-05-07 20:22:10
用K表示你会希望每个星系团是不同的颜色。如果您有两个集群,那么模型kmeans将其标签存储在一个类似于[1 1 1 1 0 0 1 0 0 0 1 0 0...]的数组中。若要使用特定颜色,请在开始所有绘图代码并使用列表设置每个点的颜色之前对其进行迭代:
colors = []
for i in kmeans.labels_:
if i == 0:
colors.append('blue')
elif i == 1:
colors.append('orange')如果您想要使用预定义的海运调色板作为您的颜色,您也可以迭代调色板!例如,如果您想使用“深度”调色板:
palette = sns.color_palette('deep')
colors = []
for i in kmeans.labels_:
if i == 0:
colors.append(palette[0])
elif i == 1:
colors.append(palette[1])如果有3种颜色,那么需要为i == 2添加另一个i == 2,依此类推。
然后,在创建绘图时,只需将c参数设置为等于您创建的colors列表:
plt.scatter(df['x'], df['y'], c = colors)
plt.show()https://stackoverflow.com/questions/40496620
复制相似问题