MATLAB: Legend problem in a multiple axes graph

graphlegendmultiple axes

I want to avoid the tick misalignment of plotyy (and the ticks on the top x axis), so I create a multiple axes plot manually…
Ex :
x = [1 2 3 4 5 6 7 ];
y1 = x;
y2 = [10 20 30 70 80 90 100]
line(x, y1)
ax1 = gca;
ax2 = axes('Position',get(ax1,'Position'),...
'XAxisLocation','bottom',...
'YAxisLocation','right',...
'Color','none',...
'XTick',[],...
'XColor','k','YColor','k');
line(x,y2,'color','black','linestyle','--')
legend('y1','y2')
But then I can't display both lines in my legend box and get the following message: "Warning: Ignoring extra legend entries."
Any suggestion on how to solve this problem? Thanks!

Best Answer

x = [1 2 3 4 5 6 7 ];
y1 = x;
y2 = [10 20 30 70 80 90 100]
L1 = line(x, y1);
ax1 = gca;
ax2 = axes('Position',get(ax1,'Position'),...
'XAxisLocation','bottom',...
'YAxisLocation','right',...
'Color','none',...
'XTick',[],...
'XColor','k','YColor','k');
L2 = line(x,y2,'color','black','linestyle','--');
legend([L1, L2],'y1','y2')