Plot with multiple axes but only one legend

本秂侑毒 提交于 2019-12-11 18:27:03

问题


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')

回答1:


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);

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');


来源:https://stackoverflow.com/questions/32924141/plot-with-multiple-axes-but-only-one-legend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!