matplotlib.pyplot.legend¶
-
matplotlib.pyplot.
legend
(\*args, \*\*kwargs)[source]¶ Place a legend on the axes.
Call signatures:
legend() legend(labels) legend(handles, labels)
The call signatures correspond to three different ways how to use this method.
1. Automatic detection of elements to be shown in the legend
The elements to be added to the legend are automatically determined, when you do not pass in any extra arguments.
In this case, the labels are taken from the artist. You can specify them either at artist creation or by calling the
set_label()
method on the artist:line, = ax.plot([1, 2, 3], label='Inline label') ax.legend()
or:
line, = ax.plot([1, 2, 3]) line.set_label('Label via method') ax.legend()
Specific lines can be excluded from the automatic legend element selection by defining a label starting with an underscore. This is default for all artists, so calling
Axes.legend
without any arguments and without setting the labels manually will result in no legend being drawn.2. Labeling existing plot elements
To make a legend for lines which already exist on the axes (via plot for instance), simply call this function with an iterable of strings, one for each legend item. For example:
ax.plot([1, 2, 3]) ax.legend(['A simple line'])
Note: This way of using is discouraged, because the relation between plot elements and labels is only implicit by their order and can easily be mixed up.
3. Explicitly defining the elements in the legend
For full control of which artists have a legend entry, it is possible to pass an iterable of legend artists followed by an iterable of legend labels respectively:
legend((line1, line2, line3), ('label1', 'label2', 'label3'))
Parameters: - handlessequence of
Artist
, optional A list of Artists (lines, patches) to be added to the legend. Use this together with labels, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient.
The length of handles and labels should be the same in this case. If they are not, they are truncated to the smaller length.
- labelslist of str, optional
A list of labels to show next to the artists. Use this together with handles, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient.
Returns: - legend
Legend
Other Parameters: - locstr or pair of floats, default:
rcParams["legend.loc"]
(default: 'best') ('best' for axes, 'upper right' for figures) The location of the legend.
The strings
'upper left', 'upper right', 'lower left', 'lower right'
place the legend at the corresponding corner of the axes/figure.The strings
'upper center', 'lower center', 'center left', 'center right'
place the legend at the center of the corresponding edge of the axes/figure.The string
'center'
places the legend at the center of the axes/figure.The string
'best'
places the legend at the location, among the nine locations defined so far, with the minimum overlap with other drawn artists. This option can be quite slow for plots with large amounts of data; your plotting speed may benefit from providing a specific location.The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored).
For back-compatibility,
'center right'
(but no other location) can also be spelled'right'
, and each "string" locations can also be given as a numeric value:Location String Location Code 'best' 0 'upper right' 1 'upper left' 2 'lower left' 3 'lower right' 4 'right' 5 'center left' 6 'center right' 7 'lower center' 8 'upper center' 9 'center' 10 - bbox_to_anchor
BboxBase
, 2-tuple, or 4-tuple of floats Box that is used to position the legend in conjunction with loc. Defaults to
axes.bbox
(if called as a method toAxes.legend
) orfigure.bbox
(ifFigure.legend
). This argument allows arbitrary placement of the legend.Bbox coordinates are interpreted in the coordinate system given by
bbox_transform
, with the default transform Axes or Figure coordinates, depending on whichlegend
is called.If a 4-tuple or
BboxBase
is given, then it specifies the bbox(x, y, width, height)
that the legend is placed in. To put the legend in the best location in the bottom right quadrant of the axes (or figure):loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5)
A 2-tuple
(x, y)
places the corner of the legend specified by loc at x, y. For example, to put the legend's upper right-hand corner in the center of the axes (or figure) the following keywords can be used:loc='upper right', bbox_to_anchor=(0.5, 0.5)
- ncolinteger
The number of columns that the legend has. Default is 1.
- propNone or
matplotlib.font_manager.FontProperties
or dict The font properties of the legend. If None (default), the current
matplotlib.rcParams
will be used.- fontsizeint or float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
The font size of the legend. If the value is numeric the size will be the absolute font size in points. String values are relative to the current default font size. This argument is only used if prop is not specified.
- numpointsNone or int
The number of marker points in the legend when creating a legend entry for a
Line2D
(line). Default isNone
, which means usingrcParams["legend.numpoints"]
(default: 1).- scatterpointsNone or int
The number of marker points in the legend when creating a legend entry for a
PathCollection
(scatter plot). Default isNone
, which means usingrcParams["legend.scatterpoints"]
(default: 1).- scatteryoffsetsiterable of floats
The vertical offset (relative to the font size) for the markers created for a scatter plot legend entry. 0.0 is at the base the legend text, and 1.0 is at the top. To draw all markers at the same height, set to
[0.5]
. Default is[0.375, 0.5, 0.3125]
.- markerscaleNone or int or float
The relative size of legend markers compared with the originally drawn ones. Default is
None
, which means usingrcParams["legend.markerscale"]
(default: 1.0).- markerfirstbool
If True, legend marker is placed to the left of the legend label. If False, legend marker is placed to the right of the legend label. Default is True.
- frameonNone or bool
Whether the legend should be drawn on a patch (frame). Default is
None
, which means usingrcParams["legend.frameon"]
(default: True).- fancyboxNone or bool
Whether round edges should be enabled around the
FancyBboxPatch
which makes up the legend's background. Default isNone
, which means usingrcParams["legend.fancybox"]
(default: True).- shadowNone or bool
Whether to draw a shadow behind the legend. Default is
None
, which means usingrcParams["legend.shadow"]
(default: False).- framealphaNone or float
The alpha transparency of the legend's background. Default is
None
, which means usingrcParams["legend.framealpha"]
(default: 0.8). If shadow is activated and framealpha isNone
, the default value is ignored.- facecolorNone or "inherit" or color
The legend's background color. Default is
None
, which means usingrcParams["legend.facecolor"]
(default: 'inherit'). If"inherit"
, usercParams["axes.facecolor"]
(default: 'white').- edgecolorNone or "inherit" or color
The legend's background patch edge color. Default is
None
, which means usingrcParams["legend.edgecolor"]
(default: '0.8'). If"inherit"
, use takercParams["axes.edgecolor"]
(default: 'black').- mode{"expand", None}
If mode is set to
"expand"
the legend will be horizontally expanded to fill the axes area (orbbox_to_anchor
if defines the legend's size).- bbox_transformNone or
matplotlib.transforms.Transform
The transform for the bounding box (
bbox_to_anchor
). For a value ofNone
(default) the Axes'transAxes
transform will be used.- titlestr or None
The legend's title. Default is no title (
None
).- title_fontsize: str or None
The fontsize of the legend's title. Default is the default fontsize.
- borderpadfloat or None
The fractional whitespace inside the legend border, in font-size units. Default is
None
, which means usingrcParams["legend.borderpad"]
(default: 0.4).- labelspacingfloat or None
The vertical space between the legend entries, in font-size units. Default is
None
, which means usingrcParams["legend.labelspacing"]
(default: 0.5).- handlelengthfloat or None
The length of the legend handles, in font-size units. Default is
None
, which means usingrcParams["legend.handlelength"]
(default: 2.0).- handletextpadfloat or None
The pad between the legend handle and text, in font-size units. Default is
None
, which means usingrcParams["legend.handletextpad"]
(default: 0.8).- borderaxespadfloat or None
The pad between the axes and legend border, in font-size units. Default is
None
, which means usingrcParams["legend.borderaxespad"]
(default: 0.5).- columnspacingfloat or None
The spacing between columns, in font-size units. Default is
None
, which means usingrcParams["legend.columnspacing"]
(default: 2.0).- handler_mapdict or None
The custom dictionary mapping instances or types to a legend handler. This
handler_map
updates the default handler map found atmatplotlib.legend.Legend.get_legend_handler_map()
.
Notes
Not all kinds of artist are supported by the legend command. See Legend guide for details.
Examples
(Source code, png, pdf)
- handlessequence of