2015-02-23 132 views
0

我无法在matlab中获得散点图的图例条目。图例条目在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

你对“传奇”做过任何研究吗? – MickyD 2015-02-23 05:52:37

+0

@MickyDuncan是的,我已阅读http://au.mathworks.com/help/matlab/ref/legend.html,但似乎无法得到正确的代码 – user2861089 2015-02-23 06:01:20

回答

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

我们得到:

enter image description here

+0

谢谢@rayryeng!这很棒。现在,如果x = [1 2 3 4 5 6 7 8 ...],我该如何添加抖动?谢谢! – user2861089 2015-02-23 22:48:01

+0

@ user2861089 - 嗨!抖动是什么意思?你能提供一个例子吗?你想添加噪音到'x'? – rayryeng 2015-02-23 22:51:51

+1

是的,但这似乎是诀窍!谢谢! 'xsize = size(x); a = 0; b = 0.1; r = a +(b-a)。* rand(xsize); r = r-均值(r); x = r + x;' – user2861089 2015-02-23 22:56:21