pythonmatplotlibscikit-learnmean-shift

Color of the center of the clusters do not match with the color of its data points


I have a working example of Mean Shift clustering using Pandas and Sci-kit learn. I am new to Python so I think I am missing something basic here. Here is my working code:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import MeanShift
from matplotlib import style
style.use("ggplot")


filepath = "./Probes1.xlsx"
X = pd.read_excel(filepath, usecols="B:I", header=1)
df=pd.DataFrame(data=X)
np_array = df.values
print(np_array)

ms=MeanShift()
ms.fit(np_array)

labels= ms.labels_
cluster_centers = ms.cluster_centers_
print("cluster centers:")
print(cluster_centers)

labels_unique = np.unique(labels)
n_clusters_=len(labels_unique)

print("number of estimated clusters : %d" % n_clusters_)
#colors = 10*['r.','g.','b.','c.','k.','y.','m.']

for i in range(len(np_array)):
    plt.scatter(np_array[i][0], np_array[i][1], edgecolors='face' )
plt.scatter(cluster_centers[:,0],cluster_centers[:,1],c='b',
   marker = "x", s = 20, linewidths = 5, zorder = 10)
plt.show()

Here is the plot that I get from this code :

Plot

However the color of the centers of the clusters do not match with its data points. Any help would be appreciated. Currently I have set my center colors to blue ('b'). Thank you!

EDIT : I was able to create this! 2D-plot with perfect colors

EDIT2 :

from itertools import cycle
import numpy as np
import pandas as pd
from sklearn.cluster import MeanShift
from sklearn.datasets.samples_generator import make_blobs
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D


filepath = "./Probes1.xlsx"
X = pd.read_excel(filepath, usecols="B:I", header=1) #import excel data
df=pd.DataFrame(data=X) #excel to dataframe to use in ML
np_array = df.values #dataframe
print(np_array) #printing dataframe

ms = MeanShift()
ms.fit(X) #Clustering
labels=ms.labels_
cluster_centers = ms.cluster_centers_ #coordinates of cluster centers
print("cluster centers:")
print(cluster_centers)

labels_unique = np.unique(labels)
n_clusters_=len(labels_unique) #no. of clusters
print("number of estimated clusters : %d" % n_clusters_)

# ################################# Plotting
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

colors=cycle('bgrkmycbgrkmycbgrkmycbgrkyc')
for k, col in zip(range(n_clusters_), colors):
    my_members= labels == k
    cluster_center = cluster_centers[k]
    ax.scatter(np_array[my_members, 0], np_array[my_members, 1], np_array[my_members, 2], col + '.')
    ax.scatter(cluster_centers[:,0], cluster_centers[:,1], cluster_centers[:,2], marker='o', s=300, linewidth=1, zorder=0)
    print(col) #prints b g r k in the respective iterations
plt.title('Estimated number of clusters: %d' % n_clusters_)
plt.grid()
plt.show()

Plots this: 3d plot

Again the colors are not matching, is there any alternative to 'markerfacecolor' from plt.plot in the scatter plots so I can match the colors of clusters with their data points?

EDIT 3: Got the required results: Final3d-Plot


Solution

  • You're setting your cluster center color to blue with c='b':

    plt.scatter(cluster_centers[:,0], cluster_centers[:,1], c='b', marker='x', s=20, linewidths=5, zorder=10)
    

    To match the colors of both scatters, you would have to specify them for both.