MATLAB: How to explicitly specify which lines to include in the legend of a plot in MATLAB 7.7 (R2008b)

MATLAB

I want to explicitly specify which lines to include in the legend of a plot regardless of which lines actually show up in the plot.

Best Answer

When you plot data in a plot, each set of (x,y) points is its own separate line object. Each line object can be manipulated directly via handles. For instance, the following code plots three line objects: a sine, cosine, and arctan on the same figure. The variables 'h1', 'h2', and 'h3' are handles to each of the line objects respectively.
x1 = 0:0.1:6; y1 = sin(x1);
x2 = 0:0.1:6; y2 = cos(x2);
x3 = 0:0.1:6; y3 = atan(x3);
figure; hold on
h1 = plot(x1,y1,'r');
h2 = plot(x2,y2,'g');
h3 = plot(x3,y3,'m');
To specify which line objects to include in the legend, put into one vector all the line objects you want included in the legend. Then pass this vector into the LEGEND command. The following example creates a plot with all three curves but creates a legend with just the sine and cosine included.
handlevec = [h1 h2];
legend(handlevec,'sine wave','cosine wave');