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 is a container of legend handles and legend texts.

The legend handler map specifies how to create legend handles from artists (lines, patches, etc.) in the axes or figures. Default legend handlers are defined in the legend_handler module. While not all artist types are covered by the default legend handlers, custom legend handlers can be defined to support arbitrary objects.

See the :ref`<legend_guide>` for more information.

class matplotlib.legend.DraggableLegend(legend, use_blit=False, update='loc')[source]#

Bases: 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.

finalize_offset()[source]#
class matplotlib.legend.Legend(parent, handles, labels, *, loc=None, numpoints=None, markerscale=None, markerfirst=True, reverse=False, scatterpoints=None, scatteryoffsets=None, prop=None, fontsize=None, labelcolor=None, borderpad=None, labelspacing=None, handlelength=None, handleheight=None, handletextpad=None, borderaxespad=None, columnspacing=None, ncols=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, title_fontproperties=None, alignment='center', ncol=1, draggable=False)[source]#

Bases: Artist

Place a legend on the figure/axes.

Parameters:
parentAxes or Figure

The artist that contains the legend.

handleslist of (Artist or tuple 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 length of the shorter list.

Other Parameters:
locstr or pair of floats, default: rcParams["legend.loc"] (default: 'best') for Axes, 'upper right' for Figure

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/figure 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" location can also be given as a numeric 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

If a figure is using the constrained layout manager, the string codes of the loc keyword argument can get better layout behaviour using the prefix 'outside'. There is ambiguity at the corners, so 'outside upper right' will make space for the legend above the rest of the axes in the layout, and 'outside right upper' will make space on the right side of the layout. In addition to the values of loc listed above, we have 'outside right upper', 'outside right lower', 'outside left upper', and 'outside left lower'. See Legend guide for more details.

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 to Axes.legend) or figure.bbox (if Figure.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 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 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)
ncolsint, default: 1

The number of columns that the legend has.

For backward compatibility, the spelling ncol is also supported but 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 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.

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 can also 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, use rcParams["text.color"] (default: 'black').

numpointsint, default: rcParams["legend.numpoints"] (default: 1)

The number of marker points in the legend when creating a legend entry for a Line2D (line).

scatterpointsint, default: rcParams["legend.scatterpoints"] (default: 1)

The number of marker points in the legend when creating a 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 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].

markerscalefloat, default: rcParams["legend.markerscale"] (default: 1.0)

The relative size of legend markers compared to the originally drawn ones.

markerfirstbool, default: True

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.

reversebool, default: False

If True, the legend labels are displayed in reverse order from the input. If False, the legend labels are displayed in the same order as the input.

New 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 which makes 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 via rcParams["legend.shadow"] (default: False) is currently not supported.

framealphafloat, default: rcParams["legend.framealpha"] (default: 0.8)

The alpha transparency of the legend's background. If shadow is activated and framealpha is None, the default value is ignored.

facecolor"inherit" or color, default: rcParams["legend.facecolor"] (default: 'inherit')

The legend's background color. If "inherit", use rcParams["axes.facecolor"] (default: 'white').

edgecolor"inherit" or color, default: rcParams["legend.edgecolor"] (default: '0.8')

The legend's background patch edge color. If "inherit", use take rcParams["axes.edgecolor"] (default: 'black').

mode{"expand", None}

If mode is set to "expand" the legend will be horizontally expanded to fill the axes area (or bbox_to_anchor if defines the legend's size).

bbox_transformNone or Transform

The transform for the bounding box (bbox_to_anchor). For a value of 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), the title_fontsize argument will be used if present; if title_fontsize is also 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 with title_fontproperties. If you want to set the fontsize alongside other font properties, use the size parameter in title_fontproperties.

alignment{'center', 'left', 'right'}, default: 'center'

The alignment of the legend title and the box of entries. The entries are 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 legend handler. This handler_map updates the default handler map found at matplotlib.legend.Legend.get_legend_handler_map.

draggablebool, default: False

Whether the legend can be dragged with the mouse.

Attributes:
legend_handles

List of Artist objects added as legend entries.

New in version 3.7.

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(mouseevent)[source]#

Test whether the artist contains the mouse event.

Parameters:
mouseeventMouseEvent
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.

draw(renderer)[source]#

Draw the Artist (and its children) using the given renderer.

This has no effect if the artist is not visible (Artist.get_visible returns False).

Parameters:
rendererRendererBase subclass.

Notes

This method is overridden in the Artist subclasses.

draw_frame(b)[source]#

Set whether the legend box patch is drawn.

Parameters:
bbool
get_alignment()[source]#

Get the alignment value of the legend box

get_bbox_to_anchor()[source]#

Return the bbox that the legend will be anchored to.

get_children()[source]#

Return a list of the child Artists of this Artist.

classmethod get_default_handler_map()[source]#

Return the global default handler map, shared by all legends.

get_draggable()[source]#

Return True if the legend is draggable, False otherwise.

get_frame()[source]#

Return the Rectangle used to frame the legend.

get_frame_on()[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()[source]#

Return this legend instance's handler map.

get_lines()[source]#

Return the list of Line2Ds in the legend.

get_patches()[source]#

Return the list of Patchs in the legend.

get_texts()[source]#

Return the list of Texts in the legend.

get_tightbbox(renderer=None)[source]#

Like Artist.get_window_extent, but includes any clipping.

Parameters:
rendererRendererBase subclass, optional

renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer())

Returns:
Bbox or None

The enclosing bounding box (in figure pixel coordinates). Returns None if clipping results in no intersection.

get_title()[source]#

Return the Text instance for the legend title.

get_window_extent(renderer=None)[source]#

Get the artist's bounding box in display space.

The bounding box' width and height are nonnegative.

Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0.

Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.

property legendHandles[source]#

[Deprecated]

Notes

Deprecated since version 3.7: Use legend_handles instead.

set(*, agg_filter=<UNSET>, alignment=<UNSET>, alpha=<UNSET>, animated=<UNSET>, bbox_to_anchor=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, draggable=<UNSET>, frame_on=<UNSET>, gid=<UNSET>, in_layout=<UNSET>, label=<UNSET>, loc=<UNSET>, mouseover=<UNSET>, ncols=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, title=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, zorder=<UNSET>)[source]#

Set multiple properties at once.

Supported properties are

Property

Description

agg_filter

a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image

alignment

{'center', 'left', 'right'}.

alpha

scalar or None

animated

bool

bbox_to_anchor

BboxBase or tuple

clip_box

BboxBase or None

clip_on

bool

clip_path

Patch or (Path, Transform) or None

draggable

bool

figure

Figure

frame_on

bool

gid

str

in_layout

bool

label

object

loc

str or pair of floats, default: rcParams["legend.loc"] (default: 'best') for Axes, 'upper right' for Figure

mouseover

bool

ncols

unknown

path_effects

list of AbstractPathEffect

picker

None or bool or float or callable

rasterized

bool

sketch_params

(scale: float, length: float, randomness: float)

snap

bool or None

title

str

transform

Transform

url

str

visible

bool

zorder

float

set_alignment(alignment)[source]#

Set the alignment of the legend title and the box of entries.

The entries are aligned as a single block, so that markers always lined up.

Parameters:
alignment{'center', 'left', 'right'}.
set_bbox_to_anchor(bbox, transform=None)[source]#

Set the bbox that the legend will be anchored to.

Parameters:
bboxBboxBase or tuple

The bounding box can be specified in the following ways:

  • 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.

  • None, to remove the bbox anchoring, and use the parent bbox.

transformTransform, optional

A transform to apply to the bounding box. If not specified, this will use a transform to the bounding box of the parent.

classmethod set_default_handler_map(handler_map)[source]#

Set the global default handler map, shared by all legends.

set_draggable(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:
DraggableLegend or None

If state is True this returns the DraggableLegend helper instance. Otherwise this returns None.

set_frame_on(b)[source]#

Set whether the legend box patch is drawn.

Parameters:
bbool
set_loc(loc=None)[source]#

Set the location of the legend.

New in version 3.8.

Parameters:
locstr or pair of floats, default: rcParams["legend.loc"] (default: 'best') for Axes, 'upper right' for Figure

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/figure 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" location can also be given as a numeric 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

If a figure is using the constrained layout manager, the string codes of the loc keyword argument can get better layout behaviour using the prefix 'outside'. There is ambiguity at the corners, so 'outside upper right' will make space for the legend above the rest of the axes in the layout, and 'outside right upper' will make space on the right side of the layout. In addition to the values of loc listed above, we have 'outside right upper', 'outside right lower', 'outside left upper', and 'outside left lower'. See Legend guide for more details.

set_ncols(ncols)[source]#

Set the number of columns.

set_title(title, prop=None)[source]#

Set legend title and title style.

Parameters:
titlestr

The legend title.

propfont_manager.FontProperties or str or pathlib.Path

The font properties of the legend title. If a str, it is interpreted as a fontconfig pattern parsed by FontProperties. If a pathlib.Path, it is interpreted as the absolute path to a font file.

classmethod update_default_handler_map(handler_map)[source]#

Update the global default handler map, shared by all legends.

zorder = 5#