Max
Max

Reputation: 1481

Plot with multiple axes but only one 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')

Upvotes: 0

Views: 1798

Answers (1)

MinF
MinF

Reputation: 326

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

Upvotes: 1

Related Questions