How to setup legend for a figure with two axes (left and right)?

조회 수: 36 (최근 30일)
Alborz Sakhaei
Alborz Sakhaei 2016년 10월 3일
댓글: Armando Cerullo 2021년 9월 30일
I have a figure with two axes (left and right). 2 lines on left axis and one line on right axis. I can not get all legends in one box using following code.
PS. I have read previous discussions (links below) on this topic but does not seem to work for me!
x = 0:0.01:10;
y11 = sin(x);
y12 = cos(x);
y2 = ones(1001,1);
figure;
ax(1) = axes('position',[0.1 0.1 0.8 0.8]);
ax(2) = axes('position',[0.1 0.1 0.8 0.8], 'yaxislocation','right','color','none');
line('parent',ax(1),'xdata',x,'ydata',y11,'color','b');
line('parent',ax(1),'xdata',x,'ydata',y12,'color','g');
line('parent',ax(2),'xdata',x,'ydata',y2,'color','r');
legend( [ax(1) ; ax(2)] , {'sin','cos','one'} )

채택된 답변

Jakub Rysanek
Jakub Rysanek 2016년 10월 4일
You can create the legend using the handles of your line objects:
l1=line('parent',ax(1),'xdata',x,'ydata',y11,'color','b');
l2=line('parent',ax(1),'xdata',x,'ydata',y12,'color','g');
l3=line('parent',ax(2),'xdata',x,'ydata',y2,'color','r');
legend( [l1;l2;l3] , {'sin','cos','one'} );
  댓글 수: 3
Armando Cerullo
Armando Cerullo 2021년 9월 30일
How would you then move the legend?

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

추가 답변 (1개)

KSSV
KSSV 2016년 10월 4일
편집: KSSV 2016년 10월 4일
Try the legend separately:
legend(ax(1) , {'sin','cos'} ) ;
legend(ax(2) , {'one'} ) ;
  댓글 수: 2
Alborz Sakhaei
Alborz Sakhaei 2016년 10월 4일
Thanks. Although it's more favorable to have all legends in one box
Subhamoy Saha
Subhamoy Saha 2018년 12월 25일
편집: Subhamoy Saha 2018년 12월 25일
For R2014b that works fine but for R2017a only last legend is showing (i.e., ax(2) legend) ignoring the first one (, i.e. ax(1)). This is really important as I want to set location for these two legend at two different location and so cannot use a single legend command. Please help how to proceed.

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

카테고리

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