How do I create multiple legends to correspond to multiple sets of curves in my MATLAB figure?

24 views (last 30 days)
I am plotting six curves in a MATLAB figure. I want to create two legends positioned at 'NorthWest' and 'NorthEast' of the figure such that the first legend represents the first three curves and the second legend represents the second set of three curves.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
The function LEGEND allows creation of only one legend object per axes. Multiple legends can be created by using the function COPYOBJ to make a copy of a legend object.
The following example illustrates how two legends corresponding to two sets of plots in a figure can be created. Note that some of the properties of the legend objects are lost because of copying.
%Six data sets.
x = 1:10;
y1 = x.*0.9;
y2 = x.^1.1;
y3 = 2*x + 3;
y4 = x;
y5 = 3*x;
y6 = 4*x;
hf1 = figure;
ax1 = axes('Parent',hf1);
hold on;
% First set of plots
hplots = plot(x,y1, '-x',x,y2, '-.+', x,y3,'.');
[hleg,hobjs,hlinpatches,legtxt] ...
= legend(hplots,'y1','y2','y3','location','NorthWest');
hleg_copy = copyobj(hleg,hf1);
delete(hleg);
% Now move the first set of plots and legend to a second figure
% Note that the LEGEND function creates references for all the plots in a
% figure
% Moving allows us to create second set of plots and legend easily without
% having to locate and delete legend objects corresponding to the first set
% of plots
hf2 = figure('visible', 'on');
ax2 = axes('Parent',hf2,'visible','on');
hold(ax2, 'on');
set(hplots,'Parent',ax2);
set(hleg_copy,'Parent',hf2);
% Second set of plots
hplots2 = plot(x,y4,'-.k*',x,y5,'--k^',x,y6,'k:');
[hleg2,hobjs2,hlinpatches2,legtxt2] = ...
legend(hplots2,'y4','y5','y6','location','NorthEast');
% Create a copy of the second legend and delete the original
% This forces similar appearance and behavior for the two legends.
hleg_copy2 = copyobj(hleg2,hf1);
delete(hleg2);
% The following two lines remove the references to properties that
% original legend object referred to. This prevents potential errors from
% methods like ButtonDownFcn and others that are specific to legend
% objects.
set(hleg_copy,'Tag','', 'ButtonDownFcn','', 'UserData', []);
set(hleg_copy2,'Tag','', 'ButtonDownFcn','', 'UserData', []);
% Now move the first set of plots and corresponding legend back to our
% figure. Must also move the second set of plots to the first figure.
set(hplots,'Parent',ax1);
set(hplots2, 'Parent', ax1);
set(hleg_copy,'Parent',hf1);
xlabel('X-Data');
close(hf2);
For more information on functions used in this example execute the following command at the MATLAB command prompt
doc <function_name>

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!