为scatter3 plot创建图例(Matlab)

时间:2012-12-22 21:20:04

标签: matlab legend scatter-plot

我有3个维度的矩阵点XXNx3矩阵),这些点属于群集。它所属的集群由Nx1向量Cluster给出(它的值为1,2,3,......)。所以,我正在scatter3上这样绘图:

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

它工作正常,但我想添加一个图例,显示彩色标记及其代表的簇。

例如,如果我有3个集群,我希望有一个像:

这样的图例
<blue o> - Cluster 1
<red o> - Cluster 2
<yellow o> - Cluster 3

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

我建议您使用scatter3,而不是使用plot3,这会使标签更加简单:

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

答案 1 :(得分:1)

要么使用

  • legend

代码:

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