多轴绘图,但只有一个图例 [英] Plot with multiple axes but only one legend
问题描述
以下代码生成了一条绘图,其中有两条线分别指向左y轴,一条线指向右y轴.这两个地块都有自己的图例,但我只想列出所有3条线的图例.我也尝试将'y1'
,'y2'
字符串也放入第二个legend
-命令,但这并没有解决.
The following code produces a plot with two lines reffering to the left y-axis and one line referring to the right y-axis. Both plots have their own legend, but I want only one legend listing all 3 lines. I tried to just put the 'y1'
,'y2'
strings into the 2nd legend
-command as well, but that didn't work out.
line(x,y1,'b','LineWidth',2)
line(x,y2,'Color',[0,0.6,0.5],'LineWidth',2)
legend('y1','y2');
ax1 = gca;
ax2 = axes('Position',ax1.Position,'YAxisLocation','right', 'Color','none','YColor',[255,127,80]/256);
linkaxes([ax1,ax2],'x');
line(x,y3,'Parent',ax2,'LineWidth',2,'Color',[255,127,80]/256)
legend('y3')
推荐答案
这是一个棘手的问题,因为图例以某种方式连接到了轴上.由于将创建2个轴,因此将有2个图例.但是,有一个技巧可以实现您想要的.首先,在同一轴上绘制所有线,然后运行legend
.然后创建第二根轴,然后将第三条线移动到第二根轴.因此,您的代码应如下所示:
This is a tricky problem since the legend are somehow connected to the axes. Since you will be creating 2 axes, hence there will be 2 legends. However there is a trick to achieve what you want. Firstly, plot all line on the same axes, then run legend
. Then create 2nd axes and then move the third line to the 2nd axes. So your code should look like this:
% line
line(x,y1,'b','LineWidth',2)
line(x,y2,'Color',[0,0.6,0.5],'LineWidth',2)
l3=line(x,y3,'LineWidth',2,'Color',[255,127,80]/256)
% legend
legend('y1','y2','y3');
% 2nd axes
ax1 = gca;
ax2 = axes('Position',ax1.Position,'YAxisLocation','right', 'Color','none','YColor',[255,127,80]/256);
linkaxes([ax1,ax2],'x');
% move l3 to 2nd axes
set(l3,'Parent',ax2);
如果要使用'DisplayName'
,则意味着它可以与line
If you want to use 'DisplayName'
, it meant to be used with line
line(x,y1,'Color','b','LineWidth',2,'DisplayName','y1');
line(x,y2,'Color',[0,0.6,0.5],'LineWidth',2,'DisplayName','y2');
legend('show');
这篇关于多轴绘图,但只有一个图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!