How to make color of centers the same color of clusters?

Viewed 57

i have two methods one for drawing the centers for the cluster

def draw_roh_delta(self, rho, delta, center, plot):
        plot.scatter(rho, delta, label='rho-delta', c='k', s=5)
        plot.set_xlabel('rho')
        plot.set_ylabel('delta')
        center_rho = rho[center]
        center_delta = delta[center]
        np.random.seed(6)
        colors = np.random.rand(len(center), 3)
        plot.scatter(center_rho, center_delta, c=colors)
        plot.legend()

and others for drawing the cluster

def draw_cluster(self, title, cluster, halo, points, plot):
    cluster_points = dict()
    colors = dict()
    np.random.seed(10)
    for k, v in cluster.items():
        cluster_points[k] = points.loc[cluster[k], :]
        colors[k] = np.random.rand(3)
    for k, v in cluster_points.items():
        plot.scatter(v.loc[:, 'x'], v.loc[:, 'y'], c=colors[k], alpha=0.5)
        plot.scatter(v.at[k, 'x'], v.at[k, 'y'], c=colors[k], s=np.pi * 10 ** 2)

I need to make the color of the centers the same color as the clusters instead of creating them randomly. can someone help, please?

EDIT

def draw_roh_delta(self, rho, delta, center, plot):
    plot.scatter(rho, delta, label='rho-delta', c='k', s=5)
    plot.set_xlabel('rho')
    plot.set_ylabel('delta')
    center_rho = rho[center]
    center_delta = delta[center]
    color= ['red', 'blue', 'green', 'yellow','orange','purple']
    plot.scatter(center_rho, center_delta, c=color)
    plot.legend()
1 Answers

One way is to use the plot function to draw points, which returns a list[Line2d]. You just need to take out the first element and call its get_color() method obtains the color drawn this time.

I drew my result of kmeans clustering as follow:

fig, ax = plt.subplots()

for i, center in enumerate(centers):
    color = ax.plot(*center, '*')[0].get_color()
    points = data_set[labels == i]
    ax.plot(*points.T, 'o', c=color)

Unfortunately, to do this, you may need to blend the two methods together, or let the first method return all colors to the second method.

EDIT

I would solve it like this:

def draw_rho_delta(self, rho, delta, center, plot):
    # ...
    self.colors = []
    for c_rho, c_delta in zip(center_rho, center_delta):
        color = plot.plot(c_rho, c_delta, 'o')[0].get_color()
        self.colors.append(color)

def draw_cluster(self, title, cluster, halo, points, plot):
    # ...
    for (k, v), color in zip(cluster.items(), self.colors):
        p = points.loc[v, :]
        plot.plot(p.loc[:, 'x'], p.loc[:, 'y'], 'o', c=color)
        plot.plot(p.at[k, 'x'], p.at[k, 'y'], 'o', c=color)

I don't know the type of your plot, so I assume it's matplotlib.pyplot.Axes, and I assume that the order in which you draw the centers is consistent with the order in which you draw the clusters.

Related