I have a matrix points X
in 3 dimensions ( X
is a Nx3
matrix) and those points belong to clusters. The cluster it belongs is given by the Nx1
vector Cluster
(it has values like 1,2,3,...). So, I am plotting it on scatter3
like this:
scatter3(X(:,1),X(:,2),X(:,3),15,Cluster)
It works fine, but I would like to add a legend to it, showing the colored markers and the cluster it represents.
For example, if i have 3 clusters, I would like to have a legend like:
<blue o> - Cluster 1
<red o> - Cluster 2
<yellow o> - Cluster 3
Thank you very much for the help!
Instead of using scatter3
, I suggest you use plot3
, which will make labeling much simpler:
%# find out how many clusters you have
uClusters = unique(Cluster);
nClusters = length(uClusters);
%# create colormap
%# distinguishable_colormap from the File Exchange
%# is great for distinguishing groups instead of hsv
cmap = hsv(nClusters);
%# plot, set DisplayName so that the legend shows the right label
figure,hold on
for iCluster = 1:nClusters
clustIdx = Cluster==uClusters(iCluster);
plot3(X(clustIdx,1),X(clustIdx,2),X(clustIdx,3),'o','MarkerSize',15,...
'DisplayName',sprintf('Cluster %i',uClusters(iCluster)));
end
legend('show');
Either you use
legend
Code:
h = scatter3(X(:,1),X(:,2),X(:,3),15,Cluster)
hstruct = get(h);
legend(hstruct.Children, "Cluster1", "Cluster2", "Cluter3");
or
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.