How to unify legend in plot command?

조회 수: 1 (최근 30일)
Harr
Harr 2022년 2월 23일
댓글: Harr 2022년 2월 23일
I have the following code making a line plots for 2 different groups. In the legend it dosent show legend per group (only the first group is correct). I wonder if there is some command can be added to each plot group to fix the problem? BTW i am using matlab2018b.
ax = gca;
ax.TickLength = [0.02 0.06];
set(gca,'XAxisLocation','top','YAxisLocation','left','ydir','reverse','XScale','log');
ax.XRuler.TickLabelGapOffset =-10;
ax.YLim = [0 20];
ax.XLim = [0 1];
ax.YDir= 'reverse';
x = [1 3 5 7];
y = [2 4 6 8];
z = [0.1 0.21 0.78 0.48];
plot([z;z], [x; y], 'LineWidth',3,'color',[0.9 0.4 0.5])
hold(gca,'on')
x = [2 8 9 14];
y = [3 9 14 20];
z = [0.9 0.1 0.71 0.38];
plot([z;z], [x; y], 'LineWidth',3,'color',[0.9 0.8 0.10])
hold(gca,'on')
legend("Group1_Red","Group2_Yellow")
hold(gca,'off')

채택된 답변

VBBV
VBBV 2022년 2월 23일
ax = gca;
ax.TickLength = [0.02 0.06];
set(gca,'XAxisLocation','top','YAxisLocation','left','ydir','reverse','XScale','log');
ax.XRuler.TickLabelGapOffset =-10;
ax.YLim = [0 20];
ax.XLim = [0 1];
ax.YDir= 'reverse';
x = [1 3 5 7];
y = [2 4 6 8];
z = [0.1 0.21 0.78 0.48];
h1 = plot([z;z], [x; y], 'LineWidth',3,'color',[0.9 0.4 0.5])
hold(gca,'on')
x = [2 8 9 14];
y = [3 9 14 20];
z = [0.9 0.1 0.71 0.38];
h2 = plot([z;z], [x; y], 'LineWidth',3,'color',[0.9 0.8 0.10])
hold(gca,'on')
legend([h1(1) h2(1)],{"Group1_Red","Group2_Yellow"})
hold(gca,'off')
Use handles in legend
  댓글 수: 1
Harr
Harr 2022년 2월 23일
Dear VBBV,
Thanks for your answer! The trick about naming each plot group to h1,h2...is very useful and solved my problem :)
Best regards
/HARR

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by