MATLAB: Is there a command in MATLAB for creating one overall legend when I have a figure with subplots

legendMATLABoneoverallsubplot

Is there a command in MATLAB for creating one overall legend when I have a figure with subplots?
I have a figure with subplots and I would like to create one legend that refers to all of my subplots. Is there a way to do this?

Best Answer

The ability to create an overall legend for subplots is not available in MATLAB.
Currently, to work around this issue, try creating a legend using a vector of handles corresponding to the subplots. Then, move the legend manually by clicking the left mouse button on the legend and dragging it to the desired destination, or programatically using the 'Position' attribute of the legend handle. The following is an example on how to create a legend using a vector of handles and move the legend programatically.
% Construct a figure with subplots and data
subplot(2,2,1);
line1 = plot(1:10,rand(1,10),'b');
title('Axes 1');
subplot(2,2,2);
line2 = plot(1:10,rand(1,10),'g');
title('Axes 2');
subplot(2,2,3);
line3 = plot(1:10,rand(1,10),'r');
title('Axes 3');
subplot(2,2,4);
line4 = plot(1:10,rand(1,10),'y');
title('Axes 4');
% Construct a Legend with the data from the sub-plots
hL = legend([line1,line2,line3,line4],{'Data Axes 1','Data Axes 2','Data Axes 3','Data Axes 4'});
% Programatically move the Legend
newPosition = [0.4 0.4 0.2 0.2];
newUnits = 'normalized';
set(hL,'Position', newPosition,'Units', newUnits);
-Note 1: This will create the legend in the axes which corresponds to the first handle passed into LEGEND. In this case, the legend will appear in the bottom subplot since that is the axes in which "h2" is plotted in.
-Note 2: The legend is a wrapper for axes and is thus parented to the figure. You can use its handle to reposition it within the figure.