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

4 views (last 30 days)
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

Accepted Answer

José M. Requena Plens
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

More Answers (1)

ANKUR KUMAR
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'})

Community Treasure Hunt

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

Start Hunting!