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

9 visualizaciones (últimos 30 días)
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!

Respuesta aceptada

Birdman
Birdman el 27 de Oct. de 2017
Try this:
legend('2 terms approx','3 terms approx','cos(x)')

Más respuestas (1)

Walter Roberson
Walter Roberson el 27 de Oct. de 2017
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')

Categorías

Más información sobre Discrete Data Plots en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by