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

9 vues (au cours des 30 derniers jours)
Zhuoying Lin
Zhuoying Lin le 27 Oct 2017
Commenté : Zhuoying Lin le 27 Oct 2017
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!

Réponse acceptée

Birdman
Birdman le 27 Oct 2017
Try this:
legend('2 terms approx','3 terms approx','cos(x)')
  1 commentaire
Zhuoying Lin
Zhuoying Lin le 27 Oct 2017
Yes it works! Thanks for your soln and immediate response!

Connectez-vous pour commenter.

Plus de réponses (1)

Walter Roberson
Walter Roberson le 27 Oct 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')
  1 commentaire
Zhuoying Lin
Zhuoying Lin le 27 Oct 2017
I try the first one and it works thanks for your soln and quick response!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Discrete Data Plots dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by