MATLAB: Single legend for plot with two axes

axeslegendplot

Hi,
I am trying to create a figure consisting of two axes with one plot in each one. For this figure however, I only want one legend that includes both of the plots.
An example of the plot code i would like to modify:
x = [0:0.01:5];
y1 = x.^2;
y2 = sqrt(x);
% Create figure
figure1 = figure('Units', 'pixels','Color', 'none', 'Position',[100 100 630 450]);
% Create axes 1
axes1 = axes('Parent',figure1,...
'Units', 'pixels',...
'Position',[115 85 400 305],...
'XMinorTick','on',...
'YMinorTick','on',...
'YGrid','on',...
'XTick', 0:1:5,...
'YTick' , 0:5:25, ...
'Yscale', 'linear',...
'YMinorGrid','off',...
'XColor',[0.1 0.1 0.1],...
'YColor' , [.1 .1 .1], ...
'TickDir','out',...
'TickLength',[0.02 0.02],...
'LineWidth',1,...
'FontName','Arial',...
'FontSize',12);
xlim([0 5]);
ylim([0 25]);
box('on');
hold('all');
plot(x,y1,'Parent',axes1,...
'LineWidth',2,...
'Color',[0.1 0.1 0.9],...
'DisplayName','1');
% Create axes 2
axes2 = axes('Parent',figure1,...
'Units', 'pixels',...
'Position',[115 85 400 305],...
'YTick',0:0.5:3,...
'XTick', 0:1:5,...
'YMinorTick','on',...
'Yscale', 'linear',...
'YMinorGrid','off',...
'YGrid','off',...
'YAxisLocation','right',...
'TickDir','out',...
'YColor' , [.1 .1 .1], ...
'XColor',[0.1 0.1 0.1],...
'FontName','Arial',...
'FontSize',12,...
'Color','none');
xlim([0 5]);
ylim([0 3]);
hold('all');
plot(x,y2,'Parent',axes2,...
'LineWidth',2,...
'Color',[0.9 0.1 0.1],...
'DisplayName','2');
% Create legend
legend1 = legend(axes1,'show');
legend(axes1,'boxon')
set(legend1,'Location','SouthWest','FontSize',10);
legend2 = legend(axes2,'show');
legend(axes2,'boxon')
set(legend2,'Location','SouthEast','FontSize',10);
The code plots y1 and y2 in two different axes (axes1 and axes2). I want legend1 and legend2 to be the same legend. Any ideas on how to make this happen?

Best Answer

You can catch the handles of the created lines to create the legend and set the legend's position manually:
subplot(1, 3, 1);
a = plot(rand(4));
subplot(1, 3, 2);
b = plot(rand(4));
Leg = legend([a; b], {'a', 'b', 'c', 'd', 'a2', 'b2', 'c2', 'd2'});
Pos = get(Leg, 'Position');
set(Leg, 'Position', [1 - Pos(3), Pos(2:4)]);
 
 
ADDED: See also: SubPlotLegend, GridLegend