Why when I put legend for 3 functions it only shows 1 on the graph?

3 次查看(过去 30 天)
Hi, below is my script:
x=linspace(0,2*pi,100);
y1=1-x.^2/factorial(2);
y2=y1+x.^4/factorial(4);
y3=cos(x);
plot(x,y1,'k:')
legend('2 terms approx')
hold on
plot(x,y2,'k--')
legend('3 terms approx')
hold on
plot(x,y3,'r')
legend('cos(x)')
xlabel('x')
ylabel('y')
Thanks!

采纳的回答

Birdman
Birdman 2017-10-27
Try this:
legend('2 terms approx','3 terms approx','cos(x)')

更多回答(1 个)

Walter Roberson
Walter Roberson 2017-10-27
legend() calls with text arguments never add the text to the existing legend entries.
As of R2017a, if there is a legend in effect and new graphics objects are added, then the legend is automatically expanded to include new entries; in versions up to R2016b, no entries were automatically added.
The entries that are automatically by default use names such as 'data1'. You can change this by adding a DisplayName property at the time the object was created. So, for example,
%R2017a or later
x=linspace(0,2*pi,100);
y1=1-x.^2/factorial(2);
y2=y1+x.^4/factorial(4);
y3=cos(x);
plot(x,y1,'k:', 'DisplayName', '2 terms approx');
hold on
plot(x,y2,'k--', 'DisplayName', '3 terms approx');
plot(x,y3,'r', 'DisplayName', 'cos(x)');
hold off
legend show
xlabel('x')
ylabel('y')
or
%R2016b or earlier
x=linspace(0,2*pi,100);
y1=1-x.^2/factorial(2);
y2=y1+x.^4/factorial(4);
y3=cos(x);
plot(x,y1,'k:')
legends{1} = '2 terms approx';
hold on
plot(x,y2,'k--')
legends{end+1} = '3 terms approx';
plot(x,y3,'r')
hold off
legends{end+1} = 'cos(x)';
legend(legends{:})
xlabel('x')
ylabel('y')

类别

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