B
    A—W[K  ã               @   s’  d Z ddlmZmZ ddlZddlZddlZddlm	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 ddlmZ eejƒd	kZeejƒd
kZddddddgZdd„ Zdd„ Z dd„ Z!dBdd„Z"dd„ Z#dd„ Z$dCdd„Z%dd„ Z&dDd!d„Z'd"d#„ Z(d$d%„ Z)dEd&d'„Z*dFd)d*„Z+d+d,„ Z,d-d.„ Z-d/d„ Z.dGd0d1„Z/dHd2d„Z0d3d4„ Z1d5d6„ Z2dId7d8„Z3d9d:„ Z4d;d<„ Z5d=d>„ Z6dJd@dA„Z7dS )Kz)Small plotting-related utility functions.é    )Úprint_functionÚdivisionN)Ústatsé   )ÚurlopenÚurlretrieve)ÚHTTPException)ÚLooseVersionz0.15z1.5.0Ú
desaturateÚsaturateÚset_hls_valuesÚdespineÚget_dataset_namesÚload_datasetc             C   s   | t  | ¡ S )a  Helper method for removing NA values from array-like.

    Parameters
    ----------
    arr : array-like
        The array-like from which to remove NA values.

    Returns
    -------
    clean_arr : array-like
        The original array with NA values removed.

    )ÚpdÚnotnull)Zarr© r   ú,lib/python3.7/site-packages/seaborn/utils.pyÚ	remove_na   s    r   c             O   s.   y| j ||ŽS  tk
r(   | j||ŽS X dS )z=Wrapper to handle different pandas sorting API pre/post 0.17.N)Zsort_valuesÚAttributeErrorÚsort)ÚdfÚargsÚkwargsr   r   r   Úsort_df*   s    r   c       	      C   sv   t  | ¡ dd¡} t  |¡}g }xDtt  | ¡ƒD ]2\}\}}|| }|| }|| }| ||g¡ q0W t  |¡j}|S )a‚  Convert intervals to error arguments relative to plot heights.

    Parameters
    ----------
    cis: 2 x n sequence
        sequence of confidence interval limits
    heights : n sequence
        sequence of plot heights

    Returns
    -------
    errsize : 2 x n array
        sequence of error size relative to height values in correct
        format as argument for plt.bar

    é   éÿÿÿÿ)	ÚnpZ
atleast_2dZreshapeZ
atleast_1dÚ	enumerateZ	transposeÚappendÚasarrayÚT)	ZcisZheightsZerrsizeÚiZlowZhighÚhZelowZehighr   r   r   Úci_to_errsize2   s    
r$   é
   c             C   s>   t  | |¡\}}|| ¡  }|d |d  }|dd… ||fS )aK  Return arguments to plt.bar for pmf-like histogram of an array.

    Parameters
    ----------
    a: array-like
        array to make histogram of
    bins: int
        number of bins

    Returns
    -------
    x: array
        left x position of bars
    h: array
        height of bars
    w: float
        width of bars

    r   r   Nr   )r   Z	histogramÚsum)ÚaZbinsÚnÚxr#   Úwr   r   r   Úpmf_histP   s    r+   c             C   sT   d|  krdksn t dƒ‚tj | ¡}tj|Ž \}}}||9 }t |||¡}|S )al  Decrease the saturation channel of a color by some percent.

    Parameters
    ----------
    color : matplotlib color
        hex, rgb-tuple, or html color name
    prop : float
        saturation channel of color will be multiplied by this value

    Returns
    -------
    new_color : rgb tuple
        desaturated color code in RGB tuple representation

    r   r   zprop must be between 0 and 1)Ú
ValueErrorÚmplcolÚcolorConverterÚto_rgbÚcolorsysÚ
rgb_to_hlsÚ
hls_to_rgb)ÚcolorZpropÚrgbr#   ÚlÚsZ	new_colorr   r   r   r
   j   s    c             C   s   t | ddS )a  Return a fully saturated color with the same hue.

    Parameters
    ----------
    color :  matplotlib color
        hex, rgb-tuple, or html color name

    Returns
    -------
    new_color : rgb tuple
        saturated color code in RGB tuple representation

    r   )r6   )r   )r3   r   r   r   r      s    c             C   sT   t j | ¡}ttj|Ž ƒ}x*t|||gƒD ]\}}|dk	r*|||< q*W tj|Ž }|S )an  Independently manipulate the h, l, or s channels of a color.

    Parameters
    ----------
    color : matplotlib color
        hex, rgb-tuple, or html color name
    h, l, s : floats between 0 and 1, or None
        new values for each channel in hls space

    Returns
    -------
    new_color : rgb tuple
        new color code in RGB tuple representation

    N)r-   r.   r/   Úlistr0   r1   r   r2   )r3   r#   r5   r6   r4   Zvalsr"   Úvalr   r   r   r   ž   s    
c             K   s(   t  ¡ }|j| f|Ž |j|f|Ž dS )zGrab current axis and label it.N)ÚpltZgcaZ
set_xlabelZ
set_ylabel)ZxlabelZylabelr   Úaxr   r   r   Úaxlabel¹   s    r;   TFc          
   C   sÚ  | dkr|dkrt  ¡ j}n| dk	r,| j}n|dk	r:|g}x˜|D ]Ž}	xrdD ]j}
tƒ |
  }|	j|
  |¡ |dk	rN|rNy| |
d¡}W n tk
r¢   |}Y nX t|	j|
 d|fƒ qNW |r4|s4t	dd„ |	j
jD ƒƒ}t	dd„ |	j
jD ƒƒ}|	j
 d¡ x|	j
jD ]}||_q
W x|	j
jD ]}||_q$W |r¬|s¬t	d	d„ |	jjD ƒƒ}t	d
d„ |	jjD ƒƒ}|	j d¡ x|	jjD ]}||_q‚W x|	jjD ]}||_qœW |rB|	 ¡ }|jrBt |t|	 ¡ ƒk|¡d }t |t|	 ¡ ƒk|¡d }|	jd  ||¡ |	jd  ||¡ | ||k¡}| ||k¡}|	 |¡ |	 ¡ }|jrBt |t|	 ¡ ƒk|¡d }t |t|	 ¡ ƒk|¡d }|	jd  ||¡ |	jd  ||¡ | ||k¡}| ||k¡}|	 |¡ qBW dS )aì  Remove the top and right spines from plot(s).

    fig : matplotlib figure, optional
        Figure to despine all axes of, default uses current figure.
    ax : matplotlib axes, optional
        Specific axes object to despine.
    top, right, left, bottom : boolean, optional
        If True, remove that spine.
    offset : int or dict, optional
        Absolute distance, in points, spines should be moved away
        from the axes (negative values move spines inward). A single value
        applies to all spines; a dict can be used to set offset values per
        side.
    trim : bool, optional
        If True, limit spines to the smallest and largest major tick
        on each non-despined axis.

    Returns
    -------
    None

    N)ÚtopÚrightÚleftÚbottomr   Zoutwardc             s   s   | ]}|j V  qd S )N)Útick1On)Ú.0Útr   r   r   ú	<genexpr>î   s    zdespine.<locals>.<genexpr>c             s   s   | ]}|j V  qd S )N)r@   )rA   rB   r   r   r   rC   ï   s    r=   c             s   s   | ]}|j V  qd S )N)r@   )rA   rB   r   r   r   rC   ÷   s    c             s   s   | ]}|j V  qd S )N)r@   )rA   rB   r   r   r   rC   ø   s    r<   r   r?   r>   )r9   ZgcfÚaxesÚlocalsZspinesZset_visibleÚgetr   Ú_set_spine_positionÚanyZyaxisZ
majorTicksZ
minorTicksZset_ticks_positionZtick2OnZxaxisZ
get_xticksÚsizer   ÚcompressÚminZget_xlimÚmaxZ
set_boundsZ
set_xticksZ
get_yticksZget_ylimZ
set_yticks)Zfigr:   r<   r=   r>   r?   ÚoffsetZtrimrD   Zax_iZsideZ
is_visibler8   Zmaj_onZmin_onrB   ZxticksZ	firsttickZlasttickZnewticksZyticksr   r   r   r   À   sn    






c             C   s8   | j }|dk	r|j}|j|_|  |¡ |dk	r4||_dS )aL  
    Set the spine's position without resetting an associated axis.

    As of matplotlib v. 1.0.0, if a spine has an associated axis, then
    spine.set_position() calls axis.cla(), which resets locators, formatters,
    etc.  We temporarily replace that call with axis.reset_ticks(), which is
    sufficient for our purposes.
    N)ÚaxisÚclaZreset_ticksZset_position)ZspineZpositionrN   rO   r   r   r   rG     s    	
rG   c             C   sB   t |  ¡ ||  |d ƒ}t|   ¡ ||  |d ƒ}t |||¡S )z0Establish support for a kernel density estimate.r   r   )rL   rK   r   Zlinspace)ÚdataZbwZgridsizeZcutZclipZsupport_minZsupport_maxr   r   r   Ú_kde_support,  s    rQ   c             C   s–   g }yt |ƒ}W n tk
r.   |g}d}Y nX xJt|ƒD ]>\}}|dkr\t |  ¡ |¡}nt tj|| |¡}| |¡ q:W t 	|¡}|s’| 
¡ }|S )aÆ  Like scoreatpercentile but can take and return array of percentiles.

    Parameters
    ----------
    a : array
        data
    pcts : sequence of percentile values
        percentile or percentiles to find score at
    axis : int or None
        if not None, computes scores over this axis

    Returns
    -------
    scores: array
        array of scores at requested percentiles
        first dimension is length of object passed to ``pcts``

    r   N)ÚlenÚ	TypeErrorr   r   ÚscoreatpercentileZravelr   Zapply_along_axisr   r    Zsqueeze)r'   ZpctsrN   Zscoresr(   r"   ÚpZscorer   r   r   Úpercentiles3  s    

rV   é_   c             C   s$   d|d  d|d  f}t | ||ƒS )z2Return a percentile range from an array of values.é2   r   )rV   )r'   ZwhichrN   rU   r   r   r   ÚciX  s    rY   c             C   s4   | dk rdS | dk rdS | dk r$dS | dk r0dS d	S )
z?Return a R-style significance string corresponding to p values.gü©ñÒMbP?z***g{®Gáz„?z**gš™™™™™©?Ú*gš™™™™™¹?Ú.Ú r   )rU   r   r   r   Ú	sig_stars^  s    r]   c             C   s*   t  | ¡} t | d¡}t | d¡}|| S )z*Calculate the IQR for an array of numbers.é   éK   )r   r    r   rT   )r'   Zq1Zq3r   r   r   Úiqrk  s    
r`   c              C   s6   ddl m}  tdƒ}| |ƒ}dd„ | dddi¡D ƒS )	z?Report available example datasets, useful for reporting issues.r   )ÚBeautifulSoupz(https://github.com/mwaskom/seaborn-data/c             S   s&   g | ]}|j  d ¡r|j  d d¡‘qS )z.csvr\   )ÚtextÚendswithÚreplace)rA   r5   r   r   r   ú
<listcomp>z  s   z%get_dataset_names.<locals>.<listcomp>r'   Úclasszjs-navigation-open)Zbs4ra   r   Zfind_all)ra   ZhttpZgh_listr   r   r   r   s  s
    c             C   sF   | dkr t j dt j dd¡¡} t j | ¡} t j | ¡sBt  | ¡ | S )aC  Return the path of the seaborn data directory.

    This is used by the ``load_dataset`` function.

    If the ``data_home`` argument is not specified, the default location
    is ``~/seaborn-data``.

    Alternatively, a different default location can be specified using the
    environment variable ``SEABORN_DATA``.
    NZSEABORN_DATAú~zseaborn-data)ÚosÚenvironrF   ÚpathÚjoinÚ
expanduserÚexistsÚmakedirs)Ú	data_homer   r   r   Úget_data_home  s    
rp   c             K   s¢  d}|  | ¡}|rFtj t|ƒtj |¡¡}tj |¡sBt||ƒ |}tj	|f|Ž}|j
d  ¡  ¡ rt|j
dd… }ts||S | dkrèt |d dddd	g¡|d< t |d
 ddg¡|d
< t |d ddg¡|d< t |d ddg¡|d< | dkrt |d |j ¡ ¡|d< | dkrbt |d dddg¡|d< t |d dddg¡|d< t |d ddg¡|d< | d kržt |d! d"d#d$g¡|d!< t |d% td&ƒ¡|d%< |S )'a:  Load a dataset from the online repository (requires internet).

    Parameters
    ----------
    name : str
        Name of the dataset (`name`.csv on
        https://github.com/mwaskom/seaborn-data).  You can obtain list of
        available datasets using :func:`get_dataset_names`
    cache : boolean, optional
        If True, then cache data locally and use the cache on subsequent calls
    data_home : string, optional
        The directory in which to cache data. By default, uses ~/seaborn-data/
    kws : dict, optional
        Passed to pandas.read_csv

    zDhttps://raw.githubusercontent.com/mwaskom/seaborn-data/master/{}.csvr   NZtipsZdayZThurZFriZSatZSunZsexZMaleZFemaleZtimeZLunchZDinnerZsmokerZYesZNoZflightsÚmonthZexercisez1 minz15 minz30 minZkindÚrestZwalkingZrunningZdietzno fatzlow fatZtitanicrf   ZFirstZSecondZThirdZdeckZABCDEFG)Úformatrh   rj   rk   rp   Úbasenamerm   r   r   Zread_csvZilocZisnullÚallÚpandas_has_categoricalsZCategoricalrq   Úuniquer7   )ÚnameÚcachero   Zkwsrj   Ú	full_pathÚ
cache_pathr   r   r   r   r   “  s8    




c                sN   | sdS y,dd„ | D ƒ‰ ‡ fdd„ˆ D ƒ}t |ƒdkS  tk
rH   dS X dS )záReturn a boolean for whether the list of ticklabels have overlaps.

    Parameters
    ----------
    labels : list of ticklabels

    Returns
    -------
    overlap : boolean
        True if any of the labels overlap.

    Fc             S   s   g | ]}|  ¡ ‘qS r   )Zget_window_extent)rA   r5   r   r   r   re   Ý  s    z+axis_ticklabels_overlap.<locals>.<listcomp>c                s   g | ]}|  ˆ ¡‘qS r   )Zcount_overlaps)rA   Úb)Úbboxesr   r   re   Þ  s    r   N)rL   ÚRuntimeError)ÚlabelsZoverlapsr   )r}   r   Úaxis_ticklabels_overlapÍ  s    r€   c             C   s   t |  ¡ ƒt |  ¡ ƒfS )zôReturn booleans for whether the x and y ticklabels on an Axes overlap.

    Parameters
    ----------
    ax : matplotlib Axes

    Returns
    -------
    x_overlap, y_overlap : booleans
        True when the labels on that axis overlap.

    )r€   Zget_xticklabelsZget_yticklabels)r:   r   r   r   Úaxes_ticklabels_overlapå  s    
r   c             C   s¾   |dkr¶t | dƒr| j}ny| jj}W n‚ ttfk
r¨   y|  ¡ }W n tk
rd   t | ¡}Y nX y t | ¡ 	tj
¡ t |¡}W n ttfk
r¢   |}Y nX Y nX ttj|ƒ}t|ƒS )aÔ  Return a list of unique data values.

    Determine an ordered list of levels in ``values``.

    Parameters
    ----------
    values : list, array, Categorical, or Series
        Vector of "categorical" values
    order : list-like, optional
        Desired order of category levels to override the order determined
        from the ``values`` object.

    Returns
    -------
    order : list
        Ordered list of category levels not including null values.

    NÚ
categories)Úhasattrr‚   ÚcatrS   r   rw   r   r   r    ZastypeÚfloatr   r,   Úfilterr   r7   )ÚvaluesÚorderr   r   r   Úcategorical_orderö  s"    
r‰   c              C   s<   t r2tjd } ydd„ | D ƒS  tk
r0   Y nX tjd S )z@Return the list of colors in the current matplotlib color cycle.zaxes.prop_cyclec             S   s   g | ]}|d  ‘qS )r3   r   )rA   r)   r   r   r   re   %  s    z#get_color_cycle.<locals>.<listcomp>zaxes.color_cycle)Ú
mpl_ge_150ÚmplZrcParamsÚKeyError)Zcylr   r   r   Úget_color_cycle  s    
r   c             C   sr   t jj | ¡dd…dd…f }t |dk|d |d d d ¡}| dd	d
g¡}y| ¡ S  tk
rl   |S X dS )a  Calculate the relative luminance of a color according to W3C standards

    Parameters
    ----------
    color : matplotlib color or sequence of matplotlib colors
        Hex code, rgb-tuple, or html color name.

    Returns
    -------
    luminance : float(s) between 0 and 1

    Né   g#Æ‚¤?g×£p=
×)@g)\Âõ(¬?gáz®Gáð?g333333@g¼–z6Ë?g¥,Cëâæ?g]mÅþ²{²?)	r‹   Úcolorsr.   Zto_rgba_arrayr   ÚwhereÚdotÚitemr,   )r3   r4   Zlumr   r   r   Úrelative_luminance,  s    "r“   c             C   s€   t | tƒr*y
|  d¡S  tk
r(   | S X y t | tƒr:| S |  ¡  d¡S W n0 tk
rz   t | tƒrn|  d¡S |  ¡ S Y nX dS )ap  Return a Unicode string representing a Python object.

    Unicode strings (i.e. type ``unicode`` in Python 2.7 and type ``str`` in
    Python 3.x) are returned unchanged.

    Byte strings (i.e. type ``str`` in Python 2.7 and type ``bytes`` in
    Python 3.x) are returned as UTF-8-encoded strings.

    For other objects, the method ``__str__()`` is called, and the result is
    returned as a UTF-8-encoded string.

    Parameters
    ----------
    obj : object
        Any Python object

    Returns
    -------
    s : unicode (Python 2.7) / str (Python 3.x)
        UTF-8-encoded string representation of ``obj``
    zutf-8N)Ú
isinstanceÚstrÚdecoder   ZunicodeÚ__str__Ú	NameErrorÚbytes)Úobjr   r   r   Úto_utf8B  s    




r›   úhttps://google.comc                s0   ddl ‰ ˆdkr‡fdd„S ‡ ‡‡fdd„}|S )z”
    Decorator that will skip a test if `url` is unreachable.

    Parameters
    ----------
    t : function, optional
    url : str, optional
    r   Nc                s   t | ˆ dS )N)Úurl)Ú_network)r)   )r   r   r   Ú<lambda>€  s    z_network.<locals>.<lambda>c           	      sD   yt ˆƒ}W n  ttfk
r,   ˆ  ¡ ‚Y nX | ¡  ˆ| |ŽS d S )N)r   ÚIOErrorr   ZSkipTestÚclose)r   r   Úf)ÚnoserB   r   r   r   Úwrapper‚  s    z_network.<locals>.wrapper)r£   )rB   r   r¤   r   )r£   rB   r   r   rž   t  s
    		rž   )r%   )NNN)NNTTFFNF)N)rW   N)N)TN)N)Nrœ   )8Ú__doc__Z
__future__r   r   r0   rh   Znumpyr   Zscipyr   Zpandasr   Z
matplotlibr‹   Zmatplotlib.colorsr   r-   Zmatplotlib.pyplotZpyplotr9   Z!external.six.moves.urllib.requestr   r   Zexternal.six.moves.http_clientr   Zdistutils.versionr	   Ú__version__rv   rŠ   Ú__all__r   r   r$   r+   r
   r   r   r;   r   rG   rQ   rV   rY   r]   r`   r   rp   r   r€   r   r‰   r   r“   r›   rž   r   r   r   r   Ú<module>   sT   

#
 
Y
%


:
'2