legend with multiple axes using yyaxis

조회 수: 233 (최근 30일)
nathan blanc
nathan blanc 2021년 1월 2일
댓글: Star Strider 2023년 2월 3일
I am creating a plot with two different y axes. the curves are added alternately. for example:
yyaxis left
plot(A)
yyaxis right
plot(B)
yyaxis left
plot(C)
yyaxis right
plot(D)
My problem is that when I add a legend to the plot, the order of the curves is not the order in which they were created. instead, they are ordered first by the left axis
and then by the right axis. meaning if i write down "legend(A,B,C,D)" the legend entry B will correspond with the curve C and vice-versa. is there a way to fix this? The actual case there are more than 4 curves, and the number changes every time, so manual changing is not possible. many thanks in advance
Nathan

채택된 답변

Star Strider
Star Strider 2021년 1월 2일
편집: Star Strider 2021년 1월 2일
Try this:
A = rand(1,10);
B = rand(1,15);
C = rand(1,20);
D = rand(1,30);
figure
hold on
yyaxis left
ha = plot(A);
yyaxis right
hb = plot(B);
yyaxis left
hc = plot(C);
yyaxis right
hd = plot(D);
hold off
legend([ha,hb,hc,hd], 'A','B','C','D')
Alternatively:
figure
yyaxis left
ha = plot(A);
hold on
hc = plot(C);
hold off
yyaxis right
hb = plot(B);
hold on
hd = plot(D);
hold off
legend([ha,hb,hc,hd], 'A','B','C','D')
Using hold is the only way to do what you want. This cannot be used with your posted code, because without the hold function, the second calls to yyaxis left and yyaxis right calls eliminate the handles to the previously plotted curves.
EDIT — (2 Jan 2021 at 17:41)
Added alternative code.
.
  댓글 수: 6
Giovanni Bambini
Giovanni Bambini 2023년 2월 3일
Thanks!!!!
Star Strider
Star Strider 2023년 2월 3일
My pleasure!
A Vote would be appreciated!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by