matplotlib.pyplot.legend#
- matplotlib.pyplot.legend(*args,**kwargs)[source]#
Place a legend on the Axes.
Call signatures:
legend()legend(handles,labels)legend(handles=handles)legend(labels)
The call signatures correspond to the following different ways to usethis 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 specifythem either at artist creation or by calling the
set_label()
method on the artist: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()
Note
Specific artists can be excluded from the automatic legend elementselection by using a label starting with an underscore, "_".A string starting with an underscore is the default label for allartists, so calling
Axes.legend
without any arguments andwithout setting the labels manually will result in aUserWarning
and an empty legend being drawn.2. Explicitly listing the artists and labels in the legend
For full control of which artists have a legend entry, it is possibleto pass an iterable of legend artists followed by an iterable oflegend labels respectively:
ax.legend([line1,line2,line3],['label1','label2','label3'])
3. Explicitly listing the artists in the legend
This is similar to 2, but the labels are taken from the artists'label properties. Example:
line1,=ax.plot([1,2,3],label='label1')line2,=ax.plot([1,2,3],label='label2')ax.legend(handles=[line1,line2])
4. Labeling existing plot elements
Discouraged
This call signature is discouraged, because the relation betweenplot elements and labels is only implicit by their order and caneasily be mixed up.
To make a legend for all artists on an Axes, call this function withan iterable of strings, one for each legend item. For example:
ax.plot([1,2,3])ax.plot([5,6,7])ax.legend(['First line','Second line'])
- Parameters:
- handleslist of (
Artist
or tuple ofArtist
), optional A list of Artists (lines, patches) to be added to the legend.Use this together withlabels, if you need full control on whatis shown in the legend and the automatic mechanism described aboveis not sufficient.
The length of handles and labels should be the same in thiscase. If they are not, they are truncated to the smaller length.
If an entry contains a tuple, then the legend handler for all Artists in thetuple will be placed alongside a single label.
- labelslist of str, optional
A list of labels to show next to the artists.Use this together withhandles, if you need full control on whatis shown in the legend and the automatic mechanism described aboveis not sufficient.
- handleslist of (
- Returns:
- Other Parameters:
- locstr or pair of floats, default:
rcParams["legend.loc"]
(default:'best'
) The location of the legend.
The strings
'upperleft'
,'upperright'
,'lowerleft'
,'lowerright'
place the legend at the corresponding corner of theaxes.The strings
'uppercenter'
,'lowercenter'
,'centerleft'
,'centerright'
place the legend at the center of the corresponding edgeof the axes.The string
'center'
places the legend at the center of the axes.The string
'best'
places the legend at the location, among the ninelocations defined so far, with the minimum overlap with other drawnartists. This option can be quite slow for plots with large amounts ofdata; your plotting speed may benefit from providing a specific location.The location can also be a 2-tuple giving the coordinates of the lower-leftcorner of the legend in axes coordinates (in which casebbox_to_anchorwill be ignored).
For back-compatibility,
'centerright'
(but no other location) can alsobe spelled'right'
, and each "string" location can also be given as anumeric value:Location String
Location Code
'best' (Axes only)
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 withloc.Defaults to
axes.bbox
(if called as a method toAxes.legend
) orfigure.bbox
(iffigure.legend
). This argument allows arbitraryplacement of the legend.Bbox coordinates are interpreted in the coordinate system given bybbox_transform, with the default transformAxes or Figure coordinates, depending on which
legend
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 rightquadrant 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 byloc atx, y. For example, to put the legend's upper right-hand corner in thecenter of the Axes (or figure) the following keywords can be used:loc='upper right',bbox_to_anchor=(0.5,0.5)
- ncolsint, default: 1
The number of columns that the legend has.
For backward compatibility, the spellingncol is also supportedbut it is discouraged. If both are given,ncols takes precedence.
- propNone or
FontProperties
or dict The font properties of the legend. If None (default), the current
matplotlib.rcParams
will be used.- fontsizeint 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 theabsolute font size in points. String values are relative to the currentdefault font size. This argument is only used ifprop is not specified.
- labelcolorstr or list, default:
rcParams["legend.labelcolor"]
(default:'None'
) The color of the text in the legend. Either a valid color string(for example, 'red'), or a list of color strings. The labelcolor canalso be made to match the color of the line or marker using 'linecolor','markerfacecolor' (or 'mfc'), or 'markeredgecolor' (or 'mec').
Labelcolor can be set globally using
rcParams["legend.labelcolor"]
(default:'None'
). If None,usercParams["text.color"]
(default:'black'
).- numpointsint, default:
rcParams["legend.numpoints"]
(default:1
) The number of marker points in the legend when creating a legendentry for a
Line2D
(line).- scatterpointsint, default:
rcParams["legend.scatterpoints"]
(default:1
) The number of marker points in the legend when creatinga legend entry for a
PathCollection
(scatter plot).- scatteryoffsetsiterable of floats, default:
[0.375,0.5,0.3125]
The vertical offset (relative to the font size) for the markerscreated for a scatter plot legend entry. 0.0 is at the base thelegend text, and 1.0 is at the top. To draw all markers at thesame height, set to
[0.5]
.- markerscalefloat, default:
rcParams["legend.markerscale"]
(default:1.0
) The relative size of legend markers compared to the originally drawn ones.
- markerfirstbool, default: True
IfTrue, legend marker is placed to the left of the legend label.IfFalse, legend marker is placed to the right of the legend label.
- reversebool, default: False
IfTrue, the legend labels are displayed in reverse order from the input.IfFalse, the legend labels are displayed in the same order as the input.
Added in version 3.7.
- frameonbool, default:
rcParams["legend.frameon"]
(default:True
) Whether the legend should be drawn on a patch (frame).
- fancyboxbool, default:
rcParams["legend.fancybox"]
(default:True
) Whether round edges should be enabled around the
FancyBboxPatch
whichmakes up the legend's background.- shadowNone, bool or dict, default:
rcParams["legend.shadow"]
(default:False
) Whether to draw a shadow behind the legend.The shadow can be configured using
Patch
keywords.Customization viarcParams["legend.shadow"]
(default:False
) is currently not supported.- framealphafloat, default:
rcParams["legend.framealpha"]
(default:0.8
) The alpha transparency of the legend's background.Ifshadow is activated andframealpha is
None
, the default value isignored.- facecolor"inherit" or color, default:
rcParams["legend.facecolor"]
(default:'inherit'
) The legend's background color.If
"inherit"
, usercParams["axes.facecolor"]
(default:'white'
).- edgecolor"inherit" or color, default:
rcParams["legend.edgecolor"]
(default:'0.8'
) The legend's background patch edge color.If
"inherit"
, usercParams["axes.edgecolor"]
(default:'black'
).- mode{"expand", None}
Ifmode is set to
"expand"
the legend will be horizontallyexpanded to fill the Axes area (orbbox_to_anchor if definesthe legend's size).- bbox_transformNone or
Transform
The transform for the bounding box (bbox_to_anchor). For a valueof
None
(default) the Axes'transAxes
transform will be used.- titlestr or None
The legend's title. Default is no title (
None
).- title_fontpropertiesNone or
FontProperties
or dict The font properties of the legend's title. If None (default), thetitle_fontsize argument will be used if present; iftitle_fontsize isalso None, the current
rcParams["legend.title_fontsize"]
(default:None
) will be used.- title_fontsizeint or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}, default:
rcParams["legend.title_fontsize"]
(default:None
) The font size of the legend's title.Note: This cannot be combined withtitle_fontproperties. If you wantto set the fontsize alongside other font properties, use thesizeparameter intitle_fontproperties.
- alignment{'center', 'left', 'right'}, default: 'center'
The alignment of the legend title and the box of entries. The entriesare aligned as a single block, so that markers always lined up.
- borderpadfloat, default:
rcParams["legend.borderpad"]
(default:0.4
) The fractional whitespace inside the legend border, in font-size units.
- labelspacingfloat, default:
rcParams["legend.labelspacing"]
(default:0.5
) The vertical space between the legend entries, in font-size units.
- handlelengthfloat, default:
rcParams["legend.handlelength"]
(default:2.0
) The length of the legend handles, in font-size units.
- handleheightfloat, default:
rcParams["legend.handleheight"]
(default:0.7
) The height of the legend handles, in font-size units.
- handletextpadfloat, default:
rcParams["legend.handletextpad"]
(default:0.8
) The pad between the legend handle and text, in font-size units.
- borderaxespadfloat, default:
rcParams["legend.borderaxespad"]
(default:0.5
) The pad between the Axes and legend border, in font-size units.
- columnspacingfloat, default:
rcParams["legend.columnspacing"]
(default:2.0
) The spacing between columns, in font-size units.
- handler_mapdict or None
The custom dictionary mapping instances or types to a legendhandler. Thishandler_map updates the default handler mapfound at
matplotlib.legend.Legend.get_legend_handler_map
.- draggablebool, default: False
Whether the legend can be dragged with the mouse.
- locstr or pair of floats, default:
See also
Notes
Note
This is thepyplot wrapper for
axes.Axes.legend
.Some artists are not supported by this function. SeeLegend guide for details.
Examples