How to unify legend in plot command?

1 次查看(过去 30 天)
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 中查找有关 Legend 的更多信息

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by