The first mark color in my plot legend is not correct

2 views (last 30 days)
Hello, When I try to run the following code the first item in the plot legend is marked as yellow, like the second one, while I expected to be blue
x = randn(2, 100);
y = randn(2, 100);
hold on;
pop1 = scatter(x(1,:), y(1,:), 'b*');
pop2 = scatter(x(2,:), y(2,:), 'yo');
params1 = polyfit(x(1,:), y(1,:), 1);
params2 = polyfit(x(2,:), y(2,:), 1);
xcoord = [-10 10];
ycoord = params1(1) * xcoord + params1(2);
plot(xcoord,ycoord, 'g-');
ycoord = params2(1) * xcoord + params2(2);
plot(xcoord,ycoord, 'ro-.');
legend('population 1', 'population 2', 'reg pop 1', 'reg pop 2');
I'm sure I'm doing something wrong. Thank you for any suggestion, kind regards, Milko
  2 Comments
Geoff Hayes
Geoff Hayes on 21 Oct 2015
Milko - typically this problem occurs because more graphics objects have been plotted than you expect. For example, depending upon your input, a call to plot may return more than one graphics object handle. See http://www.mathworks.com/matlabcentral/answers/247736-legend-has-different-color-lines-from-plot-lines for a discussion on this.
However, when I run your above code, each call to scatter and to plot returns a single handle and all four strings in the legend have distinct colours. So it works for me (OS X 10.9.5, R2014a).
Use the debugger to step through your code to ensure that the calls to scatter and plot return a single handle.
Milko Lupinacci
Milko Lupinacci on 29 Oct 2015
Geoff - Thank you. I followed your suggestion and I checked using the debugger that both scatter and plot return a single handle. The version I'm using is R2015b on Windows 10 Pro.

Sign in to comment.

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!