How can i automatically Fill Legend using Cluster Number (K-means)

7 views (last 30 days)
Hello everyone, I hope you are doing well.
I have the following Dataset,
i have Find the Optimal Clusters for this dataset using evalclusters (K)
and Apply Kmeans to the dataset with Optimal Clusters K
Now i am ploting gscatter plot with manually enter legend cluster number for example Cluster 1, Cluster 2, Cluster 3....
I want to plot it automatically , Like when Optimal Clusters K find the gscatter plot shows thats clusters
%Read Dataset
%Find the Optimal Clusters for this dataset
eva = evalclusters(dataset1,'kmeans','silhouette','KList',[1:10])
K=eva.OptimalK;
%Apply Kmeans to the dataset with Optimal Clusters K
[idx,C,sumdist] = kmeans(dataset,K,'Display','final','Replicates',5);
%Plot the Clusters
figure
gscatter(dataset(:,1),dataset(:,2),idx,'bgmkr')
hold on
plot(C(:,1),C(:,2),'kx')
%NEED TO change here depend on value of K
legend('Cluster 1','Cluster 2','Cluster 3','Cluster 4','Cluster 5','Cluster Centroid')
  1 Comment
Jan
Jan on 13 May 2022
Edited: Jan on 13 May 2022
@Stephen john: Please do not try to catch the attraction of other users using the @ method. Remember, that these persons are informed, when you mention them and imagine what happens, if all asking persons do this. I would drown in a pile of messages and disable the service immediately. Thanks.

Sign in to comment.

Answers (1)

KSSV
KSSV on 12 May 2022
%Read Dataset
%Find the Optimal Clusters for this dataset
eva = evalclusters(dataset,'kmeans','silhouette','KList',[1:10])
K=eva.OptimalK;
%Apply Kmeans to the dataset with Optimal Clusters K
[idx,C,sumdist] = kmeans(dataset,K,'Display','final','Replicates',5);
%Plot the Clusters
figure
gscatter(dataset(:,1),dataset(:,2),idx,'bgmkr')
hold on
plot(C(:,1),C(:,2),'kx')
%NEED TO change here depend on value of K
G = max(idx) ;
str = repmat("Cluster ",G,1) ;
str = strcat(str,string((1:G)')) ;
lgd = legend([str ; "Cluster Centroid"]) ;

Products


Release

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!