0

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')
Max
  • 1,471
  • 15
  • 37
  • 2
    Have a look at dynamic legends: http://stackoverflow.com/questions/21685911/dynamic-legend-updates-in-every-recursion - I haven't flagged as duplicate because I don't know if this will solve your problem, but it sounds like it will. – rayryeng Oct 03 '15 at 15:48
  • @rayryeng it looks like it might actually solve my problem, but i don't get the syntax correct. since I'm not using (and cannot use in this case) the `plot`-command, but `figure` and `line` instead, i don't know where i have to add the `'DisplayName',['y1','y2','y3']` in my case. i tried adding it to the `figure`-command, but matlab says "there is no displayname in figure-class". Can you help me with that? – Max Oct 03 '15 at 16:24

1 Answers1

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');
MinF
  • 326
  • 1
  • 4