0

I was working on a MATLAB project and found some strange behavior of the legend function. Here is the code to reproduce the issue:

X=rand(3,100);
a=rand(3,100);
b=rand(3,100);
figure(1); hold on;
plot(0.17663,'m');
plot(1.223,'y');
plot(X,a,'r');
plot(X,b,'g');
legend({'s1','s2','a','b'});

My question is: The legend in the picture shows the same color for plot 3 and plot 4. Instead it should show red and green respectively. Is there something wrong with legend?

https://i.stack.imgur.com/j6JbH.png

knedlsepp
  • 6,065
  • 3
  • 20
  • 41
priyanka
  • 25
  • 1
  • 1
  • 8
  • 1
    possible duplicate of [legend for group of lines](http://stackoverflow.com/questions/2141403/legend-for-group-of-lines) – knedlsepp Feb 15 '15 at 13:58
  • Not a duplicate per se, because in the linked question this is the wanted behavior why here it is a simple mistake, but the same cause, therefore it should be closed. – NoDataDumpNoContribution Feb 17 '15 at 09:42

1 Answers1

1

The commands plot(X,a,'r') and plot(X,b,'g') are not what you might expect. As X is a 3-by-100 array they will plot 100 lines, each consisting of 3 points, start, middle, end. The legend entries will correspond to each single line, so you should expect 100 red legend entries. You will see different behavior if you pass transposed arrays: plot(X.',a.','r'). This will plot 3 lines, each consisting of 100 points.

knedlsepp
  • 6,065
  • 3
  • 20
  • 41