Legend Producing Wrong Colour Lines
2 次查看(过去 30 天)
显示 更早的评论
Hi I have been trying to plot multiple lines on the same plot and the colours of the lines are coming up incorrectly. Here is my code and the results. I am currently running 2020b
plot(x,freal,'k')
hold on
plot(x,ftaylor0,'r')
plot(x,ftaylor1,'b')
plot(x,ftaylor2,'g')
plot(x,ftaylor3,'m')
plot(x,ftaylor4,'c')
hold off
legend('f(x)', 'p0(x)', 'p1(x)', 'p2(x)', 'p3(x)', 'p4(x)')
xlabel('x')
ylabel('f(x)')
回答(1 个)
VBBV
2022-7-29
x=-5:0.1:5;
freal=x.*exp(-x);
ftaylor0= 1./exp(x); % they is scalar in your code
ftaylor1= 1./exp(-x); % this is scalar in your code
ftaylor2= (1/exp(1))-(1/(2*exp(1)).*(x-1).^2);
ftaylor3= (1/exp(1))-(1./(2.*exp(1)).*(x-1).^2)+((1./(3.*exp(1))).*(x-1).^3);
ftaylor4= (1/exp(1))-(1./(2.*exp(1)).*(x-1).^2)+((1./(3.*exp(1))).*(x-1).^3)-((1./(8.*exp(1))).*(x-1).^4);
plot(x,freal,'k')
hold on
plot(x,ftaylor0,'r')
plot(x,ftaylor1,'b')
plot(x,ftaylor2,'g')
plot(x,ftaylor3,'m')
plot(x,ftaylor4,'c')
hold off
legend('f(x)', 'p0(x)', 'p1(x)', 'p2(x)', 'p3(x)', 'p4(x)')
You can see ftaylor0 and ftaylor1 are scalars with just one point. You need to make them vectors
1 个评论
VBBV
2022-7-29
编辑:VBBV
2022-7-29
x=-5:0.1:5;
freal=x.*exp(-x);
ftaylor0= 1./exp(1) % they is scalar in your code
ftaylor1= 1./exp(1) % this is scalar in your code
ftaylor2= (1/exp(1))-(1/(2*exp(1)).*(x-1).^2);
ftaylor3= (1/exp(1))-(1./(2.*exp(1)).*(x-1).^2)+((1./(3.*exp(1))).*(x-1).^3);
ftaylor4= (1/exp(1))-(1./(2.*exp(1)).*(x-1).^2)+((1./(3.*exp(1))).*(x-1).^3)-((1./(8.*exp(1))).*(x-1).^4);
plot(x,freal,'k')
hold on
plot(ftaylor0,'>r','MarkerSize',10) % use a marker to plot
plot(ftaylor1,'sb','MarkerSize',4) % use a marker to plot
plot(x,ftaylor2,'g')
plot(x,ftaylor3,'m')
plot(x,ftaylor4,'c')
hold off
legend('f(x)', 'p0(x)', 'p1(x)', 'p2(x)', 'p3(x)', 'p4(x)','location','best')
You can also plot them as data point with proper legend
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Legend 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!