我原以为它会起作用,但我从 MATLAB 帮助文件中遗漏了“句柄向量”。
LEGEND(M), where M is a string matrix or cell array of strings, and
LEGEND(H,M) where H is a vector of handles to lines and patches also works.
myone = ones(20,1);
mytwo = ones(20,1)+1;
rows = vertcat(myone,mytwo);
mylabels = {'Alpha', 'Beta'};
figure
grouplabels = mylabels(rows);
h = scatter3(rand(40,1),rand(40,1),rand(40,1),20,rows,'filled'), ...
view(-33,22)
legend(handle(h),grouplabels)
xlabel('X')
ylabel('Y')
zlabel('Z')
最佳答案
您的代码的问题是h
,scatter3
的输出,是一个句柄。它不是与您的数据大小相同的句柄数组(这是您尝试在其上设置 40x1 标签数组时所暗示的,忽略不相关的 handle
包装器)。它甚至不是人们可能认为的两个 handle 的阵列(每种颜色一个)。所以你不能这样设置图例。一种解决方法是一次绘制一种颜色的所有点:
hFig = figure();
axh = axes('Parent', hFig);
hold(axh, 'all');
h1 = scatter3(rand(20,1),rand(20,1),rand(20,1),20,'b','filled');
h2 = scatter3(rand(20,1),rand(20,1),rand(20,1),20,'r','filled');
view(axh, -33, 22);
grid(axh, 'on');
legend(axh, [h1,h2], {'Alpha', 'Beta'});
关于matlab - Matlab 中 scatter3 的图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37287041/