Creating a legend for plot3 plot (Matlab)

I have X matrix points in three dimensions ( X is an Nx3 matrix), and these points belong to clusters. The vector Nx1 Cluster belongs to the Cluster (it has values, such as 1,2,3, ...). So, I draw it on scatter3 as follows:

 scatter3(X(:,1),X(:,2),X(:,3),15,Cluster) 

It works great, but I would like to add a legend to it showing the color markers and the cluster that 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 for help!

+4
source share
2 answers

Instead of using scatter3 , I suggest you use plot3 , which will greatly simplify the marking:

 %# 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'); 
+3
source

Or you use

  • legend

code:

 h = scatter3(X(:,1),X(:,2),X(:,3),15,Cluster) hstruct = get(h); legend(hstruct.Children, "Cluster1", "Cluster2", "Cluter3"); 

or

+1
source

All Articles