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

4 次查看(过去 30 天)
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
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

更多回答(1 个)

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

类别

Help CenterFile Exchange 中查找有关 Legend 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by