原文地址:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html#matplotlib.pyplot.legend

matplotlib.pyplot.legend(*args**kwargs)[source]

在坐标轴axes放置一个图例legend.

调用示例:

legend()
legend(labels)
legend(handles, labels)

使用此方法的三种不同方式。

1.  自动检测要显示在图例中的元素

当不传递任何额外参数时,将自动确定要添加到图例中的元素.

假若这样, 标签labels取自artist. 您可以在artist创建或通过调用artist的 set_label() 方法指定它们:

line, = ax.plot([1, 2, 3], label='Inline label')
ax.legend()

或:

line.set_label('Label via method')
line, = ax.plot([1, 2, 3])
ax.legend()

通过定义以下划线开头的标签,可以将特定的行排除在自动图例元素选择之外 . 这是所有 artists的自动设置, 所有没有手动设置任何参数和没有设置标签调用 Axes.legend 将不会绘制图例lengend.

2. 标记现有图元素Labeling existing plot elements

为已经存在在坐标轴上的线制作一个图例(比如通过plot), 只需使用一个字符串迭代器调用这个函数,每个字符串对应一个图例项 . 比如:

ax.plot([1, 2, 3])
ax.legend(['A simple line'])

注意: 这种使用方法是不鼓励的,因为情节元素和标签之间的关系只根据它们的顺序隐含,很容易混淆 .

3. 显式定义图例中的元素 Explicitly defining the elements in the legend

对于完全控制哪些 artists 有一个图例条目, 可以分别传递一个legend artists的迭代表和一个legend标签的迭代表:

legend((line1, line2, line3), ('label1', 'label2', 'label3'))
Parameters:handles : Artist序列, 可选
一个Artists列表 (lines, patches) 添加到图例中. 将其与标签labels一起使用, 如果您需要完全控制图例中显示的内容,上面描述的自动机制是不够的。
在这种情况下,句柄和标签的长度应该相同 . 如果没有,则将其截断到较小的长度。
labels :  strings序列, 可选
在artists旁显示的标签labels列表. 和句柄一起使用,如果您需要完全控制图例中显示的内容,上面描述的自动机制是不够的。
Returns:matplotlib.legend.Legend 实例
Other Parameters:loc : str or pair of floats, default: rcParams["legend.loc"] (‘best’ for axes, ‘upper right’ for figures)
The location of the legend.The strings 'upper left', 'upper right', 'lower left', 'lower right' place the legend at the corresponding corner of the axes/figure.
The strings 'upper center', 'lower center', 'center left', 'center right' place the legend at the center of the corresponding edge of the axes/figure.
The string 'center' places the legend at the center of the axes/figure.
The string 'best' places the legend at the location, among the nine locations defined so far, with the minimum overlap with other drawn artists. This option can be quite slow for plots with large amounts of data; your plotting speed may benefit from providing a specific location.
The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored).For back-compatibility, 'center right' (but no other location) can also be spelled 'right', and each “string” locations can also be given as a numeric value:
Location StringLocation Code’best’0’upper right’1’upper left’2’lower left’3’lower right’4’right’5’center left’6’center right’7’lower center’8’upper center’9’center’10
bbox_to_anchor : BboxBase, 2-tuple, or 4-tuple of floats
Box that is used to position the legend in conjunction with loc. Defaults to axes.bbox (if called as a method to Axes.legend) or figure.bbox (if Figure.legend). This argument allows arbitrary placement of the legend.
Bbox coordinates are interpreted in the coordinate system given by bbox_transform, with the default transform Axes or Figure coordinates, depending on which legend is called.
If a 4-tuple or BboxBase is given, then it specifies the bbox (x, y, width, height) that the legend is placed in. To put the legend in the best location in the bottom right quadrant of the axes (or figure):
loc=’best’, bbox_to_anchor=(0.5, 0., 0.5, 0.5)
A 2-tuple (x, y) places the corner of the legend specified by loc at x, y. For example, to put the legend’s upper right-hand corner in the center of the axes (or figure) the following keywords can be used:
loc=’upper right’, bbox_to_anchor=(0.5, 0.5)
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 fromrcParams["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 fromrcParams["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 fromrcParams["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).
title_fontsize: str or None
The fontsize of the legend’s title. Default is the default fontsize.
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().

注意

不是所有类型的artist 都支持legend 命令. 查看 Legend guide获得更多信息.

实例

(Source codepngpdf)

../../_images/legend_00_00.png

Examples using matplotlib.pyplot.legend

../../_images/sphx_glr_bar_stacked_thumb.png

Stacked Bar Graph

../../_images/sphx_glr_errorbar_limits_simple_thumb.png

Errorbar limit selection

../../_images/sphx_glr_masked_demo_thumb.png

Masked Demo

../../_images/sphx_glr_scatter_symbol_thumb.png

Scatter Symbol

../../_images/sphx_glr_scatter_with_legend_thumb.png

Scatter plots with a legend

../../_images/sphx_glr_step_demo_thumb.png

Step Demo

../../_images/sphx_glr_contourf_hatching_thumb.png

Contourf Hatching

../../_images/sphx_glr_contourf_log_thumb.png

Contourf and log color scale

../../_images/sphx_glr_pie_and_donut_labels_thumb.png

Labeling a pie and a donut

../../_images/sphx_glr_legend_thumb.png

Legend using pre-defined labels

../../_images/sphx_glr_usetex_demo_thumb.png

Usetex Demo

../../_images/sphx_glr_whats_new_98_4_legend_thumb.png

Whats New 0.98.4 Legend

../../_images/sphx_glr_parasite_simple_thumb.png

Parasite Simple

../../_images/sphx_glr_findobj_demo_thumb.png

Findobj Demo

../../_images/sphx_glr_zorder_demo_thumb.png

Zorder Demo

../../_images/sphx_glr_sankey_basics_thumb.png

The Sankey class

../../_images/sphx_glr_svg_histogram_sgskip_thumb.png

SVG Histogram

../../_images/sphx_glr_pgf_preamble_sgskip_thumb.png

Pgf Preamble

../../_images/sphx_glr_simple_legend01_thumb.png

Simple Legend01

../../_images/sphx_glr_usage_thumb.png

Usage Guide

../../_images/sphx_glr_legend_guide_thumb.png

Legend guide

发表回复