creating legend for scatter3 plot (Matlab)

对着背影说爱祢 提交于 2019-12-04 03:55:06

问题


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!


回答1:


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');



回答2:


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

  • annotation.


来源:https://stackoverflow.com/questions/14006678/creating-legend-for-scatter3-plot-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!