B
    ]t\                 @   sr  d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	m
Z
 ddlmZ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 dd
lmZmZmZmZ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* ddl&m+Z+ ddl,m-Z-m.Z.m/Z/ ddl0m1Z1 G dd de+Z2dZ3ej4j5e3d G dd de	Z6dddZ7d ddZ8dddddZ9dS )!aO  
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
    :meth:`~matplotlib.axes.Axes.legend` function. For more details on legends
    there is also a :doc:`legend guide </tutorials/intermediate/legend_guide>`.

The Legend class can be considered as a container of legend handles and
legend texts. Creation of corresponding legend handles from the plot elements
in the axes or figures (e.g., lines, patches, etc.) are specified by the
handler map, which defines the mapping between the plot elements and the
legend handlers to be used (the default legend handlers are defined in the
:mod:`~matplotlib.legend_handler` module).  Note that not all kinds of
artist are supported by the legend yet by default but it is possible to
extend the legend handler's capabilities to support arbitrary objects. See
the :doc:`legend guide </tutorials/intermediate/legend_guide>` for more
information.
    N)rcParams)	docstring)Artistallow_rasterization)silent_listis_hashablewarn_deprecated)FontProperties)Line2D)Patch	RectangleShadowFancyBboxPatch)LineCollectionRegularPolyCollectionCircleCollectionPathCollectionPolyCollection)BboxBboxBaseTransformedBbox)BboxTransformToBboxTransformFrom)HPackerVPackerTextAreaDrawingArea)DraggableOffsetBox)ErrorbarContainerBarContainerStemContainer   )legend_handlerc               @   s6   e Zd ZdddZdd Zdd Zd	d
 Zdd ZdS )DraggableLegendFlocc             C   s:   || _ |dkr|| _nt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$   bboxz'update parameter '%s' is not supported.)use_blitN)legend_update
ValueErrorr   __init___legend_box)selfr'   r&   update r.   0lib/python3.7/site-packages/matplotlib/legend.pyr*   3   s    zDraggableLegend.__init__c             C   s   | j |S )N)r'   contains)r,   r'   Zevtr.   r.   r/   artist_pickerM   s    zDraggableLegend.artist_pickerc             C   sF   |   }| jdkr| | n$| jdkr4| | ntd| j d S )Nr$   r%   z'update parameter '%s' is not supported.)Zget_loc_in_canvasr(   _update_loc_update_bbox_to_anchorRuntimeErrorr-   )r,   loc_in_canvasr.   r.   r/   finalize_offsetP   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_point_loc)r,   r5   r%   Z_bbox_transformr.   r.   r/   r2   [   s    

zDraggableLegend._update_locc             C   s$   | j jj}||}| j | d S )N)r'   axesZ	transAxesr<   r:   )r,   r5   ZtrZloc_in_bboxr.   r.   r/   r3   i   s    

z&DraggableLegend._update_bbox_to_anchorN)Fr$   )__name__
__module____qualname__r*   r1   r6   r2   r3   r.   r.   r.   r/   r#   2   s
   
r#   a  
loc : int or string or pair of floats, default: :rc:`legend.loc` ('best' for axes, 'upper right' for figures)
    The location of the legend. Possible codes are:

        ===============   =============
        Location String   Location Code
        ===============   =============
        'best'            0
        'upper right'     1
        'upper left'      2
        'lower left'      3
        'lower right'     4
        'right'           5
        'center left'     6
        'center right'    7
        'lower center'    8
        'upper center'    9
        'center'          10
        ===============   =============


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

    The 'best' option can be quite slow for plots with large amounts
    of data. Your plotting speed may benefit from providing a specific
    location.

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 :class:`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 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
    :rc:`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
    :rc:`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
    :rc:`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
    :rc:`legend.frameon`.

fancybox : None or bool
    Control whether round edges should be enabled around the
    :class:`~matplotlib.patches.FancyBboxPatch` which makes up the
    legend's background.
    Default is ``None``, which will take the value from
    :rc:`legend.fancybox`.

shadow : None or bool
    Control whether to draw a shadow behind the legend.
    Default is ``None``, which will take the value from
    :rc:`legend.shadow`.

framealpha : None or float
    Control 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 spec
    Control 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 spec
    Control 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 horizontally
    expanded to fill the axes area (or `bbox_to_anchor` if defines
    the legend's size).

bbox_transform : None or :class:`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_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
    :rc:`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
    :rc:`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
    :rc:`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
    :rc:`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
    :rc:`legend.borderaxespad`.

columnspacing : float or None
    The spacing between columns.
    Measured in font-size units.
    Default is ``None``, which will take the value from
    :rc:`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 :func:`matplotlib.legend.Legend.get_legend_handler_map`.

)_legend_kw_docc               @   s  e Zd ZdZdddddddd	d
dddZdZdd ZejdYddZ	dd Z
dd Zdd ZeeeZdd Zedd ZdZddZ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*e+d!d" Z,e+d#d$ Z-e+d%d& Z.d'd( Z/e0d)d* Z1d[d+d,Z2d-d. Z3d/d0 Z4d1d2 Z5d3d4 Z6d5d6 Z7d7d8 Z8d9d: Z9d\d;d<Z:d=d> Z;d]d?d@Z<dAdB Z=dCdD Z>dEdF Z?dGdH Z@d^dIdJZAdKdL ZBd_dMdNZCdOdP ZDd`dSdTZEdUdV ZFdadWdXZGdS )bLegendz6
    Place a legend on the axes at location loc.

    r   r!                        	   
   )bestzupper rightz
upper leftz
lower leftzlower rightrightzcenter leftzcenter rightzlower centerzupper centercenterc             C   s   dS )NrC   r.   )r,   r.   r.   r/   __str__G  s    zLegend.__str__NTc        +   	   C   s`  ddl m}  ddlm}! t|  |
dkrR|dk	r@t|d| _qttd d| _n6t	|
t
rtf |
| _d|
kr| jtd  n|
| _| j | _g | _g | _d| _|| _t }"x:dD ]2}#|"|# dkrtd	|#  }$n|"|# }$t| |#|$ qW ~"g g  }%}&xXt||D ]J\}'}(t	|'tr:|'d
r:td|(|' n|%|' |&|( qW |%|& }}t|}t|dk rxd}|| _| jdkrtd| |	dkrt !dddg| _"nt #|	| _"| j$t| j" d })t %| j"|)d| j$ | _"d| _&t	|| rd| _'|| _(| )|j* n&t	||!r8d| _'| )| nt+d|| _,|dkrntd }| j'sn|dkrnd}t	|tr|| j-kr| j'rtd|d.| j-f  d}ntd|d.| j-f  d}n
| j-| }| j's|dkrtd d}|| _/| 0|| |dkrtd }|dkr.td }|dkr@td }|dkrRtd  }t1d!d"d"||| jdd#| _2|dkr~td$ }|r| j2j3d%dd&d' n| j2j3d(dd) | 4| j2 || _5|dkrtd* | _5| 6||| |dkr|r| 7 8d n| 7 8td+  n| 7 8| || _9|dkr6td, }t|d}*| j:||*d- | j| _;d| _<dS ).aC  
        Parameters
        ----------
        parent : `~matplotlib.axes.Axes` or `.Figure`
            The artist that contains the legend.

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

        labels : sequence of strings
            A list of labels to show next to the artists. The length of handles
            and labels should be the same. If they are not, they are truncated
            to the smaller of both lengths.

        Other Parameters
        ----------------

        %(_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 an instance
        of BboxBase(or its derivatives) or a tuple of 2 or 4 floats.
        See :meth:`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)FigureN)sizezlegend.fontsizerS   )	numpointsmarkerscaleshadowcolumnspacingscatterpointshandleheight	borderpadlabelspacinghandlelengthhandletextpadborderaxespadzlegend._zVThe handle {!r} has a label of {!r} which cannot be automatically added to the legend.rD   r!   z numpoints must be > 0; it was %dg      ?g      ?g      ?TFz,Legend needs either Axes or Figure as parentz
legend.loc)r   rM   zupper rightzLUnrecognized location "%s". Falling back on "best"; valid locations are
	%s
z
	zSUnrecognized location "%s". Falling back on "upper right"; valid locations are
	%s
ziAutomatic legend placement (loc="best") not implemented for figure legend. Falling back on "upper right".zlegend.facecolorZinheritzaxes.facecolorzlegend.edgecolorzaxes.edgecolor)g        g        g      ?)Zxyr8   r9   	facecolor	edgecolorZmutation_scaleZsnapzlegend.fancyboxroundg?)padZrounding_sizeZsquare)rc   zlegend.frameonzlegend.framealphazlegend.title_fontsize)prop)=Zmatplotlib.axesrQ   Zmatplotlib.figurerR   r   r*   r	   rd   r   
isinstancedictZset_sizeZget_size_in_points	_fontsizetextslegendHandles_legend_title_box_custom_handler_maplocalssetattrzipstr
startswithwarningswarnformatappendlistlen_ncolrT   r)   nparrayZ_scatteryoffsetsZasarrayrX   Ztiler+   isaxesr>   
set_figurefigure	TypeErrorparentcodesjoin_moder:   r   legendPatchZset_boxstyle_set_artist_props
_drawFrame_init_legend_box	get_frameZ	set_alphar=   	set_titleZ_last_fontsize_points
_draggable)+r,   r~   handleslabelsr$   rT   rU   markerfirstrX   Zscatteryoffsetsrd   fontsizerZ   r[   r\   rY   r]   r^   rW   ncolmodeZfancyboxrV   titleZtitle_fontsizeZ
framealphara   r`   Zbbox_to_anchorZbbox_transformZframeonhandler_maprQ   rR   Zlocals_viewnamevalueZ_labZ_handlabelhandleZrepsZtpropr.   r.   r/   r*   J  s    K






















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|   rz   r>   Zset_transformget_transform)r,   ar.   r.   r/   r   A  s    zLegend._set_artist_propsc             C   s   || _ d| _| j| j d S )NT)	_loc_realstaler+   Z
set_offset_findoffset)r,   r$   r.   r.   r/   _set_locL  s    zLegend._set_locc             C   s   | j S )N)r   )r,   r.   r.   r/   _get_locT  s    zLegend._get_locc             C   s   | j dkr| |||\}}np| j tj krZtdd||}| | j ||  |\}}n4| j \}	}
|  }|j	|j
|	  |j|j|
   }}|| || fS )z%Helper function to locate the legend.r   )r=   _find_best_positionrC   r   valuesr   from_bounds_get_anchored_bboxr7   x0r8   y0r9   )r,   r8   r9   xdescentydescentrendererxyr%   ZfxZfyr.   r.   r/   r   Y  s    


"zLegend._findoffsetc             C   s   |   sdS |d || j}| jdkrVd| j| j  | }| j| 	 j
|  | j|}| j|j|j|j
|j | j| | jr| jrt| jdd}|| | j| | j| |d d| _dS )z+Draw everything that belongs to the legend.Nr'   )expandrD   F)Zget_visibleZ
open_grouppoints_to_pixelsrg   r   r^   rZ   r+   Z	set_widthr7   r8   get_window_extentr   Z
set_boundsr   r   r9   Zset_mutation_scaler   rV   r   drawZclose_groupr   )r,   r   r   rc   r%   rV   r.   r.   r/   r   j  s&    



zLegend.drawc             C   s   |dkr| j S || j S dS )zm
        Return the approximate height of the text. This is used to place
        the legend handle.
        N)rg   r   )r,   r   r.   r.   r/   _approx_text_height  s    zLegend._approx_text_height)Zupdate_funcc             C   s   | j S )zF
        A class method that returns the default handler map.
        )_default_handler_map)clsr.   r.   r/   get_default_handler_map  s    zLegend.get_default_handler_mapc             C   s
   || _ dS )z@
        A class method to set the default handler map.
        N)r   )r   r   r.   r.   r/   set_default_handler_map  s    zLegend.set_default_handler_mapc             C   s   | j | dS )zC
        A class method to update the default handler map.
        N)r   r-   )r   r   r.   r.   r/   update_default_handler_map  s    z!Legend.update_default_handler_mapc             C   s.   |   }| jr&| }|| j |S |S dS )z)
        Return the handler map.
        N)r   rk   copyr-   )r,   Zdefault_handler_mapZhmr.   r.   r/   get_legend_handler_map  s    zLegend.get_legend_handler_mapc          	   C   s^   t |r&y| | S  tk
r$   Y nX x2t| D ]"}y| | S  tk
rT   Y q4X q4W 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_hanler_map* and return the associated value.
        Otherwise, it checks for each of the classes in its
        method-resolution-order. If no matching key is found, it
        returns ``None``.
        N)r   KeyErrortypemro)legend_handler_maporig_handleZhandle_typer.   r.   r/   get_legend_handler  s    
zLegend.get_legend_handlerc          	      s~  j  g }g }g }tddjd}d  jd  } j | }	 }
xt||D ]\}}|
|}|dkrt	d
| |d q^t||ddd	}tj  |	d
|d}||j ||| | |||f q^W |rbtjt|}tt||\}}|| }|d g| |g|  }tdgt|dd g}t||}ng }g }x|D ]\}} fdd||||  D }r|d  d d n|d  d d rdnd}|tdj  ||d qpW jdkrdnd}j  }td|d||d_td_ tj!  j  dj jgd_"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.
        baselineleft)ZverticalalignmentZhorizontalalignmentZfontpropertiesgffffff?gffffff?NzLegend does not support {!r} instances.
A proxy artist may be used instead.
See: http://matplotlib.org/users/legend_guide.html#creating-artists-specifically-for-adding-to-the-legend-aka-proxy-artistsT)Z	textpropsZmultilinebaselineZminimumdescentg        )r8   r9   r   r   r!   r   c                s6   g | ].\}}t d j  r$||gn||gddqS )r   r   )rc   sepchildrenalign)r   r]   ).0ht)r   r   r,   r.   r/   
<listcomp>C  s   z+Legend._init_legend_box.<locals>.<listcomp>FrN   )rc   r   r   r   r   Zfixed)rc   r   r   r   r    rO   )'rg   rf   rd   r   rY   r   rn   r   rq   rr   rs   rt   r   r   r\   _textZlegend_artistminrw   rv   divmodrx   concatenateZcumsumget_childrenZset_minimumdescentr   r[   r   rW   r   Z_legend_handle_boxrj   rZ   r+   r{   r|   rh   ri   )r,   r   r   r   Z	text_listZhandle_listZhandles_and_labelsZ
label_propZdescentr9   r   r   ZlabZhandlerZtextboxZ	handleboxr   ZnrowsZnum_largecolZnum_smallcolZrows_per_colZ
start_idxsZcolsZ	columnboxZi0ZdiZ	itemBoxesZ	alignmentr   r   r.   )r   r   r,   r/   r     s|    

	






zLegend._init_legend_boxc             C   sL  | j s
t| j}g }g }g }x@|jD ]6}t|ts6t| }| }||}|	| q$W x`|j
D ]V}t|tsxtt|tr| }	|	| |	 qf| }	|	| |	 qfW xD|jD ]:}| \}	}
}}t|rx|
|D ]}|	| qW qW ytdd |D }W n  tk
r>   tg }Y nX ||||gS )a{  
        Returns list of vertices and extents covered by the plot.

        Returns a two long list.

        First element is a list of (x, y) vertices (in
        display-coordinates) covered by all the lines and line
        collections, in the legend's handles.

        Second element is a list of bounding boxes for all the patches in
        the legend's handles.
        c             S   s   g | ]
}|j qS r.   )vertices)r   lr.   r.   r/   r     s    z,Legend._auto_legend_data.<locals>.<listcomp>)rz   AssertionErrorr~   linesre   r
   Zget_pathr   Ztransform_pathrt   patchesr   r   Zget_data_transformZget_bboxZtransformedZget_extentscollectionsZ_prepare_pointsrv   	transformrx   r   r)   ry   )r,   axbboxesr   offsetsr   pathZtransZtpathr   ZtransOffsetZhoffsetspathsoffsetr   r.   r.   r/   _auto_legend_datae  s8    


zLegend._auto_legend_datac             C   s   |  | dS )z^
        Set draw frame to b.

        Parameters
        ----------
        b : bool
        N)set_frame_on)r,   br.   r.   r/   
draw_frame  s    zLegend.draw_framec             C   s(   g }| j r|| j  ||   |S )zReturn a list of child artists.)r+   rt   r   )r,   r   r.   r.   r/   r     s
    zLegend.get_childrenc             C   s   | j S )zV
        Return the `~.patches.Rectangle` instances used to frame the legend.
        )r   )r,   r.   r.   r/   r     s    zLegend.get_framec             C   s   dd | j D S )z:Return a list of `~.lines.Line2D` instances in the legend.c             S   s   g | ]}t |tr|qS r.   )re   r
   )r   r   r.   r.   r/   r     s    z$Legend.get_lines.<locals>.<listcomp>)ri   )r,   r.   r.   r/   	get_lines  s    zLegend.get_linesc             C   s   t ddd | jD S )z;Return a list of `~.patches.Patch` instances in the legend.r   c             S   s   g | ]}t |tr|qS r.   )re   r   )r   r   r.   r.   r/   r     s    z&Legend.get_patches.<locals>.<listcomp>)r   ri   )r,   r.   r.   r/   get_patches  s    zLegend.get_patchesc             C   s   t d| jS )z7Return a list of `~.text.Text` instances in the legend.ZText)r   rh   )r,   r.   r.   r/   	get_texts  s    zLegend.get_textsc             C   s|   | j j| |r.| j jd | j d n| j jd | j d |dk	rrt|trdtf |}| j j| d| _dS )zk
        Set the legend title. Fontproperties can be optionally set
        with *prop* parameter.
        TFN)	rj   r   Zset_textZset_visiblere   rf   r	   Zset_fontpropertiesr   )r,   r   rd   r.   r.   r/   r     s    

zLegend.set_titlec             C   s   | j jS )z1Return the `.Text` instance for the legend title.)rj   r   )r,   r.   r.   r/   	get_title  s    zLegend.get_titlec             C   s   |dkr| j j}| jj|dS )zReturn extent of the legend.N)r   )r|   Z_cachedRendererr+   r   )r,   r   r.   r.   r/   r     s    zLegend.get_window_extentc             C   s   | j |S )a  
        Like `.Legend.get_window_extent`, but uses the box for the legend.

        Parameters
        ----------
        renderer : `.RendererBase` instance
            renderer that will be used to draw the figures (i.e.
            ``fig.canvas.get_renderer()``)

        Returns
        -------
        `.BboxBase` : containing the bounding box in figure pixel co-ordinates.
        )r+   r   )r,   r   r.   r.   r/   get_tightbbox  s    zLegend.get_tightbboxc             C   s   | j S )z*Get whether the legend box patch is drawn.)r   )r,   r.   r.   r/   get_frame_on  s    zLegend.get_frame_onc             C   s   || _ d| _dS )zt
        Set whether the legend box patch is drawn.

        Parameters
        ----------
        b : bool
        TN)r   r   )r,   r   r.   r.   r/   r     s    zLegend.set_frame_onc             C   s   | j dkr| jjS | j S dS )z4Return the bbox that the legend will be anchored to.N)_bbox_to_anchorr~   r%   )r,   r.   r.   r/   r7     s    
zLegend.get_bbox_to_anchorc             C   s   |dkrd| _ dS t|tr$|| _ nZyt|}W n$ tk
rT   tdt| Y nX |dkrr|d |d ddg}tj| | _ |dkrt	| j
j}t| j || _ d| _dS )ab  
        Set the bbox that the legend will be anchored to.

        *bbox* can be

        - A `.BboxBase` instance
        - A tuple of ``(left, bottom, width, height)`` in the given transform
          (normalized axes coordinate if None)
        - A tuple of ``(left, bottom)`` where the width and height will be
          assumed to be zero.
        NzInvalid argument for bbox : %srD   r   r!   T)r   re   r   rv   r}   r)   ro   r   r   r   r~   r%   r   r   )r,   r%   r   r   r.   r.   r/   r:     s"    
zLegend.set_bbox_to_anchorc             C   s   |t ddkstt d\}}}}}	}
}}}}}|d|d|d|	d|
d|d|d|d	|d
|di
}|| }|| j}|| j | }|j||d}|j|jfS )a  
        Place the *bbox* inside the *parentbbox* according to a given
        location code. Return the (x,y) coordinate of the bbox.

        - loc: a location code in range(1, 11).
          This corresponds to the possible values for self._loc, excluding
          "best".

        - bbox: bbox to be placed, display coordinate units.
        - parentbbox: a parent box which will contain the bbox. In
            display coordinates.
        r!      ZNEZNWZSWZSEEWSNC)	container)	ranger   r   rg   Zpaddedr^   Zanchoredr   r   )r,   r$   r%   Z
parentbboxr   ZBESTZURZULZLLZLRRZCLZCRZLCZUCr   Zanchor_coefscr   r   Zanchored_boxr.   r.   r/   r   '  s"    zLegend._get_anchored_bboxc                s   j s
t \}}}}tdd|| |dkrT fddtdtjD }g }	xt|D ]x\}
\}}t||||d}	|	| 
| tfdd|D  }|dkr||fS |	||
||ff qbW t|	\}}\}}||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 r.   )r   r7   )r   r   )r%   r   r,   r.   r/   r   X  s   z.Legend._find_best_position.<locals>.<listcomp>r!   c             3   s   | ]}|j  d dV  qdS )F)ZfilledN)Zintersects_bbox)r   line)	legendBoxr.   r/   	<genexpr>g  s   z-Legend._find_best_position.<locals>.<genexpr>)rz   r   r   r   r   r   rv   r   	enumerateZcount_containsZcount_overlapssumrt   r   )r,   r8   r9   r   ZconsiderZvertsr   r   r   Z
candidatesidxr   r   Zbadnessr_   r.   )r%   r   r   r,   r/   r   J  s"    
(zLegend._find_best_positionc             C   s   | j |S )N)r   r0   )r,   Zeventr.   r.   r/   r0   q  s    zLegend.containsFr$   c             C   s@   |r | j dkr:t| ||d| _ n| j dk	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
        -------
        If *state* is ``True`` this returns the `~.DraggableLegend` helper
        instance. Otherwise this returns ``None``.
        N)r-   )r   r#   Z
disconnect)r,   stater&   r-   r.   r.   r/   set_draggablet  s    


zLegend.set_draggablec             C   s
   | j dk	S )z@Return ``True`` if the legend is draggable, ``False`` otherwise.N)r   )r,   r.   r.   r/   get_draggable  s    zLegend.get_draggablec             C   s2   t ddd |dkr|   }| ||| | jS )a?  
        Set the draggable state -- if state is

          * None : toggle the current state

          * True : turn draggable on

          * False : turn draggable off

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

        The update parameter control which parameter of the legend changes
        when dragged. If update is "loc", the *loc* parameter of the legend
        is changed. If "bbox", the *bbox_to_anchor* parameter is changed.
        z2.2zLegend.draggable() is drepecated in favor of Legend.set_draggable(). Legend.draggable may be reintroduced as a property in future releases.)messageN)r   r   r   r   )r,   r   r&   r-   r.   r.   r/   	draggable  s    
zLegend.draggable)NNNTNNNNNNNNNNNr!   NNNNNNNNNNNN)N)T)N)N)N)N)Fr$   )NFr$   )Hr?   r@   rA   __doc__r   ZzorderrP   r   Zdedent_interpdr*   r   r   r   propertyr=   r   r   r   r   r    r"   ZHandlerStemr   ZHandlerErrorbarr
   ZHandlerLine2Dr   ZHandlerPatchr   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   r7   r:   r   r   r0   r   r   r   r.   r.   r.   r/   rC   3  s                               O
#

y4
	


##
'
!rC   c       	      c   s   g }x^| D ]V}||j |j |j |j 7 }t|dr
x*|jD ] }||j |j |j |j 7 }q<W q
W t }|dk	r| }|	| tj
}x,|D ]$}| }|dkr|||r|V  qW dS )zU
    Return a generator of artists that can be used as handles in
    a legend.

    	parasitesNZ
_nolegend_)r   r   r   Z
containershasattrr   rC   r   r   r-   r   	get_label)	axsr   Zhandles_originalr   Zaxxr   Zhas_handlerr   r   r.   r.   r/   _get_legend_handles  s"    

"

r   c             C   sN   g }g }x<t | |D ].}| }|r|ds|| || qW ||fS )zA
    Return handles and labels for legend, internal method.

    r_   )r   r   rp   rt   )r   r   r   r   r   r   r.   r.   r/   _get_legend_handles_labels  s    
r   )r   r   c            O   s<  t t}|di pi }d}|dk	s.|dk	r<|r<td |rX|rXtt|| \}}n|dk	rx|dkrxdd |D }n|dk	r|dkrdd tt| ||D }nt|dkrt	| |\}}|s|
d	 nbt|d
kr|\}dd tt| ||D }n4t|dkr(|dd \}}|dd }ntd||||fS )z
    Get the handles and labels from the calls to either ``figure.legend``
    or ``axes.legend``.

    ``axs`` is a list of axes (to get legend artists from)
    r   r.   NzMYou have mixed positional and keyword arguments, some input may be discarded.c             S   s   g | ]}|  qS r.   )r   )r   r   r.   r.   r/   r     s    z&_parse_legend_args.<locals>.<listcomp>c             S   s   g | ]\}}|qS r.   r.   )r   r   r   r.   r.   r/   r     s    r   z.No handles with labels found to put in legend.r!   c             S   s   g | ]\}}|qS r.   r.   )r   r   r   r.   r.   r/   r     s    rD   zInvalid arguments to legend.)loggingZ	getLoggerr?   getrq   rr   rn   r   rv   r   Zwarningr}   )r   r   r   argskwargslogZhandlersZ
extra_argsr.   r.   r/   _parse_legend_args  s2    

r  )N)N):r   r  rq   Znumpyrx   Z
matplotlibr   r   Zmatplotlib.artistr   r   Zmatplotlib.cbookr   r   r   Zmatplotlib.colorsZcolorsZmatplotlib.font_managerr	   Zmatplotlib.linesr
   Zmatplotlib.patchesr   r   r   r   Zmatplotlib.collectionsr   r   r   r   r   Zmatplotlib.transformsr   r   r   r   r   Zmatplotlib.offsetboxr   r   r   r   r   Zmatplotlib.containerr   r   r    r   r"   r#   rB   Zinterpdr-   rC   r   r   r  r.   r.   r.   r/   <module>   sB    ~       

