当前位置: 代码迷 >> 综合 >> Python可视化:`legend()`函数详细参数
  详细解决方案

Python可视化:`legend()`函数详细参数

热度:72   发布时间:2024-02-07 02:59:41.0

Python可视化:legend()函数详细参数

legend()函数是用来设置图像图例相关参数的函数,其所有参数解释如下:

Signature: plt.legend(*args, **kwargs)
Docstring:
Place a legend on the axes.Call signatures::legend()legend(labels)legend(handles, labels)The call signatures correspond to three different ways how to use
this method.**1. Automatic detection of elements to be shown in the legend**The elements to be added to the legend are automatically determined,
when you do not pass in any extra arguments.In this case, the labels are taken from the artist. You can specify
them either at artist creation or by calling the
:meth:`~.Artist.set_label` method on the artist::line, = ax.plot([1, 2, 3], label='Inline label')ax.legend()or::line, = ax.plot([1, 2, 3])line.set_label('Label via method')ax.legend()Specific lines can be excluded from the automatic legend element
selection by defining a label starting with an underscore.
This is default for all artists, so calling `Axes.legend` without
any arguments and without setting the labels manually will result in
no legend being drawn.**2. Labeling existing plot elements**To make a legend for lines which already exist on the axes
(via plot for instance), simply call this function with an iterable
of strings, one for each legend item. For example::ax.plot([1, 2, 3])ax.legend(['A simple line'])Note: This way of using is discouraged, because the relation between
plot elements and labels is only implicit by their order and can
easily be mixed up.**3. Explicitly defining the elements in the legend**For full control of which artists have a legend entry, it is possible
to pass an iterable of legend artists followed by an iterable of
legend labels respectively::legend((line1, line2, line3), ('label1', 'label2', 'label3'))Parameters
----------handles : sequence of `.Artist`, optionalA list of Artists (lines, patches) to be added to the legend.Use this together with *labels*, if you need full control on whatis shown in the legend and the automatic mechanism described aboveis not sufficient.The length of handles and labels should be the same in thiscase. If they are not, they are truncated to the smaller length.labels : sequence of strings, optionalA list of labels to show next to the artists.Use this together with *handles*, if you need full control on whatis shown in the legend and the automatic mechanism described aboveis not sufficient.Other Parameters
----------------loc : str or pair of floats, default: :rc:`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 theaxes/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 coordinates (in which case *bbox_to_anchor*will be ignored).For back-compatibility, ``'center right'`` (but no other location) can alsobe spelled ``'right'``, and each "string" locations can also be given as anumeric value:===============   =============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===============   =============bbox_to_anchor : `.BboxBase`, 2-tuple, or 4-tuple of floatsBox 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 arbitraryplacement of the legend.Bbox coordinates are interpreted in the coordinate system given by`bbox_transform`, with the default transformAxes 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 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 by *loc* 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)ncol : integerThe number of columns that the legend has. Default is 1.prop : None or :class:`matplotlib.font_manager.FontProperties` or dictThe font properties of the legend. If None (default), the current:data:`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 thesize will be the absolute font size in points. String values arerelative to the current default font size. This argument is onlyused if `prop` is not specified.numpoints : None or intThe number of marker points in the legend when creating a legendentry for a `.Line2D` (line).Default is ``None``, which will take the value from:rc:`legend.numpoints`.scatterpoints : None or intThe number of marker points in the legend when creatinga legend entry for a `.PathCollection` (scatter plot).Default is ``None``, which will take the value from:rc:`legend.scatterpoints`.scatteryoffsets : iterable of floatsThe 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]``. Default is ``[0.375, 0.5, 0.3125]``.markerscale : None or int or floatThe relative size of legend markers compared with the originallydrawn ones.Default is ``None``, which will take the value from:rc:`legend.markerscale`.markerfirst : boolIf *True*, legend marker is placed to the left of the legend label.If *False*, legend marker is placed to the right of the legendlabel.Default is *True*.frameon : None or boolControl whether the legend should be drawn on a patch(frame).Default is ``None``, which will take the value from:rc:`legend.frameon`.fancybox : None or boolControl whether round edges should be enabled around the:class:`~matplotlib.patches.FancyBboxPatch` which makes up thelegend's background.Default is ``None``, which will take the value from:rc:`legend.fancybox`.shadow : None or boolControl whether to draw a shadow behind the legend.Default is ``None``, which will take the value from:rc:`legend.shadow`.framealpha : None or floatControl the alpha transparency of the legend's background.Default is ``None``, which will take the value from:rc:`legend.framealpha`.  If shadow is activated and*framealpha* is ``None``, the default value is ignored.facecolor : None or "inherit" or a color specControl the legend's background color.Default is ``None``, which will take the value from:rc:`legend.facecolor`.  If ``"inherit"``, it will take:rc:`axes.facecolor`.edgecolor : None or "inherit" or a color specControl the legend's background patch edge color.Default is ``None``, which will take the value from:rc:`legend.edgecolor` If ``"inherit"``, it will take:rc:`axes.edgecolor`.mode : {"expand", None}If `mode` is set to ``"expand"`` the legend will be horizontallyexpanded to fill the axes area (or `bbox_to_anchor` if definesthe legend's size).bbox_transform : None or :class:`matplotlib.transforms.Transform`The transform for the bounding box (`bbox_to_anchor`). For a valueof ``None`` (default) the Axes':data:`~matplotlib.axes.Axes.transAxes` transform will be used.title : str or NoneThe legend's title. Default is no title (``None``).title_fontsize: str or NoneThe fontsize of the legend's title.  Default is the default fontsize.borderpad : float or NoneThe fractional whitespace inside the legend border.Measured in font-size units.Default is ``None``, which will take the value from:rc:`legend.borderpad`.labelspacing : float or NoneThe vertical space between the legend entries.Measured in font-size units.Default is ``None``, which will take the value from:rc:`legend.labelspacing`.handlelength : float or NoneThe length of the legend handles.Measured in font-size units.Default is ``None``, which will take the value from:rc:`legend.handlelength`.handletextpad : float or NoneThe pad between the legend handle and text.Measured in font-size units.Default is ``None``, which will take the value from:rc:`legend.handletextpad`.borderaxespad : float or NoneThe pad between the axes and legend border.Measured in font-size units.Default is ``None``, which will take the value from:rc:`legend.borderaxespad`.columnspacing : float or NoneThe spacing between columns.Measured in font-size units.Default is ``None``, which will take the value from:rc:`legend.columnspacing`.handler_map : dict or NoneThe custom dictionary mapping instances or types to a legendhandler. This `handler_map` updates the default handler mapfound at :func:`matplotlib.legend.Legend.get_legend_handler_map`.Returns
-------:class:`matplotlib.legend.Legend` instanceNotes
-----Not all kinds of artist are supported by the legend command. See
:doc:`/tutorials/intermediate/legend_guide` for details.Examples
--------.. plot:: gallery/text_labels_and_annotations/legend.py
File:      c:\users\hsingluliu\anaconda3\lib\site-packages\matplotlib\pyplot.py
Type:      function