matplotlib.legend#

The legend module defines the Legend class, which is responsible fordrawing 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 thelegendfunction. For more details on legends there is also alegend guide.

TheLegend 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 aredefined in thelegend_handler module. While not all artisttypes are covered by the default legend handlers, custom legend handlers can bedefined to support arbitrary objects.

See the :ref`<legend_guide>` for moreinformation.

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

Bases:DraggableOffsetBox

Wrapper around aLegend to support mouse dragging.

Parameters:
legendLegend

TheLegend instance to wrap.

use_blitbool, optional

Use blitting for faster image composition. For details seeFuncAnimation.

update{'loc', 'bbox'}, optional

If "loc", update theloc parameter of the legend upon finalizing.If "bbox", update thebbox_to_anchor parameter.

finalize_offset()[source]#
classmatplotlib.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 orFigure

The artist that contains the legend.

handleslist of (Artist or tuple ofArtist)

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 handlesand labels should be the same. If they are not, they are truncatedto the length of the shorter list.

Attributes:
legend_handles

List ofArtist objects added as legend entries.

Added in version 3.7.

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'upperleft','upperright','lowerleft','lowerright' place the legend at the corresponding corner of theaxes/figure.

The strings'uppercenter','lowercenter','centerleft','centerright' place the legend at the center of the corresponding edgeof 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 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/figure 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

If a figure is using the constrained layout manager, the string codesof theloc keyword argument can get better layout behaviour using theprefix 'outside'. There is ambiguity at the corners, so 'outsideupper right' will make space for the legend above the rest of theaxes in the layout, and 'outside right upper' will make space on theright side of the layout. In addition to the values ofloclisted above, we have 'outside right upper', 'outside right lower','outside left upper', and 'outside left lower'. SeeLegend guide for more details.

bbox_to_anchorBboxBase, 2-tuple, or 4-tuple of floats

Box that is used to position the legend in conjunction withloc.Defaults toaxes.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 whichlegend is called.

If a 4-tuple orBboxBase 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 orFontProperties or dict

The font properties of the legend. If None (default), the currentmatplotlib.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 usingrcParams["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 aLine2D (line).

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

The number of marker points in the legend when creatinga legend entry for aPathCollection (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 theFancyBboxPatch 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 usingPatch 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 isNone, 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 orTransform

The transform for the bounding box (bbox_to_anchor). For a valueofNone (default) the Axes'matplotlib.axes.Axes.transAxes transform will be used.

titlestr or None

The legend's title. Default is no title (None).

title_fontpropertiesNone orFontProperties 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 currentrcParams["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 atmatplotlib.legend.Legend.get_legend_handler_map.

draggablebool, default: False

Whether the legend can be dragged with the mouse.

codes={'best':0,'center':10,'centerleft':6,'centerright':7,'lowercenter':8,'lowerleft':3,'lowerright':4,'right':5,'uppercenter':9,'upperleft':2,'upperright':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 theindividual 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_visiblereturns 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 childArtists of thisArtist.

classmethodget_default_handler_map()[source]#

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

get_draggable()[source]#

ReturnTrue if the legend is draggable,False otherwise.

get_frame()[source]#

Return theRectangle used to frame the legend.

get_frame_on()[source]#

Get whether the legend box patch is drawn.

staticget_legend_handler(legend_handler_map,orig_handle)[source]#

Return a legend handler fromlegend_handler_map thatcorresponds toorig_handler.

legend_handler_map should be a dictionary object (that isreturned by the get_legend_handler_map method).

It first checks if theorig_handle itself is a key in thelegend_handler_map and return the associated value.Otherwise, it checks for each of the classes in itsmethod-resolution-order. If no matching key is found, itreturnsNone.

get_legend_handler_map()[source]#

Return this legend instance's handler map.

get_lines()[source]#

Return the list ofLine2Ds in the legend.

get_patches()[source]#

Return the list ofPatchs in the legend.

get_texts()[source]#

Return the list ofTexts in the legend.

get_tightbbox(renderer=None)[source]#

LikeArtist.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 theText instance for the legend title.

get_window_extent(renderer=None)[source]#

Get the artist's bounding box in display space.

The bounding box's width and height are non-negative.

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

Warning

The extent can change due to any changes in the transform stack, suchas changing the Axes limits, the figure size, the canvas used (as isdone when saving a figure), or the DPI.

Relying on a once-retrieved window extent can lead to unexpectedbehavior in various cases such as interactive figures being resized ormoved to a screen with different dpi, or figures that look fine onscreen render incorrectly when saved to file.

To get accurate results you may need to manually callmatplotlib.figure.Figure.savefig ormatplotlib.figure.Figure.draw_without_rendering to have Matplotlibcompute the rendered size.

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

float 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 orSubFigure

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 ofAbstractPathEffect

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 alwayslined 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:

  • ABboxBase instance

  • A tuple of(left,bottom,width,height) in the giventransform (normalized axes coordinate if None)

  • A tuple of(left,bottom) where the width and height will beassumed 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, thiswill use a transform to the bounding box of the parent.

classmethodset_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 seeFuncAnimation.

update{'loc', 'bbox'}, optional

The legend parameter to be changed when dragged:

  • 'loc': update theloc parameter of the legend

  • 'bbox': update thebbox_to_anchor parameter of the legend

Returns:
DraggableLegend orNone

Ifstate isTrue this returns theDraggableLegend helperinstance. Otherwise this returnsNone.

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.

Added 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'upperleft','upperright','lowerleft','lowerright' place the legend at the corresponding corner of theaxes/figure.

The strings'uppercenter','lowercenter','centerleft','centerright' place the legend at the center of the corresponding edgeof 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 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/figure 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

If a figure is using the constrained layout manager, the string codesof theloc keyword argument can get better layout behaviour using theprefix 'outside'. There is ambiguity at the corners, so 'outsideupper right' will make space for the legend above the rest of theaxes in the layout, and 'outside right upper' will make space on theright side of the layout. In addition to the values ofloclisted above, we have 'outside right upper', 'outside right lower','outside left upper', and 'outside left lower'. SeeLegend 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 orstr orpathlib.Path

The font properties of the legend title.If astr, it is interpreted as a fontconfig pattern parsed byFontProperties. If apathlib.Path, it is interpreted as theabsolute path to a font file.

classmethodupdate_default_handler_map(handler_map)[source]#

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

zorder=5#