You are reading an old version of the documentation (v2.2.0). For the latest version see https://matplotlib.org/stable/api/legend_api.html
Version 2.2.0
matplotlib
Fork me on GitHub

Table Of Contents

Related Topics

This Page

legend and legend_handler

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')

Bases: matplotlib.offsetbox.DraggableOffsetBox

Parameters:

update : string

If “loc”, update loc parameter of legend upon finalizing. If “bbox”, update bbox_to_anchor parameter.

artist_picker(legend, evt)
finalize_offset()
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, framealpha=None, edgecolor=None, facecolor=None, bbox_to_anchor=None, bbox_transform=None, frameon=None, handler_map=None)

Bases: matplotlib.artist.Artist

Place a legend on the axes at location loc.

Parameters:

parent : Axes or Figure

The artist that contains the legend.

handles : sequence of Artist

A list of Artists (lines, patches) to be added to the legend.

labels : sequence of strings

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:
 

loc : int or string or pair of floats, default: ‘upper right’

The location of the legend. Possible codes are:

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

Alternatively can be a 2-tuple giving x, y of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored).

bbox_to_anchor : BboxBase or pair of floats

Specify any arbitrary location for the legend in bbox_transform coordinates (default Axes coordinates).

For example, to put the legend’s upper right hand corner in the center of the axes the following keywords can be used:

loc='upper right', bbox_to_anchor=(0.5, 0.5)

ncol : integer

The number of columns that the legend has. Default is 1.

prop : None or matplotlib.font_manager.FontProperties or dict

The font properties of the legend. If None (default), the current matplotlib.rcParams will be used.

fontsize : int or float or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}

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

numpoints : None or int

The number of marker points in the legend when creating a legend entry for a Line2D (line). Default is None, which will take the value from rcParams["legend.numpoints"].

scatterpoints : None or int

The number of marker points in the legend when creating a legend entry for a PathCollection (scatter plot). Default is None, which will take the value from rcParams["legend.scatterpoints"].

scatteryoffsets : iterable 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].

markerscale : None or int or float

The relative size of legend markers compared with the originally drawn ones. Default is None, which will take the value from rcParams["legend.markerscale"].

markerfirst : bool

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.

frameon : None or bool

Control whether the legend should be drawn on a patch (frame). Default is None, which will take the value from rcParams["legend.frameon"].

fancybox : None or bool

Control whether round edges should be enabled around the FancyBboxPatch which makes up the legend’s background. Default is None, which will take the value from rcParams["legend.fancybox"].

shadow : None or bool

Control whether to draw a shadow behind the legend. Default is None, which will take the value from rcParams["legend.shadow"].

framealpha : None or float

Control the alpha transparency of the legend’s background. Default is None, which will take the value from rcParams["legend.framealpha"]. If shadow is activated and framealpha is None, the default value is ignored.

facecolor : None or “inherit” or a color spec

Control the legend’s background color. Default is None, which will take the value from rcParams["legend.facecolor"]. If "inherit", it will take rcParams["axes.facecolor"].

edgecolor : None or “inherit” or a color spec

Control the legend’s background patch edge color. Default is None, which will take the value from rcParams["legend.edgecolor"] If "inherit", it will take rcParams["axes.edgecolor"].

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_transform : None or matplotlib.transforms.Transform

The transform for the bounding box (bbox_to_anchor). For a value of None (default) the Axes’ transAxes transform will be used.

title : str or None

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

borderpad : float or None

The fractional whitespace inside the legend border. Measured in font-size units. Default is None, which will take the value from rcParams["legend.borderpad"].

labelspacing : float or None

The vertical space between the legend entries. Measured in font-size units. Default is None, which will take the value from rcParams["legend.labelspacing"].

handlelength : float or None

The length of the legend handles. Measured in font-size units. Default is None, which will take the value from rcParams["legend.handlelength"].

handletextpad : float or None

The pad between the legend handle and text. Measured in font-size units. Default is None, which will take the value from rcParams["legend.handletextpad"].

borderaxespad : float or None

The pad between the axes and legend border. Measured in font-size units. Default is None, which will take the value from rcParams["legend.borderaxespad"].

columnspacing : float or None

The spacing between columns. Measured in font-size units. Default is None, which will take the value from rcParams["legend.columnspacing"].

handler_map : dict 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().

Notes

Users can specify any arbitrary location for the legend using the bbox_to_anchor keyword argument. bbox_to_anchor can be an instance of BboxBase(or its derivatives) or a tuple of 2 or 4 floats. See set_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(event)

Test whether the artist contains the mouse event.

Returns the truth value and a dictionary of artist specific details of selection, such as which points are contained in the pick radius. See individual artists for details.

draggable(state=None, use_blit=False, update='loc')

Set the draggable state – if state is

  • None : toggle the current state
  • True : turn draggable on
  • False : turn draggable off

If draggable is on, you can drag the legend on the canvas with the mouse. The DraggableLegend helper instance is returned if draggable is on.

The update parameter control which parameter of the legend changes when dragged. If update is “loc”, the loc parameter of the legend is changed. If “bbox”, the bbox_to_anchor parameter is changed.

draw(renderer)

Draw everything that belongs to the legend.

draw_frame(b)

Set draw frame to b.

Parameters:b : bool
get_bbox_to_anchor()

Return the bbox that the legend will be anchored to.

get_children()

Return a list of child artists.

classmethod get_default_handler_map()

A class method that returns the default handler map.

get_frame()

Return the Rectangle instances used to frame the legend.

get_frame_on()

Get whether the legend box patch is drawn.

static get_legend_handler(orig_handle)

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_hanler_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()

Return the handler map.

get_lines()

Return a list of Line2D instances in the legend.

get_patches()

Return a list of Patch instances in the legend.

get_texts()

Return a list of Text instances in the legend.

get_title()

Return the Text instance for the legend title.

get_window_extent(*args, **kwargs)

Return extent of the legend.

set_bbox_to_anchor(bbox, transform=None)

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.
classmethod set_default_handler_map(handler_map)

A class method to set the default handler map.

set_frame_on(b)

Set whether the legend box patch is drawn.

Parameters:

b : bool

set_title(title, prop=None)

Set the legend title. Fontproperties can be optionally set with prop parameter.

classmethod update_default_handler_map(handler_map)

A class method to update the default handler map.

zorder = 5

matplotlib.legend_handler

This module defines default legend handlers.

It is strongly encouraged to have read the legend guide before this documentation.

Legend handlers are expected to be a callable object with a following signature.

legend_handler(legend, orig_handle, fontsize, handlebox)

Where legend is the legend itself, orig_handle is the original plot, fontsize is the fontsize in pixels, and handlebox is a OffsetBox instance. Within the call, you should create relevant artists (using relevant properties from the legend and/or orig_handle) and add them into the handlebox. The artists needs to be scaled according to the fontsize (note that the size is in pixel, i.e., this is dpi-scaled value).

This module includes definition of several legend handler classes derived from the base class (HandlerBase) with the following method:

def legend_artist(self, legend, orig_handle, fontsize, handlebox):
class matplotlib.legend_handler.HandlerBase(xpad=0.0, ypad=0.0, update_func=None)

A Base class for default legend handlers.

The derived classes are meant to override create_artists method, which has a following signature.:

def create_artists(self, legend, orig_handle,
                   xdescent, ydescent, width, height, fontsize,
                   trans):

The overridden method needs to create artists of the given transform that fits in the given dimension (xdescent, ydescent, width, height) that are scaled by fontsize if necessary.

adjust_drawing_area(legend, orig_handle, xdescent, ydescent, width, height, fontsize)
create_artists(legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans)
legend_artist(legend, orig_handle, fontsize, handlebox)

Return the artist that this HandlerBase generates for the given original artist/handle.

Parameters:

legend : matplotlib.legend.Legend instance

The legend for which these legend artists are being created.

orig_handle : matplotlib.artist.Artist or similar

The object for which these legend artists are being created.

fontsize : float or int

The fontsize in pixels. The artists being created should be scaled according to the given fontsize.

handlebox : matplotlib.offsetbox.OffsetBox instance

The box which has been created to hold this legend entry’s artists. Artists created in the legend_artist method must be added to this handlebox inside this method.

update_prop(legend_handle, orig_handle, legend)
class matplotlib.legend_handler.HandlerCircleCollection(yoffsets=None, sizes=None, **kw)

Handler for CircleCollections.

create_collection(orig_handle, sizes, offsets, transOffset)
class matplotlib.legend_handler.HandlerErrorbar(xerr_size=0.5, yerr_size=None, marker_pad=0.3, numpoints=None, **kw)

Handler for Errorbars.

create_artists(legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans)
get_err_size(legend, xdescent, ydescent, width, height, fontsize)
class matplotlib.legend_handler.HandlerLine2D(marker_pad=0.3, numpoints=None, **kw)

Handler for Line2D instances.

Parameters:

marker_pad : float

Padding between points in legend entry.

numpoints : int

Number of points to show in legend entry.

Notes

Any other keyword arguments are given to HandlerNpoints.

create_artists(legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans)
class matplotlib.legend_handler.HandlerLineCollection(marker_pad=0.3, numpoints=None, **kw)

Handler for LineCollection instances.

Parameters:

marker_pad : float

Padding between points in legend entry.

numpoints : int

Number of points to show in legend entry.

Notes

Any other keyword arguments are given to HandlerNpoints.

create_artists(legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans)
get_numpoints(legend)
class matplotlib.legend_handler.HandlerNpoints(marker_pad=0.3, numpoints=None, **kw)

A legend handler that shows numpoints points in the legend entry.

Parameters:

marker_pad : float

Padding between points in legend entry.

numpoints : int

Number of points to show in legend entry.

Notes

Any other keyword arguments are given to HandlerBase.

get_numpoints(legend)
get_xdata(legend, xdescent, ydescent, width, height, fontsize)
class matplotlib.legend_handler.HandlerNpointsYoffsets(numpoints=None, yoffsets=None, **kw)

A legend handler that shows numpoints in the legend, and allows them to be individually offest in the y-direction.

Parameters:

numpoints : int

Number of points to show in legend entry.

yoffsets : array of floats

Length numpoints list of y offsets for each point in legend entry.

Notes

Any other keyword arguments are given to HandlerNpoints.

get_ydata(legend, xdescent, ydescent, width, height, fontsize)
class matplotlib.legend_handler.HandlerPatch(patch_func=None, **kw)

Handler for Patch instances.

Parameters:

patch_func : callable, optional

The function that creates the legend key artist. patch_func should have the signature:

def patch_func(legend=legend, orig_handle=orig_handle,
               xdescent=xdescent, ydescent=ydescent,
               width=width, height=height, fontsize=fontsize)

Subsequently the created artist will have its update_prop method called and the appropriate transform will be applied.

Notes

Any other keyword arguments are given to HandlerBase.

create_artists(legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans)
class matplotlib.legend_handler.HandlerPathCollection(yoffsets=None, sizes=None, **kw)

Handler for PathCollections, which are used by scatter.

create_collection(orig_handle, sizes, offsets, transOffset)
class matplotlib.legend_handler.HandlerPolyCollection(xpad=0.0, ypad=0.0, update_func=None)

Handler for PolyCollection used in fill_between and stackplot.

create_artists(legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans)
class matplotlib.legend_handler.HandlerRegularPolyCollection(yoffsets=None, sizes=None, **kw)

Handler for RegularPolyCollections.

create_artists(legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans)
create_collection(orig_handle, sizes, offsets, transOffset)
get_numpoints(legend)
get_sizes(legend, orig_handle, xdescent, ydescent, width, height, fontsize)
update_prop(legend_handle, orig_handle, legend)
class matplotlib.legend_handler.HandlerStem(marker_pad=0.3, numpoints=None, bottom=None, yoffsets=None, **kw)

Handler for plots produced by stem.

Parameters:

marker_pad : float

Padding between points in legend entry. Default is 0.3.

numpoints : int, optional

Number of points to show in legend entry.

bottom : float, optional

yoffsets : array of floats, optional

Length numpoints list of y offsets for each point in legend entry.

Notes

Any other keyword arguments are given to HandlerNpointsYoffsets.

create_artists(legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans)
get_ydata(legend, xdescent, ydescent, width, height, fontsize)
class matplotlib.legend_handler.HandlerTuple(ndivide=1, pad=None, **kwargs)

Handler for Tuple.

Additional kwargs are passed through to HandlerBase.

Parameters:

ndivide : int, optional

The number of sections to divide the legend area into. If None, use the length of the input tuple. Default is 1.

pad : float, optional

If None, fall back to legend.borderpad as the default. In units of fraction of font size. Default is None.

create_artists(legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans)
matplotlib.legend_handler.update_from_first_child(tgt, src)