How do I create a legend describing a subset of the lines in my axes?
120 views (last 30 days)
Show older comments
MathWorks Support Team
on 27 Jun 2009
Edited: MathWorks Support Team
on 6 Sep 2018
How do I create a legend describing a subset of the lines in my axes? Is it possible to select which lines are shown in the legend?
For example, if I have a plot with 15 lines, how do I create a legend describing only 3 of those lines?
Accepted Answer
MathWorks Support Team
on 6 Sep 2018
There is an option for the LEGEND command that allows you to specify the handles of the objects that should be included in your legend. The following code can be studied as an example:
% create some arbitrary data
% the data will be scales of sine, cosine, and tangent curves
t = (0:.1:2*pi)';
x = sin(t);
sc = linspace(.8,1.2,10); % scaling matrix
x1 = repmat(x,1,10);
x1 = x1.*repmat(sc,length(t),1);
x = cos(t);
x2 = repmat(x,1,10);
x2 = x2.*repmat(sc,length(t),1);
x = tan(t);
x3 = repmat(x,1,10);
x3 = x3.*repmat(sc,length(t),1);
% plot the data
hf = figure;
hsin = plot(t,x1,'r');
hold on
hcos = plot(t,x2,'g');
htan = plot(t,x3,'b');
axis([0 2*pi -2 2])
% extract the handles that require legend entries
hleglines = [hsin(1) hcos(1) htan(1)];
% create the legend
hleg = legend(hleglines,'sine curves','cosine curves','tangent curves');
For more information on Handle Graphics and using GET and SET, please see the following resources:
Handle Graphics Object Properties
0 Comments
More Answers (0)
See Also
Categories
Find more on Legend in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!