MATLAB: Legend repeating same color

ds

Please I am just plotting two data extracted from my work. but after plotting the code, the color of the legend keep repeating with the first color I input with indicating the legend of the next color. The attached data, Dposition and Uposition are the data plotted. please I hope anyone can help.

Best Answer

Set the DisplayName property when calling plot, or use the output from plot to build your legend with specific handles.
x=linspace(0,10,50);
y1=5*cos(x)+rand(size(x));
y2=4*sin(x)+rand(size(x));
y1a=y1+0.5*rand(size(x));
y1b=y1-0.5*rand(size(x));
figure(1),clf(1)%only use clf during debugging
%example 1:
subplot(1,3,1)
plot(x,y1,'DisplayName','foo'),hold on
plot(x,y2,'DisplayName','bar'),hold off
legend
%example 2:
subplot(1,3,2)
h1=plot(x,y1);hold on
h2=plot(x,y2);hold off
legend([h1 h2],{'foo','bar'})
%example 3:
subplot(1,3,3)
h1=plot([x;x]',[y1a;y1b]');hold on
h2=plot(x,y2);hold off
legend([h1(1) h2(1)],{'foo','bar'})