kmeans scatter plot: plot different colors per cluster kmeans scatter plot: plot different colors per cluster python python

kmeans scatter plot: plot different colors per cluster


from sklearn.cluster import KMeansimport matplotlib.pyplot as plt# Scaling the data to normalizemodel = KMeans(n_clusters=5).fit(X)# Visualize it:plt.figure(figsize=(8, 6))plt.scatter(data[:,0], data[:,1], c=model.labels_.astype(float))

Now you have different color for different clusters.


The color= or c= property should be a matplotlib color, as mentioned in the documentation for plot.

To map a integer label to a color just do

LABEL_COLOR_MAP = {0 : 'r',                   1 : 'k',                   ....,                   }label_color = [LABEL_COLOR_MAP[l] for l in labels]plt.scatter(x, y, c=label_color)

If you don't want to use the builtin one-character color names, you can use other color definitions. See the documentation on matplotlib colors.


It should work:

from sklearn.cluster import KMeans;cluster = KMeans(10);cluster.fit(M);cluster.labels_;plt.scatter(M[:,0],M[:,1], c=[matplotlib.cm.spectral(float(i) /10) for i in cluster.labels_]);