Anda di halaman 1dari 17

Add legend to axes - MATLAB legend https://www.mathworks.com/help/matlab/ref/legend.

html

legend
Add legend to axes

Syntax

legend
legend(label1,...,labelN)
legend(labels)
legend(subset, ___ )
legend(target, ___ )

legend( ___ ,'Location',lcn)


legend( ___ ,'Orientation',ornt)
legend( ___ ,Name,Value)
legend(bkgd)
lgd = legend( ___ )
[lgd,icons,plots,txt] = legend( ___ )

legend(vsbl)
legend('off')

Description
legend creates a legend with descriptive labels for each plotted data series. For the labels, the example
legend uses the text from the DisplayName properties of the data series. If the DisplayName
property is empty, then the legend uses a label of the form 'dataN'. The legend automatically
updates when you add or delete data series from the axes. This command creates a legend for the
current axes or chart returned by gca. If the current axes are empty, then the legend is empty. If axes
do not exist, then this command creates them.
example
legend(label1,...,labelN) sets the legend labels. Specify the labels as a list of character
vectors or strings, such as legend('Jan','Feb','Mar').

legend(labels) sets the labels using a cell array of character vectors, a string array, or a character
matrix, such as legend({'Jan','Feb','Mar'}).
example
legend(subset, ___ ) only includes items in the legend for the data series listed in subset. Specify
subset as a vector of graphics objects. You can specify subset before specifying the labels or with
no other input arguments.
example
legend(target, ___ ) uses the axes, polar axes, or chart specified by target instead of the current
axes or chart. Specify the target as the first input argument.

legend( ___ ,'Location',lcn) sets the legend location. For example, 'Location','northeast' example
positions the legend in the upper right corner of the axes. Specify the location after other input
arguments.
example
legend( ___ ,'Orientation',ornt), where ornt is 'horizontal', displays the legend items side-
by-side. The default for ornt is 'vertical', which stacks the items vertically.
example
legend( ___ ,Name,Value) sets legend properties using one or more name-value pair arguments.

1 of 17 7/16/2018, 5:29 PM
Add legend to axes - MATLAB legend https://www.mathworks.com/help/matlab/ref/legend.html

When setting properties, you must specify the labels using a cell array, such as
legend({'A','B'},'FontSize',12). If you do not want to specify labels, then include an empty
cell array, such as legend({},'FontSize',12).
example
legend(bkgd), where bkgd is 'boxoff', removes the legend background and outline. The default
for bkgd is 'boxon', which displays the legend background and outline.

lgd = legend( ___ ) returns the Legend object. Use lgd to query and set properties of the legend
after it is created. For a list of properties, see Legend Properties.

[lgd,icons,plots,txt] = legend( ___ ) additionally returns the objects used to create the legend
icons, the objects plotted in the graph, and an array of the label text. This syntax is not
recommended. It creates a legend that does not support some functionality, such as adding a legend
title. Also, the legend does not automatically update when you add or remove data series from the
axes. Instead, use the lgd = legend(__) syntax to return the Legend object and set Legend
Properties.

legend(vsbl) controls the visibility of the legend, where vsbl is 'hide', 'show', or 'toggle'.

legend('off') deletes the legend.

Examples collapse all

Add Legend to Current Axes

Plot two lines and add a legend to the current axes. Specify the
Try This Example
legend labels as input arguments to the legend function.

x = linspace(0,pi);
y1 = cos(x);
plot(x,y1)

hold on
y2 = cos(2*x);
plot(x,y2)

legend('cos(x)','cos(2x)')

2 of 17 7/16/2018, 5:29 PM
Add legend to axes - MATLAB legend https://www.mathworks.com/help/matlab/ref/legend.html

If you add or delete a data series from the axes, the legend updates accordingly. Control the label for the new
data series by setting the DisplayName property as a name-value pair during creation. If you do not specify a
label, then the legend uses a label of the form 'dataN'.

Note: If you do not want the legend to automatically update when data series are added to or removed from
the axes, then set the AutoUpdate property of the legend to 'off'.

y3 = cos(3*x);
plot(x,y3,'DisplayName','cos(3x)')
hold off

3 of 17 7/16/2018, 5:29 PM
Add legend to axes - MATLAB legend https://www.mathworks.com/help/matlab/ref/legend.html

Delete the legend.

legend('off')

Add Legend to Specific Axes

4 of 17 7/16/2018, 5:29 PM
Add legend to axes - MATLAB legend https://www.mathworks.com/help/matlab/ref/legend.html

Create a figure with two subplots and return the two Axes
Try This Example
objects, ax1 and ax2. Plot random data in each subplot. Add a
legend to the upper subplot by specifying ax1 as the first input
argument to legend.

y1 = rand(3);
ax1 = subplot(2,1,1);
plot(y1)

y2 = rand(5);
ax2 = subplot(2,1,2);
plot(y2)

legend(ax1,{'Line 1','Line 2','Line 3'})

Specify Legend Labels During Plotting Commands

Plot two lines. Specify the legend labels during the plotting
Try This Example
commands by setting the DisplayName property to the desired
text. Then, add a legend.

5 of 17 7/16/2018, 5:29 PM
Add legend to axes - MATLAB legend https://www.mathworks.com/help/matlab/ref/legend.html

x = linspace(0,pi);
y1 = cos(x);
plot(x,y1,'DisplayName','cos(x)')

hold on
y2 = cos(2*x);
plot(x,y2,'DisplayName','cos(2x)')
hold off

legend

Legend Location and Number of Columns

Plot four lines. Create a legend in the northwest area of the axes.
Try This Example
Specify the number of legend columns using the NumColumns
property.

6 of 17 7/16/2018, 5:29 PM
Add legend to axes - MATLAB legend https://www.mathworks.com/help/matlab/ref/legend.html

x = linspace(0,pi);
y1 = cos(x);
plot(x,y1)

hold on
y2 = cos(2*x);
plot(x,y2)

y3 = cos(3*x);
plot(x,y3)

y4 = cos(4*x);
plot(x,y4)
hold off

legend({'cos(x)','cos(2x)','cos(3x)','cos(4x)'},'Location','northwest','NumColumns',2)

By default, the legend orders the items from top to bottom along each column. To order the items from left to
right along each row instead, set the Orientation property to 'horizontal'.

Included Subset of Graphics Objects in Legend

If you do not want to include all of the plotted graphics objects in


Try This Example
the legend, then you can specify the graphics objects that you
want to include.

Plot three lines and return the Line objects created. Create a legend that includes only two of the lines.
Specify the first input argument as a vector of the Line objects to include.

7 of 17 7/16/2018, 5:29 PM
Add legend to axes - MATLAB legend https://www.mathworks.com/help/matlab/ref/legend.html

x = linspace(0,pi);
y1 = cos(x);
p1 = plot(x,y1);

hold on
y2 = cos(2*x);
p2 = plot(x,y2);

y3 = cos(3*x);
p3 = plot(x,y3);
hold off

legend([p1 p3],{'First','Third'})

Add Title to Legend

Plot two lines and create a legend. Then, add a title to the
Try This Example
legend.

8 of 17 7/16/2018, 5:29 PM
Add legend to axes - MATLAB legend https://www.mathworks.com/help/matlab/ref/legend.html

x = linspace(0,pi);
y1 = cos(x);
plot(x,y1)

hold on
y2 = cos(2*x);
plot(x,y2)
hold off

lgd = legend('cos(x)','cos(2x)');
title(lgd,'My Legend Title')

Remove Legend Background

Plot two lines and create a legend in the lower left corner of the
Try This Example
axes. Then, remove the legend background and outline.

x = linspace(0,pi);
y1 = cos(x);
plot(x,y1)

hold on
y2 = cos(2*x);
plot(x,y2)
hold off

legend({'cos(x)','cos(2x)'},'Location','southwest')
legend('boxoff')

9 of 17 7/16/2018, 5:29 PM
Add legend to axes - MATLAB legend https://www.mathworks.com/help/matlab/ref/legend.html

Modify Legend Appearance

Modify the legend appearance by setting Legend properties. You


Try This Example
can set properties when you create the legend using name-value
pairs in the legend command. You also can set properties after
you create the legend using the Legend object.

Plot four lines of random data. Create legend and assign the Legend object to the variable lgd. Set the
FontSize and TextColor properties using name-value pairs. When you specify name-value pair arguments,
you must specify the legend labels using a cell array.

rdm = rand(4);
plot(rdm)

lgd = legend({'Line 1','Line 2','Line 3','Line 4'},'FontSize',12,'TextColor','blue')

10 of 17 7/16/2018, 5:29 PM
Add legend to axes - MATLAB legend https://www.mathworks.com/help/matlab/ref/legend.html

lgd =
Legend (Line 1, Line 2, Line 3, Line 4) with properties:

String: {'Line 1' 'Line 2' 'Line 3' 'Line 4'}


Location: 'northeast'
Orientation: 'vertical'
FontSize: 12
Position: [0.7088 0.7034 0.1778 0.1957]
Units: 'normalized'

Show all properties

Modify the legend after it is created by referring to lgd. Set the NumColumns property using the object dot
property name notation.

lgd.NumColumns = 2;

11 of 17 7/16/2018, 5:29 PM
Add legend to axes - MATLAB legend https://www.mathworks.com/help/matlab/ref/legend.html

Input Arguments collapse all

label1,...,labelN — Labels (as separate arguments)


character vectors | strings

Labels, specified as separate arguments of character vectors or strings. To include special characters or
Greek letters in the labels, use TeX markup. For a table of options, see the Interpreter property.

Example: legend('Sin Function','Cos Function')

Example: legend("Sin Function","Cos Function")

Example: legend('\gamma','\sigma')

To specify labels that are keywords, such as 'Location' or 'off', use a cell array of character vectors, a
string array, or a character array.

12 of 17 7/16/2018, 5:29 PM
Add legend to axes - MATLAB legend https://www.mathworks.com/help/matlab/ref/legend.html

labels — Labels (as an array)


cell array of character vectors | string array | character array

Labels, specified as a cell array of character vectors, a string array, or a character array. To include special
characters or Greek letters in the labels, use TeX markup. For a table of options, see the Interpreter
property.

Example: legend({'Sin Function','Cos Function'})

Example: legend(["Sin Function","Cos Function"])

Example: legend(['Sin Function';'Cos Function'])

Example: legend({'\gamma','\sigma'})

subset — Data series to include in legend


vector of graphics objects

Data series to include in the legend, specified as a vector of graphics objects.

target — Target for legend


Axes object | PolarAxes object | graphics object

Target for legend, specified as an Axes object, a PolarAxes object, or a graphics object with a
LegendVisible property, such as a GeographicBubbleChart object. If you do not specify the target, then the
legend function uses the axes or chart returned by the gca command.

Some charts do not support modifying the legend appearance, such as the location, or returning the Legend
object as an output argument..

lcn — Legend location


'north' | 'south' | 'east' | 'west' | 'northeast' | ...

Legend location with respect to the axes, specified as one of the location values listed in this table.

Value Description

'north' Inside top of axes


'south' Inside bottom of axes
'east' Inside right of axes
'west' Inside left of axes
'northeast' Inside top-right of axes (default for 2-D axes)
'northwest' Inside top-left of axes
'southeast' Inside bottom-right of axes
'southwest' Inside bottom-left of axes
'northoutside' Above the axes
'southoutside' Below the axes
'eastoutside' To the right of the axes
'westoutside' To the left of the axes

13 of 17 7/16/2018, 5:29 PM
Add legend to axes - MATLAB legend https://www.mathworks.com/help/matlab/ref/legend.html

Value Description

'northeastoutside' Outside top-right corner of the axes (default for 3-D axes)
'northwestoutside' Outside top-left corner of the axes
'southeastoutside' Outside bottom-right corner of the axes
'southwestoutside' Outside bottom-left corner of the axes
'best' Inside axes where least conflict occurs with plot data
'bestoutside' To the right of the axes
'none' Determined by Position property. Use the Position
property to display the legend in a custom location.

Example: legend('Location','northeastoutside')

ornt — Orientation
'vertical' (default) | 'horizontal'

Orientation, specified as one of these values:

• 'vertical' — Stack the legend items vertically.


• 'horizontal' — List the legend items side-by-side.

Example: legend('Orientation','horizontal')

bkgd — Legend box display


'boxon' (default) | 'boxoff'

Legend box display, specified as one of these values:

• 'boxon' — Display the legend background and outline.


• 'boxoff' — Do not display the legend background and outline.

Example: legend('boxoff')

vsbl — Legend visibility


'hide' | 'show' | 'toggle'

Legend visibility, specified as one of these values:

• 'hide' — Hide the legend.


• 'Show' — Show the legend or create a legend if one does not exist.
• 'toggle' — Toggle the legend visibility.

Example: legend('hide')

Name-Value Pair Arguments


Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and Value is the
corresponding value. Name must appear inside single quotes (' '). You can specify several name and value pair
arguments in any order as Name1,Value1,...,NameN,ValueN.

Example: legend({'A','B'},'TextColor','blue','FontSize',12) creates a legend with blue, 12-point font.

14 of 17 7/16/2018, 5:29 PM
Add legend to axes - MATLAB legend https://www.mathworks.com/help/matlab/ref/legend.html

Note
The properties listed here are only a subset. For a complete list, see Legend Properties.
collapse all

'TextColor' — Text color


[0 0 0] (default) | RGB triplet | 'r' | 'g' | 'b' | ...

Text color, specified as an RGB triplet or one of the color options listed in the table. The default color is black
with an RGB triplet value of [0 0 0].

For a custom color, specify an RGB triplet. An RGB triplet is a three-element row vector whose elements
specify the intensities of the red, green, and blue components of the color. The intensities must be in the range
[0,1]; for example, [0.4 0.6 0.7]. Alternatively, you can specify some common colors by name. This table
lists the long and short color name options and the equivalent RGB triplet values.

Option Description Equivalent RGB Triplet

'red' or 'r' Red [1 0 0]


'green' or 'g' Green [0 1 0]
'blue' or 'b' Blue [0 0 1]
'yellow' or 'y' Yellow [1 1 0]
'magenta' or 'm' Magenta [1 0 1]
'cyan' or 'c' Cyan [0 1 1]
'white' or 'w' White [1 1 1]
'black' or 'k' Black [0 0 0]
'none' No color Not applicable
Example: [0 0 0.5]

Example: 'blue'

'FontSize' — Font size


scalar value greater than zero

Font size, specified as a scalar value greater than zero in point units. The default font size depends on the
specific operating system and locale.

If you change the axes font size, then MATLAB® automatically sets the font size of the legend object to 90%
of the axes font size. If you manually set the legend object font size, then changing the axes font size does
not affect the legend object.

collapse all

'NumColumns' — Number of columns


1 (default) | positive integer

15 of 17 7/16/2018, 5:29 PM
Add legend to axes - MATLAB legend https://www.mathworks.com/help/matlab/ref/legend.html

Number of columns, specified as a positive integer. If there are not enough legend items to fill the specified
number of columns, then the number of columns that appear might be fewer.

Use the Orientation property to control whether the legend items appear in order along each column or
along each row.

Example: lgd.NumColumns = 3

Output Arguments collapse all

lgd — Legend object


Legend object

Legend object. Use lgd to view or modify properties of the legend after it is created.

plot(rand(3))
lgd = legend('line1','line2','line3');
lgd.FontSize = 12;
lgd.FontWeight = 'bold';

Note
Starting in R2014b, the legend function returns a Legend object. For earlier releases, it returns an
Axes object.

icons — Objects used to create legend icons and labels


Text, Patch, and Line objects

Objects used to create the legend icons and labels, returned as Text, Patch, and Line objects.

Note

This output argument is not recommended.

plots — Objects plotted in axes


vector of graphics objects

Objects plotted in the axes, returned as a vector of graphics objects.

Note
This output argument is not recommended.

txt — Text used for legend labels


cell array of character vectors

16 of 17 7/16/2018, 5:29 PM
Add legend to axes - MATLAB legend https://www.mathworks.com/help/matlab/ref/legend.html

Text used for legend labels, returned as a cell array of character vectors.

Note

This output argument is not recommended. Instead, access the labels using the String property of
the legend.

More About collapse all

Compatibility Considerations

• Starting in R2017b, if axes do not exist, then the legend function creates them.
• Starting in R2017a, the legend automatically updates when you add or remove data series from the axes. If
you do not want the legend to automatically update, set the AutoUpdate property of the legend to 'off'.

Tips
• To label more than 20 objects in the legend, specify a label for each object. Otherwise, legend depicts only the
first 20 objects in the graph.

Algorithms
• Recalling the legend function does not reset legend properties, such as the location or orientation. If a legend
exists, then the legend function updates the existing legend. An Axes object can have only one legend.
• The legend reflects the visibility of graphics objects in the axes. Graphics objects that have a Visible property
set to 'off' appear as grayed out items in the legend.

See Also

Functions
hold | plot | text | title | xlabel | ylabel

Properties
Legend Properties

Topics
Add Legend to Graph

Introduced before R2006a

17 of 17 7/16/2018, 5:29 PM

Anda mungkin juga menyukai