'How to plot the cluster's centroids using seaborn
Solution 1:[1]
You could calculate the mean of each group, and draw a scatter dot at that position.
from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np
N = 1000
X0 = np.random.normal(np.repeat(np.random.uniform(0, 20, 4), N), 1)
X1 = np.random.normal(np.repeat(np.random.uniform(0, 10, 4), N), 1)
X = np.vstack([X0, X1]).T
y = np.repeat(range(4), N)
colors = ['red', 'blue', 'purple', 'green']
ax = sns.scatterplot(X[:, 0], X[:, 1], hue=y, palette=colors, alpha=0.5, s=7)
means = np.vstack([X[y == i].mean(axis=0) for i in range(4)])
ax = sns.scatterplot(means[:, 0], means[:, 1], hue=range(4), palette=colors, s=20, ec='black', legend=False, ax=ax)
plt.show()
Alternatively, Scikit Learns's KMeans
could be used to calculate both the KMeans labels and the means:
from sklearn.cluster import KMeans
from matplotlib import pyplot as plt
import numpy as np
import seaborn as sns
N = 500
X0 = np.random.normal(np.repeat(np.random.uniform(0, 20, 20), N), 3)
X1 = np.random.normal(np.repeat(np.random.uniform(0, 10, 20), N), 2)
X = np.vstack([X0, X1]).T
num_clusters = 4
kmeans = KMeans(n_clusters=num_clusters).fit(X)
colors = ['red', 'blue', 'purple', 'green']
ax = sns.scatterplot(X[:, 0], X[:, 1], hue=kmeans.labels_, palette=colors, alpha=0.5, s=7)
ax = sns.scatterplot(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1],
hue=range(num_clusters), palette=colors, s=20, ec='black', legend=False, ax=ax)
plt.show()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |