user2861089
user2861089

Reputation: 1235

Legend entries not working in matlab

I am having trouble getting legend entries for a scatter plot in matlab.

I should have four different entries for each combination of two colors and two shapes.

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

This plots a scatter plot with red circles and squares and blue circles and squares. Now I want a legend (this doesn't work).

%legend for each combination
legend([h1(1) h1(2) h2(1) h2(2)],'red+square','red+circle','blue+square','blue+circle')

Any ideas? Thanks :)

Upvotes: 0

Views: 283

Answers (1)

rayryeng
rayryeng

Reputation: 104503

scatter is very limited when you want to place more than one set of points together. I would use plot instead as you can chain multiple sets in one command. Once you do that, it's very easy to use legend. Do something like this:

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

What's important is this syntax:

red_squares = s1 & c1;
blue_squares = s1 & c2;
red_circles = s2 & c1;
blue_circles = s2 & c2;

This uses logical indexing so that we select those circles and squares that belong to one colour or another colour. In this case, we choose only those shapes that are square and that belong to the first colour. There are four different combinations:

  • s1, c1
  • s1, c2
  • s2, c1
  • s2, c2

We get:

enter image description here

Upvotes: 4

Related Questions