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

조회 수: 8 (최근 30일)
Zhuoying Lin
Zhuoying Lin 2017년 10월 27일
댓글: Zhuoying Lin 2017년 10월 27일
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')
  댓글 수: 1
Zhuoying Lin
Zhuoying Lin 2017년 10월 27일
I try the first one and it works thanks for your soln and quick response!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Discrete Data Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by