我无法在matlab中获取散点图的图例条目。
对于两种颜色和两种形状的每种组合,我应该有四种不同的条目。
colormap jet
x = rand(1,30); %x data
y = rand(1,30); %y data
c = [1 2 2 1 1 1 1 2 2 1 1 1 1 1 2 2 1 1 1 2 2 1 1 1 1 1 2 2 1 1]; %color
s = [2 2 1 1 1 2 1 2 2 1 1 1 1 2 2 2 1 1 1 1 2 2 1 1 1 2 2 1 1 2]; %shape
%index data for each shape (s)
s1 = s == 1; %square
s2 = s == 2; %circle
xsq = x(s1);
ysq = y(s1);
csq = c(s1);
xcirc = x(s2);
ycirc = y(s2);
ccirc = c(s2);
%plot data with different colors and shapes
h1 = scatter(xsq, ysq, 50,csq,'s','jitter','on','jitterAmount',0.2);
hold on
h2 = scatter(xcirc, ycirc, 50, ccirc, 'o','jitter','on','jitterAmount',0.2);
这绘制了一个散点图,其中包含红色圆圈和正方形以及蓝色圆圈和正方形。现在我想要一个传奇(这不起作用)。
%legend for each combination
legend([h1(1) h1(2) h2(1) h2(2)],'red+square','red+circle','blue+square','blue+circle')
有什么想法吗?谢谢:))
答案 0 :(得分:4)
scatter
非常有限。我会使用plot
,因为您可以在一个命令中链接多个集合。一旦你这样做,它就很容易使用legend
。做这样的事情:
colormap jet
x = rand(1,30); %x data
y = rand(1,30); %y data
c = [1 2 2 1 1 1 1 2 2 1 1 1 1 1 2 2 1 1 1 2 2 1 1 1 1 1 2 2 1 1]; %color
s = [2 2 1 1 1 2 1 2 2 1 1 1 1 2 2 2 1 1 1 1 2 2 1 1 1 2 2 1 1 2]; %shape
%index data for each shape (s)
s1 = s == 1; %square
s2 = s == 2; %circle
c1 = c == 1; %circle colour %// NEW
c2 = c == 2; %square colour %// NEW
red_squares = s1 & c1; %// NEW
blue_squares = s1 & c2; %// NEW
red_circles = s2 & c1; %// NEW
blue_circles = s2 & c2; %// NEW
plot(x(red_squares), y(red_squares), 'rs', x(blue_squares), y(blue_squares), 'bs', x(red_circles), y(red_circles), 'ro', x(blue_circles), y(blue_circles), 'bo');
legend('red+square','blue+square','red+circle','blue+circle');
这个语法重要的是什么:
red_squares = s1 & c1;
blue_squares = s1 & c2;
red_circles = s2 & c1;
blue_circles = s2 & c2;
这使用逻辑索引,以便我们选择属于一种颜色或另一种颜色的圆和正方形。在这种情况下,我们只选择那些方形且属于第一种颜色的形状。有四种不同的组合:
s1, c1
s1, c2
s2, c1
s2, c2
我们得到: