egttools.plotting.barplots.Legend

class 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, linewidth=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:
  • parent (Axes | Figure) – The artist that contains the legend.

  • handles (Iterable[Artist | tuple[Artist, ...]]) – A list of Artists (lines, patches) to be added to the legend.

  • labels (Iterable[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.

  • loc (Union[Literal['upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center', 'best', 'outside upper left', 'outside upper center', 'outside upper right', 'outside right upper', 'outside right center', 'outside right lower', 'outside lower right', 'outside lower center', 'outside lower left', 'outside left lower', 'outside left center', 'outside left upper'], tuple[float, float], int, None]) –

    The location of the legend.

    The string locations place the legend at the corresponding position within the bounding box, which by default is the full axes/figure area. The bounding box can be changed via bbox_to_anchor.

    The positions are visualized below:

    +--------------+--------------+---------------+
    | 'upper left' |'upper center'| 'upper right' |
    +--------------+--------------+---------------+
    |'center left' |   'center'   |'center right' |
    +--------------+--------------+---------------+
    | 'lower left' |'lower center'| 'lower right' |
    +--------------+--------------+---------------+
    

    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 currently takes into account most, but not all, artists added to the Axes via plotting functions. In particular it does not consider inset axes, titles, or axis labels.

    The computation of the best position can be expensive for plots with large amounts of data. If speed becomes a concern, you may 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_anchor (BboxBase | tuple[float, float] | tuple[float, float, float, float] | None) –

    Box that is used to position the legend in conjunction with loc. This is an advanced option for free placement of the legend. For most use cases, loc alone is sufficient.

    Defaults to axes.bbox (if called as a method to .Axes.legend) or figure.bbox (if figure.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)
    

    For more details on legend positioning, see the legend_guide.

  • ncols (int) –

    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.

  • prop (FontProperties | dict[str, Any] | None) – The font properties of the legend. If None (default), the current matplotlib.rcParams will be used.

  • fontsize (float | str | None) – 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.

  • labelcolor (Union[tuple[float, float, float], str, tuple[float, float, float, float], tuple[tuple[float, float, float] | str, float], tuple[tuple[float, float, float, float], float], Iterable[tuple[float, float, float] | str | tuple[float, float, float, float] | tuple[tuple[float, float, float] | str, float] | tuple[tuple[float, float, float, float], float]], Literal['linecolor', 'markerfacecolor', 'mfc', 'markeredgecolor', 'mec'], 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 :rc:`legend.labelcolor`. If None, use :rc:`text.color`.

  • numpoints (int | None) – The number of marker points in the legend when creating a legend entry for a .Line2D (line).

  • scatterpoints (int | None) – The number of marker points in the legend when creating a legend entry for a .PathCollection (scatter plot).

  • scatteryoffsets (Iterable[float] | None) – 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].

  • markerscale (float | None) – The relative size of legend markers compared to the originally drawn ones.

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

  • reverse (bool) –

    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.

    Added in version 3.7.

  • frameon (bool | None) – Whether the legend should be drawn on a patch (frame).

  • fancybox (bool | None) – Whether round edges should be enabled around the .FancyBboxPatch which makes up the legend’s background.

  • shadow (bool | dict[str, Any] | None) – Whether to draw a shadow behind the legend. The shadow can be configured using .Patch keywords. Customization via :rc:`legend.shadow` is currently not supported.

  • framealpha (float | None) – The alpha transparency of the legend’s background. If shadow is activated and framealpha is None, the default value is ignored.

  • facecolor (Union[Literal['inherit'], tuple[float, float, float], str, tuple[float, float, float, float], tuple[tuple[float, float, float] | str, float], tuple[tuple[float, float, float, float], float], None]) – The legend’s background color. If "inherit", use :rc:`axes.facecolor`.

  • edgecolor (Union[Literal['inherit'], tuple[float, float, float], str, tuple[float, float, float, float], tuple[tuple[float, float, float] | str, float], tuple[tuple[float, float, float, float], float], None]) – The legend’s background patch edge color. If "inherit", use :rc:`axes.edgecolor`.

  • linewidth (float | None) –

    The legend’s background patch edge linewidth. If None, use :rc:`patch.linewidth`.

    Added in version 3.11.

  • mode (Optional[Literal['expand']]) – 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 (Transform | None) – The transform for the bounding box (bbox_to_anchor). For a value of None (default) the Axes’ matplotlib.axes.Axes.transAxes transform will be used.

  • title (str | None) – The legend’s title. Default is no title (None).

  • title_fontproperties (FontProperties | dict[str, Any] | None) – 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 :rc:`legend.title_fontsize` will be used.

  • title_fontsize (float | 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 (Literal['center', 'left', 'right']) – 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.

  • borderpad (float | None) – The fractional whitespace inside the legend border, in font-size units.

  • labelspacing (float | None) – The vertical space between the legend entries, in font-size units.

  • handlelength (float | None) – The length of the legend handles, in font-size units.

  • handleheight (float | None) – The height of the legend handles, in font-size units.

  • handletextpad (float | None) – The pad between the legend handle and text, in font-size units.

  • borderaxespad (float | None) – The pad between the Axes and legend border, in font-size units.

  • columnspacing (float | None) – The spacing between columns, in font-size units.

  • handler_map (dict[Artist | type, HandlerBase] | 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.

  • draggable (bool) – Whether the legend can be dragged with the mouse.

legend_handles

List of .Artist objects added as legend entries.

Added in version 3.7.

Methods

add_callback

Add a callback function that will be called whenever one of the .Artist's properties changes.

contains

Test whether the artist contains the mouse event.

convert_xunits

Convert x using the unit type of the xaxis.

convert_yunits

Convert y using the unit type of the yaxis.

draw

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

draw_frame

Set whether the legend box patch is drawn.

findobj

Find artist objects.

format_cursor_data

Return a string representation of data.

get_agg_filter

Return filter function to be used for agg filter.

get_alignment

Get the alignment value of the legend box

get_alpha

Return the alpha value used for blending - not supported on all backends.

get_animated

Return whether the artist is animated.

get_bbox_to_anchor

Return the bbox that the legend will be anchored to.

get_children

Return a list of the child .Artists of this .Artist.

get_clip_box

Return the clipbox.

get_clip_on

Return whether the artist uses clipping.

get_clip_path

Return the clip path.

get_cursor_data

Return the cursor data for a given event.

get_default_handler_map

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

get_draggable

Return True if the legend is draggable, False otherwise.

get_figure

Return the .Figure or .SubFigure instance the artist belongs to.

get_frame

Return the ~.patches.Rectangle used to frame the legend.

get_frame_on

Get whether the legend box patch is drawn.

get_gid

Return the group id.

get_in_layout

Return boolean flag, True if artist is included in layout calculations.

get_label

Return the label used for this artist in the legend.

get_legend_handler

Return a legend handler from legend_handler_map that corresponds to orig_handler.

get_legend_handler_map

Return this legend instance's handler map.

get_lines

Return the list of ~.lines.Line2Ds in the legend.

get_mouseover

Return whether this artist is queried for custom context information when the mouse cursor moves over it.

get_patches

Return the list of ~.patches.Patchs in the legend.

get_path_effects

get_picker

Return the picking behavior of the artist.

get_rasterized

Return whether the artist is to be rasterized.

get_sketch_params

Return the sketch parameters for the artist.

get_snap

Return the snap setting.

get_texts

Return the list of ~.text.Texts in the legend.

get_tightbbox

Get the artist's bounding box in display space, taking clipping into account.

get_title

Return the .Text instance for the legend title.

get_transform

Return the .Transform instance used by this artist.

get_transformed_clip_path_and_affine

Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.

get_url

Return the url.

get_visible

Return the visibility.

get_window_extent

Get the artist's bounding box in display space, ignoring clipping.

get_zorder

Return the artist's zorder.

have_units

Return whether units are set on any axis.

is_transform_set

Return whether the Artist has an explicitly set transform.

pchanged

Call all of the registered callbacks.

pick

Process a pick event.

pickable

Return whether the artist is pickable.

properties

Return a dictionary of all the properties of the artist.

remove

Remove the artist from the figure if possible.

remove_callback

Remove a callback based on its observer id.

set

Set multiple properties at once.

set_agg_filter

Set the agg filter.

set_alignment

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

set_alpha

Set the alpha value used for blending - not supported on all backends.

set_animated

Set whether the artist is intended to be used in an animation.

set_bbox_to_anchor

Set the bbox that the legend will be anchored to.

set_clip_box

Set the artist's clip .Bbox.

set_clip_on

Set whether the artist uses clipping.

set_clip_path

Set the artist's clip path.

set_default_handler_map

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

set_draggable

Enable or disable mouse dragging support of the legend.

set_figure

Set the .Figure or .SubFigure instance the artist belongs to.

set_frame_on

Set whether the legend box patch is drawn.

set_gid

Set the (group) id for the artist.

set_in_layout

Set if artist is to be included in layout calculations, E.g.

set_label

Set a label that will be displayed in the legend.

set_loc

Set the location of the legend.

set_mouseover

Set whether this artist is queried for custom context information when the mouse cursor moves over it.

set_ncols

Set the number of columns.

set_path_effects

Set the path effects.

set_picker

Define the picking behavior of the artist.

set_rasterized

Force rasterized (bitmap) drawing for vector graphics output.

set_sketch_params

Set the sketch parameters.

set_snap

Set the snapping behavior.

set_title

Set legend title and title style.

set_transform

Set the artist transform.

set_url

Set the url for the artist.

set_visible

Set the artist's visibility.

set_zorder

Set the zorder for the artist.

update

[Discouraged] Update this artist's properties from the dictionary props.

update_default_handler_map

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

update_from

Copy properties from other to self.

Attributes

axes

The ~.axes.Axes instance the artist resides in, or None.

codes

figure

The (Sub)Figure that the artist is on.

mouseover

Return whether this artist is queried for custom context information when the mouse cursor moves over it.

stale

Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.

sticky_edges

x and y sticky edge lists for autoscaling.

zorder

classmethod __init_subclass__()

This method is called when a class is subclassed.

The default implementation does nothing. It may be overridden to extend subclasses.

classmethod get_default_handler_map()[source]

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

Return type:

dict[type, HandlerBase]

classmethod set_default_handler_map(handler_map)[source]

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

Return type:

None

classmethod update_default_handler_map(handler_map)[source]

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

Return type:

None

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.

Return type:

HandlerBase | None

__init__(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, linewidth=None, bbox_to_anchor=None, bbox_transform=None, frameon=None, handler_map=None, title_fontproperties=None, alignment='center', ncol=1, draggable=False)[source]
Parameters:
  • parent (Axes | Figure) – The artist that contains the legend.

  • handles (Iterable[Artist | tuple[Artist, ...]]) – A list of Artists (lines, patches) to be added to the legend.

  • labels (Iterable[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.

  • loc (Union[Literal['upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center', 'best', 'outside upper left', 'outside upper center', 'outside upper right', 'outside right upper', 'outside right center', 'outside right lower', 'outside lower right', 'outside lower center', 'outside lower left', 'outside left lower', 'outside left center', 'outside left upper'], tuple[float, float], int, None]) –

    The location of the legend.

    The string locations place the legend at the corresponding position within the bounding box, which by default is the full axes/figure area. The bounding box can be changed via bbox_to_anchor.

    The positions are visualized below:

    +--------------+--------------+---------------+
    | 'upper left' |'upper center'| 'upper right' |
    +--------------+--------------+---------------+
    |'center left' |   'center'   |'center right' |
    +--------------+--------------+---------------+
    | 'lower left' |'lower center'| 'lower right' |
    +--------------+--------------+---------------+
    

    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 currently takes into account most, but not all, artists added to the Axes via plotting functions. In particular it does not consider inset axes, titles, or axis labels.

    The computation of the best position can be expensive for plots with large amounts of data. If speed becomes a concern, you may 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_anchor (BboxBase | tuple[float, float] | tuple[float, float, float, float] | None) –

    Box that is used to position the legend in conjunction with loc. This is an advanced option for free placement of the legend. For most use cases, loc alone is sufficient.

    Defaults to axes.bbox (if called as a method to .Axes.legend) or figure.bbox (if figure.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)
    

    For more details on legend positioning, see the legend_guide.

  • ncols (int) –

    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.

  • prop (FontProperties | dict[str, Any] | None) – The font properties of the legend. If None (default), the current matplotlib.rcParams will be used.

  • fontsize (float | str | None) – 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.

  • labelcolor (Union[tuple[float, float, float], str, tuple[float, float, float, float], tuple[tuple[float, float, float] | str, float], tuple[tuple[float, float, float, float], float], Iterable[tuple[float, float, float] | str | tuple[float, float, float, float] | tuple[tuple[float, float, float] | str, float] | tuple[tuple[float, float, float, float], float]], Literal['linecolor', 'markerfacecolor', 'mfc', 'markeredgecolor', 'mec'], 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 :rc:`legend.labelcolor`. If None, use :rc:`text.color`.

  • numpoints (int | None) – The number of marker points in the legend when creating a legend entry for a .Line2D (line).

  • scatterpoints (int | None) – The number of marker points in the legend when creating a legend entry for a .PathCollection (scatter plot).

  • scatteryoffsets (Iterable[float] | None) – 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].

  • markerscale (float | None) – The relative size of legend markers compared to the originally drawn ones.

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

  • reverse (bool) –

    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.

    Added in version 3.7.

  • frameon (bool | None) – Whether the legend should be drawn on a patch (frame).

  • fancybox (bool | None) – Whether round edges should be enabled around the .FancyBboxPatch which makes up the legend’s background.

  • shadow (bool | dict[str, Any] | None) – Whether to draw a shadow behind the legend. The shadow can be configured using .Patch keywords. Customization via :rc:`legend.shadow` is currently not supported.

  • framealpha (float | None) – The alpha transparency of the legend’s background. If shadow is activated and framealpha is None, the default value is ignored.

  • facecolor (Union[Literal['inherit'], tuple[float, float, float], str, tuple[float, float, float, float], tuple[tuple[float, float, float] | str, float], tuple[tuple[float, float, float, float], float], None]) – The legend’s background color. If "inherit", use :rc:`axes.facecolor`.

  • edgecolor (Union[Literal['inherit'], tuple[float, float, float], str, tuple[float, float, float, float], tuple[tuple[float, float, float] | str, float], tuple[tuple[float, float, float, float], float], None]) – The legend’s background patch edge color. If "inherit", use :rc:`axes.edgecolor`.

  • linewidth (float | None) –

    The legend’s background patch edge linewidth. If None, use :rc:`patch.linewidth`.

    Added in version 3.11.

  • mode (Optional[Literal['expand']]) – 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 (Transform | None) – The transform for the bounding box (bbox_to_anchor). For a value of None (default) the Axes’ matplotlib.axes.Axes.transAxes transform will be used.

  • title (str | None) – The legend’s title. Default is no title (None).

  • title_fontproperties (FontProperties | dict[str, Any] | None) – 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 :rc:`legend.title_fontsize` will be used.

  • title_fontsize (float | 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 (Literal['center', 'left', 'right']) – 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.

  • borderpad (float | None) – The fractional whitespace inside the legend border, in font-size units.

  • labelspacing (float | None) – The vertical space between the legend entries, in font-size units.

  • handlelength (float | None) – The length of the legend handles, in font-size units.

  • handleheight (float | None) – The height of the legend handles, in font-size units.

  • handletextpad (float | None) – The pad between the legend handle and text, in font-size units.

  • borderaxespad (float | None) – The pad between the Axes and legend border, in font-size units.

  • columnspacing (float | None) – The spacing between columns, in font-size units.

  • handler_map (dict[Artist | type, HandlerBase] | 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.

  • draggable (bool) – Whether the legend can be dragged with the mouse.

legend_handles

List of .Artist objects added as legend entries.

Added in version 3.7.

__str__()[source]

Return str(self).

add_callback(func)

Add a callback function that will be called whenever one of the .Artist’s properties changes.

Parameters:

func (Callable[[Artist], Any]) –

The callback function. It must have the signature:

def func(artist: Artist) -> Any

where artist is the calling .Artist. Return values may exist but are ignored.

Returns:

The observer id associated with the callback. This id can be used for removing the callback with .remove_callback later.

Return type:

int

See also

remove_callback

contains(mouseevent)[source]

Test whether the artist contains the mouse event.

Parameters:

mouseevent (MouseEvent)

Return type:

tuple[bool, dict[Any, Any]]

Returns:

  • contains (bool) – Whether any values are within the radius.

  • details (dict) – 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.

convert_xunits(x)

Convert x using the unit type of the xaxis.

If the artist is not contained in an Axes or if the xaxis does not have units, x itself is returned.

convert_yunits(y)

Convert y using the unit type of the yaxis.

If the artist is not contained in an Axes or if the yaxis does not have units, y itself is returned.

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:

renderer (~matplotlib.backend_bases.RendererBase subclass.)

Notes

This method is overridden in the Artist subclasses.

draw_frame(b)

Set whether the legend box patch is drawn.

Parameters:

b (bool)

Return type:

None

findobj(match=None, include_self=True)

Find artist objects.

Recursively find all .Artist instances contained in the artist.

Parameters:
  • match (None | Callable[[Artist], bool] | type[_T_Artist]) –

    A filter criterion for the matches. This can be

    • None: Return all objects contained in artist.

    • A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True.

    • A class instance: e.g., .Line2D. The result will only contain artists of this class or its subclasses (isinstance check).

  • include_self (bool) – Include self in the list to be checked for a match.

Return type:

list[Artist] | list[_T_Artist]

format_cursor_data(data)

Return a string representation of data.

Note

This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself.

The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar’s formatter.

See also

get_cursor_data

Return type:

str

get_agg_filter()

Return filter function to be used for agg filter.

Return type:

Callable[[ArrayLike, float], tuple[ndarray, float, float]] | None

get_alignment()[source]

Get the alignment value of the legend box

Return type:

Literal['center', 'left', 'right']

get_alpha()

Return the alpha value used for blending - not supported on all backends.

Return type:

float | None

get_animated()

Return whether the artist is animated.

Return type:

bool

get_bbox_to_anchor()[source]

Return the bbox that the legend will be anchored to.

Return type:

BboxBase

get_children()[source]

Return a list of the child .Artists of this .Artist.

Return type:

list[Artist]

get_clip_box()

Return the clipbox.

Return type:

Bbox | None

get_clip_on()

Return whether the artist uses clipping.

Return type:

bool

get_clip_path()

Return the clip path.

Return type:

Patch | Path | TransformedPath | TransformedPatchPath | None

get_cursor_data(event)

Return the cursor data for a given event.

Note

This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself.

Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None.

Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that .format_cursor_data can convert the data to a string representation.

The only current use case is displaying the z-value of an .AxesImage in the status bar of a plot window, while moving the mouse.

Parameters:

event (MouseEvent)

Return type:

Any

get_draggable()[source]

Return True if the legend is draggable, False otherwise.

Return type:

bool

get_figure(root=False)

Return the .Figure or .SubFigure instance the artist belongs to.

Parameters:

root (Union[Literal[True], Literal[False], bool]) – If False, return the (Sub)Figure this artist is on. If True, return the root Figure for a nested tree of SubFigures.

Return type:

Figure | None | SubFigure

get_frame()[source]

Return the ~.patches.Rectangle used to frame the legend.

Return type:

Rectangle

get_frame_on()[source]

Get whether the legend box patch is drawn.

Return type:

bool

get_gid()

Return the group id.

Return type:

str | None

get_in_layout()

Return boolean flag, True if artist is included in layout calculations.

E.g. constrainedlayout_guide, .Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').

Return type:

bool

get_label()

Return the label used for this artist in the legend.

Return type:

object

get_legend_handler_map()[source]

Return this legend instance’s handler map.

Return type:

dict[type, HandlerBase]

get_lines()[source]

Return the list of ~.lines.Line2Ds in the legend.

Return type:

list[Line2D]

get_mouseover()

Return whether this artist is queried for custom context information when the mouse cursor moves over it.

Return type:

bool

get_patches()[source]

Return the list of ~.patches.Patchs in the legend.

Return type:

list[Patch]

get_path_effects()
Return type:

list[AbstractPathEffect]

get_picker()

Return the picking behavior of the artist.

The possible values are described in .Artist.set_picker.

See also

Artist.set_picker, Artist.pickable, Artist.pick

Return type:

None | bool | float | Callable[[Artist, MouseEvent], tuple[bool, dict[Any, Any]]]

get_rasterized()

Return whether the artist is to be rasterized.

Return type:

bool

get_sketch_params()

Return the sketch parameters for the artist.

Returns:

A 3-tuple with the following elements:

  • scale: The amplitude of the wiggle perpendicular to the source line.

  • length: The length of the wiggle along the line.

  • randomness: The scale factor by which the length is shrunken or expanded.

Returns None if no sketch parameters were set.

Return type:

tuple[float, float, float] | None

get_snap()

Return the snap setting.

See .set_snap for details.

Return type:

bool | None

get_texts()[source]

Return the list of ~.text.Texts in the legend.

Return type:

list[Text]

get_tightbbox(renderer=None)[source]

Get the artist’s bounding box in display space, taking clipping into account.

Parameters:

renderer (~matplotlib.backend_bases.RendererBase, optional) – Renderer used to draw the figure (i.e. fig.canvas.get_renderer()).

Returns:

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

Return type:

.Bbox or None

See also

Artist.get_window_extent

Get the artist bounding box, ignoring clipping.

get_title()[source]

Return the .Text instance for the legend title.

Return type:

Text

get_transform()

Return the .Transform instance used by this artist.

Return type:

Transform

get_transformed_clip_path_and_affine()

Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.

Return type:

tuple[None, None] | tuple[Path, Transform]

get_url()

Return the url.

Return type:

str | None

get_visible()

Return the visibility.

Return type:

bool

get_window_extent(renderer=None)[source]

Get the artist’s bounding box in display space, ignoring clipping.

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 bounding box at 0, 0.

Warning

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

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

To get accurate results you may need to manually call ~.Figure.savefig or ~.Figure.draw_without_rendering to have Matplotlib compute the rendered size.

Parameters:

renderer (~matplotlib.backend_bases.RendererBase, optional) – Renderer used to draw the figure (i.e. fig.canvas.get_renderer()).

See also

Artist.get_tightbbox

Get the artist bounding box, taking clipping into account.

get_zorder()

Return the artist’s zorder.

Return type:

float

have_units()

Return whether units are set on any axis.

Return type:

bool

is_transform_set()

Return whether the Artist has an explicitly set transform.

This is True after .set_transform has been called.

Return type:

bool

pchanged()

Call all of the registered callbacks.

This function is triggered internally when a property is changed.

Return type:

None

pick(mouseevent)

Process a pick event.

Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set.

See also

Artist.set_picker, Artist.get_picker, Artist.pickable

Return type:

None

pickable()

Return whether the artist is pickable.

See also

Artist.set_picker, Artist.get_picker, Artist.pick

Return type:

bool

properties()

Return a dictionary of all the properties of the artist.

Return type:

dict[str, Any]

remove()

Remove the artist from the figure if possible.

The effect will not be visible until the figure is redrawn, e.g., with .FigureCanvasBase.draw_idle. Call ~.axes.Axes.relim to update the Axes limits if desired.

Note: there is no support for removing the artist’s legend entry.

Return type:

None

remove_callback(oid)

Remove a callback based on its observer id.

See also

add_callback

Return type:

None

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

Set multiple properties at once.

a.set(a=A, b=B, c=C)

is equivalent to

a.set_a(A)
a.set_b(B)
a.set_c(C)

In addition to the full property names, aliases are also supported, e.g. set(lw=2) is equivalent to set(linewidth=2), but it is an error to pass both simultaneously.

The order of the individual setter calls matches the order of parameters in set(). However, most properties do not depend on each other so that order is rarely relevant.

Supported properties are

Properties:

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: ~matplotlib.transforms.BboxBase or tuple clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None draggable: bool figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure frame_on: bool gid: str in_layout: bool label: object loc: str or pair of floats, default: :rc:`legend.loc` 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: ~matplotlib.transforms.Transform url: str visible: bool zorder: float

set_agg_filter(filter_func)

Set the agg filter.

Parameters:

filter_func (Callable[[ArrayLike, float], tuple[ndarray, float, float]] | None) –

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

Return type:

None

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 (Literal['center', 'left', 'right'])

Return type:

None

set_alpha(alpha)

Set the alpha value used for blending - not supported on all backends.

Parameters:

alpha (float | None) – alpha must be within the 0-1 range, inclusive.

Return type:

None

set_animated(b)

Set whether the artist is intended to be used in an animation.

If True, the artist is excluded from regular drawing of the figure. You have to call .Figure.draw_artist / .Axes.draw_artist explicitly on the artist. This approach is used to speed up animations using blitting.

See also matplotlib.animation and blitting.

Parameters:

b (bool)

Return type:

None

set_bbox_to_anchor(bbox, transform=None)[source]

Set the bbox that the legend will be anchored to.

Parameters:
  • bbox (BboxBase | tuple[float, float] | tuple[float, float, float, float] | None) –

    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.

  • transform (Transform | None) – A transform to apply to the bounding box. If not specified, this will use a transform to the bounding box of the parent.

Return type:

None

set_clip_box(clipbox)

Set the artist’s clip .Bbox.

Parameters:

clipbox (BboxBase | None) – Will typically be created from a .TransformedBbox. For instance, TransformedBbox(Bbox([[0, 0], [1, 1]]), ax.transAxes) is the default clipping for an artist added to an Axes.

Return type:

None

set_clip_on(b)

Set whether the artist uses clipping.

When False, artists will be visible outside the Axes which can lead to unexpected results.

Parameters:

b (bool)

Return type:

None

set_clip_path(path, transform=None)

Set the artist’s clip path.

Parameters:
  • path (Patch | Path | TransformedPath | TransformedPatchPath | None) – The clip path. If given a .Path, transform must be provided as well. If None, a previously set clip path is removed.

  • transform (Transform | None) – Only used if path is a .Path, in which case the given .Path is converted to a .TransformedPath using transform.

Return type:

None

Notes

For efficiency, if path is a .Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None.

For technical reasons (support of ~.Artist.set), a tuple (path, transform) is also accepted as a single positional parameter.

set_draggable(state, use_blit=False, update='loc')[source]

Enable or disable mouse dragging support of the legend.

Parameters:
  • state (Union[Literal[True], Literal[False]]) – Whether mouse dragging is enabled.

  • use_blit (bool) – Use blitting for faster image composition. For details see func-animation.

  • update (Literal['loc', 'bbox']) –

    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.

Return type:

DraggableLegend | None

set_figure(fig)

Set the .Figure or .SubFigure instance the artist belongs to.

Warning

This function should typically not be called by users.

This is a low-level API and only modifies the internal state of the Artist. Only modifying this is not enough and will typically lead to an inconsistent state, because the state of the figure has to be changed as well.

Users should typically instead call one of the high-level APIs, i.e. .Figure.add_artist or one of the Axes methods axes-api-adding-artists.

Parameters:

fig (Figure | SubFigure)

Return type:

None

set_frame_on(b)[source]

Set whether the legend box patch is drawn.

Parameters:

b (bool)

Return type:

None

set_gid(gid)

Set the (group) id for the artist.

Parameters:

gid (str | None)

Return type:

None

set_in_layout(in_layout)

Set if artist is to be included in layout calculations, E.g. constrainedlayout_guide, .Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').

Parameters:

in_layout (bool)

Return type:

None

set_label(s)

Set a label that will be displayed in the legend.

Parameters:

s (object) – s will be converted to a string by calling str.

Return type:

None

set_loc(loc=None)[source]

Set the location of the legend.

Added in version 3.8.

Parameters:

loc (Union[Literal['upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center', 'best', 'outside upper left', 'outside upper center', 'outside upper right', 'outside right upper', 'outside right center', 'outside right lower', 'outside lower right', 'outside lower center', 'outside lower left', 'outside left lower', 'outside left center', 'outside left upper'], tuple[float, float], int, None]) –

The location of the legend.

The string locations place the legend at the corresponding position within the bounding box, which by default is the full axes/figure area. The bounding box can be changed via bbox_to_anchor.

The positions are visualized below:

+--------------+--------------+---------------+
| 'upper left' |'upper center'| 'upper right' |
+--------------+--------------+---------------+
|'center left' |   'center'   |'center right' |
+--------------+--------------+---------------+
| 'lower left' |'lower center'| 'lower right' |
+--------------+--------------+---------------+

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 currently takes into account most, but not all, artists added to the Axes via plotting functions. In particular it does not consider inset axes, titles, or axis labels.

The computation of the best position can be expensive for plots with large amounts of data. If speed becomes a concern, you may 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.

Return type:

None

set_mouseover(mouseover)

Set whether this artist is queried for custom context information when the mouse cursor moves over it.

Parameters:

mouseover (bool)

Return type:

None

See also

get_cursor_data, ToolCursorPosition, NavigationToolbar2

set_ncols(ncols)[source]

Set the number of columns.

Return type:

None

set_path_effects(path_effects)

Set the path effects.

Parameters:

path_effects (list[AbstractPathEffect])

Return type:

None

set_picker(picker)

Define the picking behavior of the artist.

Parameters:

picker (None | bool | float | Callable[[Artist, MouseEvent], tuple[bool, dict[Any, Any]]]) –

This can be one of the following:

  • None: Picking is disabled for this artist (default).

  • A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist.

  • A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event

  • A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event:

    hit, props = picker(artist, mouseevent)
    

    to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.

Return type:

None

set_rasterized(rasterized)

Force rasterized (bitmap) drawing for vector graphics output.

Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued.

This setting is ignored for pixel-based output.

See also /gallery/misc/rasterization_demo.

Parameters:

rasterized (bool)

Return type:

None

set_sketch_params(scale=None, length=None, randomness=None)

Set the sketch parameters.

Parameters:
  • scale (float | None) – The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided.

  • length (float | None) – The length of the wiggle along the line, in pixels (default 128.0)

  • randomness (float | None) –

    The scale factor by which the length is shrunken or expanded (default 16.0)

    The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.

Return type:

None

set_snap(snap)

Set the snapping behavior.

Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line.

Snapping is currently only supported by the Agg and MacOSX backends.

Parameters:

snap (bool | None) –

Possible values:

  • True: Snap vertices to the nearest pixel center.

  • False: Do not modify vertex positions.

  • None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center.

Return type:

None

set_title(title, prop=None)[source]

Set legend title and title style.

Parameters:
  • title (str) – The legend title.

  • prop (FontProperties | str | Path | None) – 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.

Return type:

None

set_transform(t)

Set the artist transform.

Parameters:

t (Transform | None)

Return type:

None

set_url(url)

Set the url for the artist.

Parameters:

url (str | None)

Return type:

None

set_visible(b)

Set the artist’s visibility.

Parameters:

b (bool)

Return type:

None

set_zorder(level)

Set the zorder for the artist. Artists with lower zorder values are drawn first.

Parameters:

level (float)

Return type:

None

update(props)

[Discouraged] Update this artist’s properties from the dictionary props.

Discouraged

This method exists for historic reasons. Please use .Artist.set instead. artist.update(props) is nowadays almost identical to artist.set(**props) with the only difference that set will additionally check that a property is not specified multiple times through aliases.

Parameters:

props (dict[str, Any]) – Dictionary of properties (keys) and their new values.

Returns:

A list of return values from the configured setters.

Return type:

list[Any]

update_from(other)

Copy properties from other to self.

Return type:

None

__annotations__ = {}
property axes

The ~.axes.Axes instance the artist resides in, or None.

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}
property figure

The (Sub)Figure that the artist is on. For more control, use the get_figure method.

Setter accepts:

Figure | SubFigure

property mouseover

Return whether this artist is queried for custom context information when the mouse cursor moves over it.

property stale

Whether the artist is ‘stale’ and needs to be re-drawn for the output to match the internal state of the artist.

property sticky_edges

x and y sticky edge lists for autoscaling.

When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added–the view limit “sticks” to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram.

Moreover, margin expansion “bumps” against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1.

This attribute cannot be assigned to; however, the x and y lists can be modified in place as needed.

Examples

>>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
zorder = 5