a
    Sic                     @   sz  d Z ddlZddlZddlZddlZddlZddlmZm	Z	m
Z
mZ ddlmZmZ ddlmZ ddlmZ ddlmZ ddlmZmZmZmZmZ dd	lmZmZmZmZm Z m!Z! dd
l"m#Z# ddl$m%Z%m&Z&m'Z' ddl$m(Z(m)Z) ddl*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2m3Z3m4Z4 ddl5m6Z6 G dd de,Z7e	j8j9dd G dd deZ:dddZ;dddZ<dddddZ=dS ) a  
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 `~.Axes.legend`
    function. For more details on legends there is also a :doc:`legend guide
    </tutorials/intermediate/legend_guide>`.

The `Legend` class is a container of legend handles and legend texts.

The legend handler map specifies how to create legend handles from artists
(lines, patches, etc.) in the axes or figures. Default legend handlers are
defined in the :mod:`~matplotlib.legend_handler` module. While not all artist
types are covered by the default legend handlers, custom legend handlers can be
defined to support arbitrary objects.

See the :doc:`legend guide </tutorials/intermediate/legend_guide>` for more
information.
    N)_api
_docstringcolors	offsetbox)Artistallow_rasterization)silent_list)FontProperties)Line2D)Patch	RectangleShadowFancyBboxPatch	StepPatch)
CollectionCircleCollectionLineCollectionPathCollectionPolyCollectionRegularPolyCollection)Text)BboxBboxBaseTransformedBbox)BboxTransformToBboxTransformFrom)AnchoredOffsetboxDraggableOffsetBoxHPackerVPackerDrawingAreaTextArea)ErrorbarContainerBarContainerStemContainer   )legend_handlerc                       s6   e Zd Zd fdd	Zdd Zdd Zd	d
 Z  ZS )DraggableLegendFlocc                    s6   || _ tjddg|d || _t j||j|d dS )a  
        Wrapper around a `.Legend` to support mouse dragging.

        Parameters
        ----------
        legend : `.Legend`
            The `.Legend` instance to wrap.
        use_blit : bool, optional
            Use blitting for faster image composition. For details see
            :ref:`func-animation`.
        update : {'loc', 'bbox'}, optional
            If "loc", update the *loc* parameter of the legend upon finalizing.
            If "bbox", update the *bbox_to_anchor* parameter.
        r(   bboxupdate)use_blitN)legendr   check_in_list_updatesuper__init___legend_box)selfr-   r,   r+   	__class__ M/var/www/html/django/DPS/env/lib/python3.9/site-packages/matplotlib/legend.pyr1   6   s    zDraggableLegend.__init__c                 C   s6   | j dkr| |   n| j dkr2| |   d S )Nr(   r)   )r/   _update_locZget_loc_in_canvas_bbox_to_anchorr3   r6   r6   r7   finalize_offsetL   s    

zDraggableLegend.finalize_offsetc                 C   sR   | j  }|jdks|jdkr4| j d  | j  }t|}t||| j _d S )Nr   )	r-   get_bbox_to_anchorwidthheightset_bbox_to_anchorr   tuple	transform_loc)r3   loc_in_canvasr)   Z_bbox_transformr6   r6   r7   r8   R   s    

zDraggableLegend._update_locc                 C   s    | j jj|}| j | d S N)r-   axes	transAxesrA   r?   )r3   rC   Zloc_in_bboxr6   r6   r7   _update_bbox_to_anchor\   s    z&DraggableLegend._update_bbox_to_anchor)Fr(   )__name__
__module____qualname__r1   r;   r8   rG   __classcell__r6   r6   r4   r7   r'   5   s   
r'   a    
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 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 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 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)

ncols : int, default: 1
    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 : None or `matplotlib.font_manager.FontProperties` or dict
    The font properties of the legend. If None (default), the current
    :data:`matplotlib.rcParams` will be used.

fontsize : int or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
    The font size of the legend. If the value is numeric the size will be 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 : str or list, default: :rc:`legend.labelcolor`
    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, default: :rc:`legend.numpoints`
    The number of marker points in the legend when creating a legend
    entry for a `.Line2D` (line).

scatterpoints : int, default: :rc:`legend.scatterpoints`
    The number of marker points in the legend when creating
    a legend entry for a `.PathCollection` (scatter plot).

scatteryoffsets : iterable of floats, default: ``[0.375, 0.5, 0.3125]``
    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, default: :rc:`legend.markerscale`
    The relative size of legend markers compared with the originally
    drawn ones.

markerfirst : bool, default: True
    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.

frameon : bool, default: :rc:`legend.frameon`
    Whether the legend should be drawn on a patch (frame).

fancybox : bool, default: :rc:`legend.fancybox`
    Whether round edges should be enabled around the `.FancyBboxPatch` which
    makes up the legend's background.

shadow : bool, default: :rc:`legend.shadow`
    Whether to draw a shadow behind the legend.

framealpha : float, default: :rc:`legend.framealpha`
    The alpha transparency of the legend's background.
    If *shadow* is activated and *framealpha* is ``None``, the default value is
    ignored.

facecolor : "inherit" or color, default: :rc:`legend.facecolor`
    The legend's background color.
    If ``"inherit"``, use :rc:`axes.facecolor`.

edgecolor : "inherit" or color, default: :rc:`legend.edgecolor`
    The legend's background patch edge color.
    If ``"inherit"``, use take :rc:`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'
    :data:`~matplotlib.axes.Axes.transAxes` transform will be used.

title : str or None
    The legend's title. Default is no title (``None``).

title_fontproperties : None or `matplotlib.font_manager.FontProperties` or dict
    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 : int or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}, default: :rc:`legend.title_fontsize`
    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 : {'center', 'left', 'right'}, default: 'center'
    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, default: :rc:`legend.borderpad`
    The fractional whitespace inside the legend border, in font-size units.

labelspacing : float, default: :rc:`legend.labelspacing`
    The vertical space between the legend entries, in font-size units.

handlelength : float, default: :rc:`legend.handlelength`
    The length of the legend handles, in font-size units.

handleheight : float, default: :rc:`legend.handleheight`
    The height of the legend handles, in font-size units.

handletextpad : float, default: :rc:`legend.handletextpad`
    The pad between the legend handle and text, in font-size units.

borderaxespad : float, default: :rc:`legend.borderaxespad`
    The pad between the axes and legend border, in font-size units.

columnspacing : float, default: :rc:`legend.columnspacing`
    The spacing between columns, in font-size units.

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`.
)Z_legend_kw_docc                !       s  e Zd ZdZddiejZdZdd Ze	dde
jdTdd fddZdd Zdd Zdd Zdd ZeeeZdd Zedd Zee ee ee ee ee  e!e" e#e$ e%e& e'ejej(de)e* e+e, e-e. iZ/e0dd Z1e0dd  Z2e0d!d" Z3d#d$ Z4e5d%d& Z6dUd'd(Z7d)d* Z8d+d, Z9d-d. Z:d/d0 Z;d1d2 Z<d3d4 Z=d5d6 Z>d7d8 Z?dVd9d:Z@d;d< ZAdWd=d>ZBdXd?d@ZCdAdB ZDdCdD ZEeEZFdEdF ZGdYdGdHZHdIdJ ZIdZdKdLZJdMdN ZKd[dPdQZLdRdS ZM  ZNS )\Legendz5
    Place a legend on the axes at location loc.
    bestr      c                 C   s   dS )NrL   r6   r:   r6   r6   r7   __str__-  s    zLegend.__str__z3.6r(   NTr%   center)ncolc#          3         s  ddl m}$ ddlm}% t   |
du rT|dur@t|d| _qttj	d d| _n0t
|
| _t|
trd|
vr| jtj	d  | j | _g | _g | _d| _| | _dd	 }&|&|d
| _|&|d| _|&|d| _|&|d| _|&|d| _|&|d| _|&|d| _|&|d| _|&|d| _|&|d| _|&|d| _g g  }'}(t||D ]P\})}*t|)t r|)!drt"#d|)d|*d n|'$|) |($|* qH|'|( }}t%|}t&|dk rd}|dkr|n|#| _'| jdkrt(d| |	du rt)*g d| _+nt),|	| _+| jt&| j+ d }+t)-| j+|+d| j | _+d| _.t||$rld| _/|| _0| 1|j2 n&t||%rd| _/| 1| nt3d|| _4|du | _5|du rtj	d  }| j/s|d!v rd"}t|t rt"j6| j7|d#}| j/s|dkrt(d$|| _8| 9|| |du r(tj	d% }|d&kr<tj	d' }|du rPtj	d( }|d&krdtj	d) }|du rxtj	d* }t:d+dd|||dur|n|rdntj	d, |rd-nd.| jd|dur|ntj	d/ d0
| _;| <| j; t"j=g d1|"d2 |"| _>| ?||| | j5},| @| |,| _5|dur8|!dur8t(d3t
|!}-t|!trnd|!vrtj	d4 }|-| n6|dur|-| n t|!tstj	d4 }|-| | jA||-d5 d| _Bd6d7gd8d7gd8d7gd9d:gd9d:gd;}.|du rtj	d< durtj	d< }n
tj	d= }t|t r||.v r|.| }/t| j| jD ]N\}*}0|/D ]>}1z"tC|*|1 }2|0D|2 W  q8W n tEy~   Y n0 qDq8nzt|t r|d>kr| jD ]}0|0D| qnJt)F|rt| jtGHtIJ|D ]\}0}2|0D|2 qnt(d?|dS )@a+  
        Parameters
        ----------
        parent : `~matplotlib.axes.Axes` or `.Figure`
            The artist that contains the legend.

        handles : list of `.Artist`
            A list of Artists (lines, patches) to be added to the legend.

        labels : list of 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 smaller of both lengths.

        Other Parameters
        ----------------
        %(_legend_kw_doc)s

        Notes
        -----
        Users can specify any arbitrary location for the legend using the
        *bbox_to_anchor* keyword argument. *bbox_to_anchor* can be a
        `.BboxBase` (or derived there from) 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.
        r   )Axes)
FigureBaseN)sizezlegend.fontsizerT   c                 S   s   | d ur| S t j| S rD   )mplrcParams)valZrc_namer6   r6   r7   	val_or_rc  s    z"Legend.__init__.<locals>.val_or_rczlegend.numpointszlegend.markerscalezlegend.scatterpointszlegend.borderpadzlegend.labelspacingzlegend.handlelengthzlegend.handleheightzlegend.handletextpadzlegend.borderaxespadzlegend.columnspacingzlegend.shadow_z
The label z of z6 starts with '_'. It is thus excluded from the legend.   r%   z numpoints must be > 0; it was %d)g      ?g      ?g      ?TFz0Legend needs either Axes or FigureBase as parentz
legend.loc)r   rM   zupper right)r(   zIAutomatic legend placement (loc='best') not implemented for figure legendzlegend.facecolorinheritzaxes.facecolorzlegend.edgecolorzaxes.edgecolorzlegend.fancybox)r   r   zlegend.framealphazround,pad=0,rounding_size=0.2zsquare,pad=0zlegend.frameon)
xyr=   r>   	facecolor	edgecoloralphaboxstylemutation_scalesnapvisiblerP   leftright	alignmentzctitle_fontsize and title_fontproperties can't be specified at the same time. Only use one of them. zlegend.title_fontsize)prop	get_colorget_facecolorget_markerfacecolorget_markeredgecolorget_edgecolor)	linecolormarkerfacecolormfcmarkeredgecolormeczlegend.labelcolorz
text.colornonezInvalid labelcolor: )Kmatplotlib.axesrR   matplotlib.figurerS   r0   r1   r	   ri   rU   rV   	_from_any
isinstancedictset_sizeget_size_in_points	_fontsizetextslegendHandles_legend_title_box_custom_handler_map	numpointsmarkerscalescatterpoints	borderpadlabelspacinghandlelengthhandleheighthandletextpadborderaxespadcolumnspacingshadowzipstr
startswithr   warn_externalappendlistlen_ncols
ValueErrornparrayZ_scatteryoffsetsasarraytiler2   isaxesrE   
set_figurefigure	TypeErrorparent_loc_used_defaultcheck_getitemcodes_moder?   r   legendPatch_set_artist_propsr.   
_alignment_init_legend_box_set_loc	set_title
_draggablegetattr	set_colorAttributeErroriterable	itertoolscycler   to_rgba_array)3r3   r   handleslabelsr(   r   r   markerfirstr   Zscatteryoffsetsri   fontsizeZ
labelcolorr   r   r   r   r   r   r   ncolsmodeZfancyboxr   titleZtitle_fontsizeZ
framealphar^   r]   Zbbox_to_anchorbbox_transformframeonhandler_mapZtitle_fontpropertiesrh   rQ   rR   rS   rX   Z_labZ_handlabelhandlerepstmpZtitle_prop_fpZcolor_gettersZgetter_namestextgetter_namecolorr4   r6   r7   r1   0  s2   I































zLegend.__init__c                 C   s,   | | j | jr| j|_||   dS )zF
        Set the boilerplate props for artists added to axes.
        N)r   r   r   rE   set_transformget_transform)r3   ar6   r6   r7   r   A  s    zLegend._set_artist_propsc                 C   s$   d| _ || _d| _| j| j d S )NFT)r   	_loc_realstaler2   
set_offset_findoffset)r3   r(   r6   r6   r7   r   L  s    zLegend._set_locc                 C   s
   || _ dS )zSet the number of columns.N)r   )r3   r   r6   r6   r7   	set_ncolsU  s    zLegend.set_ncolsc                 C   s   | j S rD   )r   r:   r6   r6   r7   _get_locY  s    zLegend._get_locc                 C   s   | j dkr| |||\}}np| j tj v rZtdd||}| | j ||  |\}}n4| j \}	}
|  }|j	|j
|	  |j|j|
   }}|| || fS )z%Helper function to locate the legend.r   )rB   _find_best_positionrL   r   valuesr   from_bounds_get_anchored_bboxr<   x0r=   y0r>   )r3   r=   r>   xdescentydescentrendererxyr)   fxfyr6   r6   r7   r   ^  s    



"zLegend._findoffsetc                 C   s   |   sd S |jd|  d || j}| jdv r^d| j| j  | }| j	| 
 j|  | j|}| j|j | j| | jrt| jdd| | j| | j| |d d| _d S )Nr-   )gid)expandrZ   F)get_visible
open_groupget_gidpoints_to_pixelsr|   r   r   r   r2   	set_widthr<   r=   get_window_extentr   
set_boundsboundsset_mutation_scaler   r   drawclose_groupr   )r3   r   r   padr)   r6   r6   r7   r   o  s     

zLegend.draw)Zupdate_funcc                 C   s   | j S )z=Return the global default handler map, shared by all legends._default_handler_map)clsr6   r6   r7   get_default_handler_map  s    zLegend.get_default_handler_mapc                 C   s
   || _ dS )z:Set the global default handler map, shared by all legends.Nr   r   r   r6   r6   r7   set_default_handler_map  s    zLegend.set_default_handler_mapc                 C   s   | j | dS )z=Update the global default handler map, shared by all legends.N)r   r+   r   r6   r6   r7   update_default_handler_map  s    z!Legend.update_default_handler_mapc                 C   s    |   }| jri || jS |S )z*Return this legend instance's handler map.)r   r   )r3   Zdefault_handler_mapr6   r6   r7   get_legend_handler_map  s
    zLegend.get_legend_handler_mapc              	   C   sZ   z
| | W S  t tfy    Y n0 t| D ]&}z| | W   S  tyR   Y q.0 q.dS )a  
        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``.
        N)r   KeyErrortypemro)legend_handler_maporig_handleZhandle_typer6   r6   r7   get_legend_handler  s    
zLegend.get_legend_handlerc              	      s  j  g }g }g }d  jd  } j | } }	t||D ]\}
}|	|
}|du rtdt|
j	 |
d qDt|dtddjdd	}tj  |d
|d}|
|j |
||
 | |
||f qDg }ttt|jD ]D} fdd|D }r dnd}|
tdj  ||d qjdkrRdnd}j  }td|d||d_td_tj  j  jjjgd_ j !j" j#j _#|_$|_%dS )z
        Initialize the legend_box. The legend_box is an instance of
        the OffsetBox, which is packed with legend handles and
        texts. Once packed, their location is calculated during the
        drawing time.
        gffffff?gffffff?NzLegend does not support handles for {0} instances.
A proxy artist may be used instead.
See: https://matplotlib.org/stable/tutorials/intermediate/legend_guide.html#controlling-the-legend-entriesTbaselinere   )verticalalignmenthorizontalalignmentfontproperties)Zmultilinebaseline	textpropsg        )r=   r>   r   r   c                    s6   g | ].\}}t d j  r$||gn||gddqS )r   r   )r   sepchildrenalign)r   r   ).0htr   r   r3   r6   r7   
<listcomp>  s   z+Legend._init_legend_box.<locals>.<listcomp>rf   r   )r   r   r   r   r   fixed)r   r   r   r   r    )&r|   r   r   r   r   r   r   formatr   rH   r   r!   ry   ri   r    r   _textZlegend_artistfilterr   r   array_splitr   r   r   r   r   r   Z_legend_handle_boxr   r   r   r2   r   r   rE   r}   r~   )r3   r   r   r   Z	text_listZhandle_listZhandles_and_labelsdescentr>   r   r   r   handlerZtextboxZ	handleboxZ	columnboxZhandles_and_labels_columnZ	itemboxesrh   r   r   r6   r   r7   r     s    	





zLegend._init_legend_boxc           	      C   s   | j s
J g }g }g }| jjD ]}t|trF|| |  qt|t	rj||
 |  qt|tr|| |  qt|tr| \}}}}||D ]}|| qq|||fS )aC  
        Return display coordinates for hit testing for "best" positioning.

        Returns
        -------
        bboxes
            List of bounding boxes of all patches.
        lines
            List of `.Path` corresponding to each line.
        offsets
            List of (x, y) offsets of all collection.
        )r   r   	_childrenrx   r
   r   r   transform_pathget_pathr   get_bboxtransformedget_data_transformr   get_extentsr   _prepare_pointsrA   )	r3   bboxeslinesoffsetsartistrY   
offset_trfZhoffsetsoffsetr6   r6   r7   _auto_legend_data7  s,    




zLegend._auto_legend_datac                 C   s   | j |  gS rD   )r2   	get_framer:   r6   r6   r7   get_childrenX  s    zLegend.get_childrenc                 C   s   | j S )z:Return the `~.patches.Rectangle` used to frame the legend.)r   r:   r6   r6   r7   r  \  s    zLegend.get_framec                 C   s   dd | j D S )z4Return the list of `~.lines.Line2D`\s in the legend.c                 S   s   g | ]}t |tr|qS r6   )rx   r
   r   r   r6   r6   r7   r   b      z$Legend.get_lines.<locals>.<listcomp>)r~   r:   r6   r6   r7   	get_lines`  s    zLegend.get_linesc                 C   s   t ddd | jD S )z5Return the list of `~.patches.Patch`\s in the legend.r   c                 S   s   g | ]}t |tr|qS r6   )rx   r   r  r6   r6   r7   r   g  s   
z&Legend.get_patches.<locals>.<listcomp>)r   r~   r:   r6   r6   r7   get_patchesd  s    zLegend.get_patchesc                 C   s   t d| jS )z1Return the list of `~.text.Text`\s in the legend.r   )r   r}   r:   r6   r6   r7   	get_textsj  s    zLegend.get_textsc                 C   s$   t jg d|d || _|| j_dS )a  
        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 : {'center', 'left', 'right'}.

        rd   rg   N)r   r.   r   r2   r   )r3   rh   r6   r6   r7   set_alignmentn  s    zLegend.set_alignmentc                 C   s   | j jS )z)Get the alignment value of the legend box)r2   r   r:   r6   r6   r7   get_alignment~  s    zLegend.get_alignmentc                 C   sh   | j j| |r.| j jd | j d n| j jd | j d |dur^| j j| d| _dS )a  
        Set legend title and title style.

        Parameters
        ----------
        title : str
            The legend title.

        prop : `.font_manager.FontProperties` or `str` or `pathlib.Path`
            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.

        TFN)r   r  set_textset_visibleset_fontpropertiesr   )r3   r   ri   r6   r6   r7   r     s    zLegend.set_titlec                 C   s   | j jS )z1Return the `.Text` instance for the legend title.)r   r  r:   r6   r6   r7   	get_title  s    zLegend.get_titlec                 C   s    |d u r| j  }| jj|dS )N)r   )r   _get_rendererr2   r   r3   r   r6   r6   r7   r     s    
zLegend.get_window_extentc                 C   s   | j |S rD   )r2   r   r&  r6   r6   r7   get_tightbbox  s    zLegend.get_tightbboxc                 C   s
   | j  S )z*Get whether the legend box patch is drawn.)r   r   r:   r6   r6   r7   get_frame_on  s    zLegend.get_frame_onc                 C   s   | j | d| _dS )zt
        Set whether the legend box patch is drawn.

        Parameters
        ----------
        b : bool
        TN)r   r"  r   )r3   br6   r6   r7   set_frame_on  s    zLegend.set_frame_onc                 C   s   | j du r| jjS | j S dS )z4Return the bbox that the legend will be anchored to.N)r9   r   r)   r:   r6   r6   r7   r<     s    
zLegend.get_bbox_to_anchorc              
   C   s   |du rd| _ dS t|tr$|| _ njzt|}W n4 tyd } ztd| |W Y d}~n
d}~0 0 |dkr|d |d ddg}tj| | _ |du rt| j	j
}t| j || _ d| _dS )a%  
        Set the bbox that the legend will be anchored to.

        Parameters
        ----------
        bbox : `~matplotlib.transforms.BboxBase` or tuple
            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 : `~matplotlib.transforms.Transform`, optional
            A transform to apply to the bounding box. If not specified, this
            will use a transform to the bounding box of the parent.
        NzInvalid bbox: rZ   r   r%   T)r9   rx   r   r   r   r   r   r   r   r   r)   r   r   )r3   r)   rA   lerrr6   r6   r7   r?     s$    
&zLegend.set_bbox_to_anchorc              	   C   s   t |||| j|| j S )a4  
        Place the *bbox* inside the *parentbbox* according to a given
        location code. Return the (x, y) coordinate of the bbox.

        Parameters
        ----------
        loc : int
            A location code in range(1, 11). This corresponds to the possible
            values for ``self._loc``, excluding "best".
        bbox : `~matplotlib.transforms.Bbox`
            bbox to be placed, in display coordinates.
        parentbbox : `~matplotlib.transforms.Bbox`
            A parent box which will contain the bbox, in display coordinates.
        )r   r   r   r   r|   )r3   r(   r)   Z
parentbboxr   r6   r6   r7   r     s    zLegend._get_anchored_bboxc                    s.  j s
J t } \}}}tdd|| |du rZ fddtdtjD }g }	t	|D ]\}
\}}t||||d}t
fdd|D | | t
fdd|D  }|dkr||f  S |	||
||ff qft|	\}}\}}jr&t | dkr&td	 ||fS )
z
        Determine the best location to place the legend.

        *consider* is a list of ``(x, y)`` pairs to consider as a potential
        lower-left corner of the legend. All are display coords.
        r   Nc                    s    g | ]} |  qS r6   )r   r<   )r   r   )r)   r   r3   r6   r7   r     s
   z.Legend._find_best_position.<locals>.<listcomp>r%   c                 3   s   | ]}  |jV  qd S rD   )count_containsverticesr   line	legendBoxr6   r7   	<genexpr>  s   z-Legend._find_best_position.<locals>.<genexpr>c                 3   s   | ]}|j  d dV  qdS )F)filledN)intersects_bboxr/  r1  r6   r7   r3  !  s   zGCreating legend with loc="best" can be slow with large amounts of data.)r   timeperf_counterr  r   r   ranger   r   	enumeratesumr-  count_overlapsr   minr   r   r   )r3   r=   r>   r   Zconsider
start_timer  r  r  
candidatesidxr+  r)  ZbadnessrY   r6   )r)   r2  r   r3   r7   r     s@    
zLegend._find_best_positionc                 C   s*   |  |\}}|d ur||fS | j|S rD   )_default_containsr   contains)r3   eventinsideinfor6   r6   r7   rA  1  s    zLegend.containsFc                 C   s@   |r | j du r:t| ||d| _ n| j dur4| j   d| _ | j S )a  
        Enable or disable mouse dragging support of the legend.

        Parameters
        ----------
        state : bool
            Whether mouse dragging is enabled.
        use_blit : bool, optional
            Use blitting for faster image composition. For details see
            :ref:`func-animation`.
        update : {'loc', 'bbox'}, optional
            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
        -------
        `.DraggableLegend` or *None*
            If *state* is ``True`` this returns the `.DraggableLegend` helper
            instance. Otherwise this returns *None*.
        Nr*   )r   r'   
disconnect)r3   stater,   r+   r6   r6   r7   set_draggable7  s    



zLegend.set_draggablec                 C   s
   | j duS )z@Return ``True`` if the legend is draggable, ``False`` otherwise.N)r   r:   r6   r6   r7   get_draggableY  s    zLegend.get_draggable)NNNTNNNNNNNNNNNNr%   NNNNNNNNNNNNNrP   )T)N)N)N)N)N)Fr(   )OrH   rI   rJ   __doc__r   r   zorderrO   r   make_keyword_onlyr   dedent_interpdr1   r   r   r   r   propertyrB   r   r   r   r$   r&   ZHandlerStemr"   ZHandlerErrorbarr
   ZHandlerLine2Dr   ZHandlerPatchr   ZHandlerStepPatchr   ZHandlerLineCollectionr   ZHandlerRegularPolyCollectionr   ZHandlerCircleCollectionr#   Zupdate_from_first_childr@   ZHandlerTupler   ZHandlerPathCollectionr   ZHandlerPolyCollectionr   classmethodr   r   r   r   staticmethodr   r   r  r  r  r  r  r  r  r   r   r$  r   r'  r(  r*  Z
draw_framer<   r?   r   r   rA  rG  rH  rK   r6   r6   r4   r7   rL   $  s   
                               '  	

"




d!



+
.
"rL   c           	      c   s   g }| D ]V}|g dd |j D |j7 }t|dr|jD ]"}|g dd |j D |j7 }q:qi t |ppi }tj}|D ]V}| }|dkr|||r|V  q~|r~|ds~|||s~t	
dt|j q~q~dS )	z6Yield artists that can be used as handles in a legend.c                 s   s$   | ]}t |ttttfr|V  qd S rD   rx   r
   r   r   r   r   r   r6   r6   r7   r3  e  s   z&_get_legend_handles.<locals>.<genexpr>	parasitesc                 s   s$   | ]}t |ttttfr|V  qd S rD   rP  rQ  r6   r6   r7   r3  l  s   
_nolegend_rY   zLegend does not support handles for {0} instances.
See: https://matplotlib.org/stable/tutorials/intermediate/legend_guide.html#implementing-a-custom-legend-handlerN)r	  
containershasattrrR  rL   r   r   	get_labelr   r   r   r  r   rH   )	axsr   Zhandles_originalaxZaxxr   Zhas_handlerr   r   r6   r6   r7   _get_legend_handles`  s>    



rY  c                 C   sJ   g }g }t | |D ].}| }|r|ds|| || q||fS )z%Return handles and labels for legend.rY   )rY  rV  r   r   )rW  r   r   r   r   r   r6   r6   r7   _get_legend_handles_labels  s    
rZ  )r   r   c                O   sR  t t}|d}d}|dus(|dur6|r6td |rR|rRtt|| \}}n|durr|du rrdd |D }n|dur|du rdd tt| ||D }nt|dkrt	| |\}}|s|
d	 n~t|d
kr|\}tdd |D rtddd tt| ||D }n4t|dkr>|dd \}}|dd }ntd||||fS )a-  
    Get the handles and labels from the calls to either ``figure.legend``
    or ``axes.legend``.

    The parser is a bit involved because we support::

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

    The behavior for a mixture of positional and keyword handles and labels
    is undefined and issues a warning.

    Parameters
    ----------
    axs : list of `.Axes`
        If handles are not given explicitly, the artists in these Axes are
        used as handles.
    *args : tuple
        Positional parameters passed to ``legend()``.
    handles
        The value of the keyword argument ``legend(handles=...)``, or *None*
        if that keyword argument was not used.
    labels
        The value of the keyword argument ``legend(labels=...)``, or *None*
        if that keyword argument was not used.
    **kwargs
        All other keyword arguments passed to ``legend()``.

    Returns
    -------
    handles : list of `.Artist`
        The legend handles.
    labels : list of str
        The legend labels.
    extra_args : tuple
        *args* with positional handles and labels removed.
    kwargs : dict
        *kwargs* with keywords handles and labels removed.

    r   r6   NzMYou have mixed positional and keyword arguments, some input may be discarded.c                 S   s   g | ]}|  qS r6   )rV  )r   r   r6   r6   r7   r     r  z&_parse_legend_args.<locals>.<listcomp>c                 S   s   g | ]\}}|qS r6   r6   r   r   r   r6   r6   r7   r     r  r   zNo artists with labels found to put in legend.  Note that artists whose label start with an underscore are ignored when legend() is called with no argument.r%   c                 s   s   | ]}t |tV  qd S rD   )rx   r   )r   r+  r6   r6   r7   r3    r  z%_parse_legend_args.<locals>.<genexpr>z\A single argument passed to legend() must be a list of labels, but found an Artist in there.c                 S   s   g | ]\}}|qS r6   r6   r[  r6   r6   r7   r     r  rZ   zInvalid arguments to legend.)logging	getLoggerrH   getr   r   r   rY  r   rZ  warninganyr   )rW  r   r   argskwargsloghandlers
extra_argsr6   r6   r7   _parse_legend_args  s>    -


rf  )N)N)>rI  r   r\  r6  numpyr   
matplotlibrU   r   r   r   r   matplotlib.artistr   r   matplotlib.cbookr   matplotlib.font_managerr	   matplotlib.linesr
   matplotlib.patchesr   r   r   r   r   matplotlib.collectionsr   r   r   r   r   r   matplotlib.textr   matplotlib.transformsr   r   r   r   r   matplotlib.offsetboxr   r   r   r   r    r!   matplotlib.containerr"   r#   r$   r  r&   r'   interpdr+   rL   rY  rZ  rf  r6   r6   r6   r7   <module>   s>     , D      B
"
