Plot color is different to the color being shown on the legend

1 view (last 30 days)
Usama Faisal on 15 Mar 2021
Commented: Usama Faisal on 16 Mar 2021
Hello,
I have been trying to fix this issue for quite a while now. I've made a plot that has four graphs, and I added a legend so that the graphs could be easily understood. The problem is the color of the graphs doesn't match with the legend. I've shared the code below, and the picture of plots in attachment. What am I doing wrong?
figure(7)
box off, grid on
xlim([-50 250]);
title("First four harmonics of y_a(t)");
xlabel("t");
ylabel("y_a(t)");
hold on
plot(n1,yline(1/7));
plot(n1,a1);
plot(n1,a2);
plot(n1,a3);
legend('Zeroth Harmonic', 'First Harmonic', 'Second Harmonic', 'Third Harmonic');
hold off

José M. Requena Plens on 16 Mar 2021
The problem is in your first plot.
the 'yline' function must not be inside the plot function.
Using your code, the correction is:
figure(7)
box off, grid on
xlim([-50 250]);
title("First four harmonics of y_a(t)");
xlabel("t");
ylabel("y_a(t)");
hold on
yline(1/7) % Plot function isn't necessary here
plot(n1,a1);
plot(n1,a2);
plot(n1,a3);
legend('Zeroth Harmonic', 'First Harmonic', 'Second Harmonic', 'Third Harmonic');
hold off
Usama Faisal on 16 Mar 2021
Thanks a lot, Jose. Worked like a charm!

ANKUR KUMAR on 15 Mar 2021
This is an example of plot using different colors. Hope this helps.
clc
clear
x=linspace(0,2*pi,100);
xdata={sin(x),cos(x),sin(2*x),cos(x/2)}
colors={'r','b','g','k'}
for kk=1:length(xdata)
plot(x,xdata{kk},colors{kk},'linewidth',2)
hold on
end
legend({'Sin x','Cos x','Sin 2x','Cos x/2'})