matplotlib.legend
The legend module defines the Legend class, which is responsible for drawing legends associated with axes and/or figures.
Important
It is unlikely that you would ever create a Legend instance manually. Most users would normally create a legend via the legend()
function. For more details on legends there is also a legend guide.
The Legend class can be considered as a container of legend handles and legend texts. Creation of corresponding legend handles from the plot elements in the axes or figures (e.g., lines, patches, etc.) are specified by the handler map, which defines the mapping between the plot elements and the legend handlers to be used (the default legend handlers are defined in the legend_handler
module). Note that not all kinds of artist are supported by the legend yet by default but it is possible to extend the legend handler's capabilities to support arbitrary objects. See the legend guide for more information.
-
class matplotlib.legend.DraggableLegend(legend, use_blit=False, update='loc')
[source] -
Bases:
matplotlib.offsetbox.DraggableOffsetBox
Wrapper around a
Legend
to support mouse dragging.Parameters: -
legendLegend
-
The
Legend
instance to wrap. -
use_blitbool, optional
-
Use blitting for faster image composition. For details see FuncAnimation.
-
update{'loc', 'bbox'}, optional
-
If "loc", update the loc parameter of the legend upon finalizing. If "bbox", update the bbox_to_anchor parameter.
-
artist_picker(self, legend, evt)
[source]
-
finalize_offset(self)
[source]
-
-
class matplotlib.legend.Legend(parent, handles, labels, loc=None, numpoints=None, markerscale=None, markerfirst=True, scatterpoints=None, scatteryoffsets=None, prop=None, fontsize=None, borderpad=None, labelspacing=None, handlelength=None, handleheight=None, handletextpad=None, borderaxespad=None, columnspacing=None, ncol=1, mode=None, fancybox=None, shadow=None, title=None, title_fontsize=None, framealpha=None, edgecolor=None, facecolor=None, bbox_to_anchor=None, bbox_transform=None, frameon=None, handler_map=None)
[source] -
Bases:
matplotlib.artist.Artist
Place a legend on the axes at location loc.
Parameters: -
parentAxes or Figure
-
The artist that contains the legend.
-
handleslist of Artist
-
A list of Artists (lines, patches) to be added to the legend.
-
labelslist of str
-
A list of labels to show next to the artists. The length of handles and labels should be the same. If they are not, they are truncated to the smaller of both lengths.
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_anchorBboxBase, 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
Users can specify any arbitrary location for the legend using the bbox_to_anchor keyword argument. bbox_to_anchor can be a
BboxBase
(or derived therefrom) or a tuple of 2 or 4 floats. Seeset_bbox_to_anchor()
for more detail.The legend location can be specified by setting loc with a tuple of 2 floats, which is interpreted as the lower-left corner of the legend in the normalized axes coordinate.
-
codes = {'best': 0, 'center': 10, 'center left': 6, 'center right': 7, 'lower center': 8, 'lower left': 3, 'lower right': 4, 'right': 5, 'upper center': 9, 'upper left': 2, 'upper right': 1}
-
contains(self, event)
[source] -
Test whether the artist contains the mouse event.
Parameters: -
mouseeventmatplotlib.backend_bases.MouseEvent
Returns: -
containsbool
-
Whether any values are within the radius.
-
detailsdict
-
An artist-specific dictionary of details of the event context, such as which points are contained in the pick radius. See the individual Artist subclasses for details.
See also
-
set_contains, get_contains
-
-
draw(self, renderer)
[source] -
Draw everything that belongs to the legend.
-
draw_frame(self, b)
[source] -
Set draw frame to b.
Parameters: -
bbool
-
-
get_bbox_to_anchor(self)
[source] -
Return the bbox that the legend will be anchored to.
-
get_children(self)
[source] -
Return a list of child artists.
-
classmethod get_default_handler_map()
[source] -
A class method that returns the default handler map.
-
get_draggable(self)
[source] -
Return
True
if the legend is draggable,False
otherwise.
-
get_frame_on(self)
[source] -
Get whether the legend box patch is drawn.
-
static get_legend_handler(legend_handler_map, orig_handle)
[source] -
Return a legend handler from legend_handler_map that corresponds to orig_handler.
legend_handler_map should be a dictionary object (that is returned by the get_legend_handler_map method).
It first checks if the orig_handle itself is a key in the legend_handler_map and return the associated value. Otherwise, it checks for each of the classes in its method-resolution-order. If no matching key is found, it returns
None
.
-
get_legend_handler_map(self)
[source] -
Return the handler map.
-
get_tightbbox(self, renderer)
[source] -
Like
Legend.get_window_extent
, but uses the box for the legend.Parameters: -
rendererRendererBase instance
-
renderer that will be used to draw the figures (i.e.
fig.canvas.get_renderer()
)
Returns: -
`.BboxBase`containing the bounding box in figure pixel co-ordinates.
-
-
get_window_extent(self, renderer=None)
[source] -
Return extent of the legend.
-
set_bbox_to_anchor(self, bbox, transform=None)
[source] -
Set the bbox that the legend will be anchored to.
bbox can be
- A
BboxBase
instance - A tuple of
(left, bottom, width, height)
in the given transform (normalized axes coordinate if None) - A tuple of
(left, bottom)
where the width and height will be assumed to be zero.
- A
-
classmethod set_default_handler_map(handler_map)
[source] -
A class method to set the default handler map.
-
set_draggable(self, state, use_blit=False, update='loc')
[source] -
Enable or disable mouse dragging support of the legend.
Parameters: -
statebool
-
Whether mouse dragging is enabled.
-
use_blitbool, optional
-
Use blitting for faster image composition. For details see FuncAnimation.
-
update{'loc', 'bbox'}, optional
-
The legend parameter to be changed when dragged:
- 'loc': update the loc parameter of the legend
- 'bbox': update the bbox_to_anchor parameter of the legend
Returns: -
If state is True this returns the DraggableLegend helper
-
instance. Otherwise this returns None.
-
-
set_frame_on(self, b)
[source] -
Set whether the legend box patch is drawn.
Parameters: -
bbool
-
-
set_title(self, title, prop=None)
[source] -
Set the legend title. Fontproperties can be optionally set with prop parameter.
-
classmethod update_default_handler_map(handler_map)
[source] -
A class method to update the default handler map.
-
zorder = 5
-
© 2012–2018 Matplotlib Development Team. All rights reserved.
Licensed under the Matplotlib License Agreement.
https://matplotlib.org/3.2.2/api/legend_api.html