Same color lines in legend using a for loop

11 views (last 30 days)
Noah
Noah on 20 Sep 2022
Commented: Mathieu NOE on 24 Oct 2022
When I try and run this code, all the lines in the legend show up as red lines instead of different colors.
hold on
for i = 1:length(g)
if g(i) >= 2
plot(x,y,Color='b');
else
plot(x2,y2,Color='r');
end
end
hold off
hold on
plot(x2,y2,Color='y');
plot(x3,x3,,Color='m');
hold off
legend('l1','l2','l3','l4')
  1 Comment
Dyuman Joshi
Dyuman Joshi on 20 Sep 2022
1 - Do not use equal-to "=" sign between 'Color', and color value, inside the plot() function.
Use a comma ","
2 - Using "hold on" immediately after "hold off" seems a bit redundant.
3 - You might be overwriting the x2-y2 curve, color 'r' with itself x2-y2 curve, color 'y'. In the case, you would only find 3 curves
Other than this, I can not say what the error is (if it occurs after considering above points), data for the variables will be required to make any more comments on it.

Sign in to comment.

Answers (1)

Mathieu NOE
Mathieu NOE on 21 Sep 2022
hello
why make simple things complicated ?
if you have only 4 arrays to plot , you could do directly the plot like this - and the colors appears correctly in the legend box
% dummy data
x = 1:5;
y = 2*x+1;
x2 = 1.5*x;
y2 = 2*y+1;
x3 = 0.5*x;
% plot
figure
plot(x,y,'b',x2,y2,'r',x2+1,y2+1,'y',x3,x3,'m');
legend('l1','l2','l3','l4')
if you want a for loop and assign a color / line style different to each line , you can do this :
t = 0:pi/50:2*pi;
MarkerStyle={'o','+','*','x','s','d','v','>'};
Colors=[1 0 0; 1 0 1; 0 1 0; 0.4660 0.6740 0.1880; 0 0 1; 0.3010 0.7450 0.9330; 0.8500 0.3250 0.0980; 0.9290 0.6940 0.1250]
figure(1),hold on
for ck = 1:8
p = plot(t,sin((1+0.2*ck)*t),'LineWidth',2,'Color',Colors(ck,:),'Marker',MarkerStyle{ck});
leg_str{ck} = (['Line #' num2str(ck)]);
end
legend(leg_str);
  1 Comment
Mathieu NOE
Mathieu NOE on 24 Oct 2022
hello
if my answer has helped you, do you mind accepting it ?
thanks

Sign in to comment.

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!