简体   繁体   中英

Want to Color Each Potted Cluster a Different Color

I'm trying to color each cluster plotted from DBscan a different color. I created a color list and tried to have the code iterate through each cluster and plot it a different color, but it colors all the clusters the same color which is the last color from the color list (purple). Help would be appreciated.

import pandas as pd
from sklearn.cluster import DBSCAN
from collections import Counter
from sklearn.neighbors import NearestNeighbors
from matplotlib import pyplot as plt
import matplotlib
matplotlib.use('TkAgg')

eps = 4.3


model  = DBSCAN(eps            = eps,
                min_samples    = 210,
                metric         = 'euclidean'
                )

data = model.fit(plotting_data)


X          = plotting_data['X']
Y          = plotting_data['Y']

clusters = data.fit_predict(plotting_data)
print(clusters)

clust_df = pd.DataFrame(plotting_data)


clusters = (clust_df[data.labels_ != -1])



labels = data.labels_
num_clusters = len(set(labels))
print(num_clusters)



color_list = ['green', 'blue', 'red', 'yellow',  'orange',  'magenta', 'cyan', 'purple']
labels = data.labels_
num_clusters = len(set(labels))


i = 0
for col in zip(color_list):
    plt.scatter(clusters['X'],
                clusters['Y'],
                c = col

                )
    i += 1


plt.title("Clusters: " + str(num_clusters), fontsize = 13)

plt.show()

[![enter image description here][1]][1]

I was able to solve it, so I'm answering in case someone in the future wants a possible answer. All I needed to do was take my DBscan data and use fit_predict with the (x,y) plotting points ('clusters', in my case).

Like so:

color_clusters = data.fit_predict(clusters)

# i = 0
# for col in zip(color_list):

plt.scatter(clusters['X'],
           clusters['Y'],
           c = color_clusters,
           cmap = 'inferno'

           )
plt.colorbar()

I think this would work:

color_list = np.array(['green', 'blue', 'red', 'yellow',  'orange',  'magenta', 'cyan', 'purple'])

plt.scatter(clusters['X'], clusters['Y'], c = color_list[labels])
plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM