3
h>                 @   s   d Z ddlmZ ddlZddlZddlmZm	Z	 ddl
ZddljZddlZddlmZ ddlmZ ddlmZ dd	lmZ d
gZddddddddejdddddfdd
Zdd Zdd Zdd Zdd Zdd Zdd Z dd Z!dd Z"dS ) zTimeseries plotting functions.    )divisionN)statsinterpolate   )string_types)utils)
algorithms)color_palettetsplotZci_bandD   Ti  c       -         s\  d}t j|t |dkr tj }|dkr,i }t| tjr|}|}|dkrftjd| j	d}d}d}d}ndol|}|}t
| | j }nttj| } | jdkr| tjddtjf } n"| jdkr| ddddtjf } | j\}}}|dkrtj|}d}tj||| }d}|dkr tj|}n
tj|}d}t|d	r@|j}d
}tjtj|||}|dkrt|}d}ttrd}t|n,tj|}do|}t|d	r|j}nd}d}tj||| }|dkrd}n|}d}tjt| j |||d} t|tr|g}n|dkrg }t|ds.|g}dkrftj }t
||k rZtd|}n
t|d}nfttrfdd| | j D }n>yt|}W n. tk
r   tjj j!g| }Y nX d}xt"| j#|ddD ]\}\}}|j$|||}|j%j&j'tj(} d|krT|	|j&dd}!tj)|j&dd}"|!|" |!|" fg}#|j& n&t*j+|j&|
d|	d  fdd|D }#|	|j&dd}$|| x|D ]}%|%dkrqyt, d|%  }&W n" t-k
r   td|% Y nX |dk	rd|%kr}'t|t
|j&t|| |j& |$|d}(x |#D ]})|)|(d< |&f |( q$W |dk	rd|%kr|'qW |j.d|rndnd  |j/d!|rd"nd}*|j.d#|* |r|nd$}+|j0| |$f|+d%| qW |dkrt1d&|j2| j3 | j4  | d | d  },|s|j2| j3 |, | j4 |,  |dk	r0|j5| |dk	rD|j6| |rX|j7d|d' |S )(a  Plot one or more timeseries with flexible representation of uncertainty.

    This function is intended to be used with data where observations are
    nested within sampling units that were measured at multiple timepoints.

    It can take data specified either as a long-form (tidy) DataFrame or as an
    ndarray with dimensions (unit, time) The interpretation of some of the
    other parameters changes depending on the type of object passed as data.

    Parameters
    ----------
    data : DataFrame or ndarray
        Data for the plot. Should either be a "long form" dataframe or an
        array with dimensions (unit, time, condition). In both cases, the
        condition field/dimension is optional. The type of this argument
        determines the interpretation of the next few parameters. When
        using a DataFrame, the index has to be sequential.
    time : string or series-like
        Either the name of the field corresponding to time in the data
        DataFrame or x values for a plot when data is an array. If a Series,
        the name will be used to label the x axis.
    unit : string
        Field in the data DataFrame identifying the sampling unit (e.g.
        subject, neuron, etc.). The error representation will collapse over
        units at each time/condition observation. This has no role when data
        is an array.
    value : string
        Either the name of the field corresponding to the data values in
        the data DataFrame (i.e. the y coordinate) or a string that forms
        the y axis label when data is an array.
    condition : string or Series-like
        Either the name of the field identifying the condition an observation
        falls under in the data DataFrame, or a sequence of names with a length
        equal to the size of the third dimension of data. There will be a
        separate trace plotted for each condition. If condition is a Series
        with a name attribute, the name will form the title for the plot
        legend (unless legend is set to False).
    err_style : string or list of strings or None
        Names of ways to plot uncertainty across units from set of
        {ci_band, ci_bars, boot_traces, boot_kde, unit_traces, unit_points}.
        Can use one or more than one method.
    ci : float or list of floats in [0, 100] or "sd" or None
        Confidence interval size(s). If a list, it will stack the error plots
        for each confidence interval. If ``"sd"``, show standard deviation of
        the observations instead of boostrapped confidence intervals. Only
        relevant for error styles with "ci" in the name.
    interpolate : boolean
        Whether to do a linear interpolation between each timepoint when
        plotting. The value of this parameter also determines the marker
        used for the main plot traces, unless marker is specified as a keyword
        argument.
    color : seaborn palette or matplotlib color name or dictionary
        Palette or color for the main plots and error representation (unless
        plotting by unit, which can be separately controlled with err_palette).
        If a dictionary, should map condition name to color spec.
    estimator : callable
        Function to determine central tendency and to pass to bootstrap
        must take an ``axis`` argument.
    n_boot : int
        Number of bootstrap iterations.
    err_palette : seaborn palette
        Palette name or list of colors used when plotting data for each unit.
    err_kws : dict, optional
        Keyword argument dictionary passed through to matplotlib function
        generating the error plot,
    legend : bool, optional
        If ``True`` and there is a ``condition`` variable, add a legend to
        the plot.
    ax : axis object, optional
        Plot in given axis; if None creates a new figure
    kwargs :
        Other keyword arguments are passed to main plot() call

    Returns
    -------
    ax : matplotlib axis
        axis with plot data

    Examples
    --------

    Plot a trace with translucent confidence bands:

    .. plot::
        :context: close-figs

        >>> import numpy as np; np.random.seed(22)
        >>> import seaborn as sns; sns.set(color_codes=True)
        >>> x = np.linspace(0, 15, 31)
        >>> data = np.sin(x) + np.random.rand(10, 31) + np.random.randn(10, 1)
        >>> ax = sns.tsplot(data=data)

    Plot a long-form dataframe with several conditions:

    .. plot::
        :context: close-figs

        >>> gammas = sns.load_dataset("gammas")
        >>> ax = sns.tsplot(time="timepoint", value="BOLD signal",
        ...                 unit="subject", condition="ROI",
        ...                 data=gammas)

    Use error bars at the positions of the observations:

    .. plot::
        :context: close-figs

        >>> ax = sns.tsplot(data=data, err_style="ci_bars", color="g")

    Don't interpolate between the observations:

    .. plot::
        :context: close-figs

        >>> import matplotlib.pyplot as plt
        >>> ax = sns.tsplot(data=data, err_style="ci_bars", interpolate=False)

    Show multiple confidence bands:

    .. plot::
        :context: close-figs

        >>> ax = sns.tsplot(data=data, ci=[68, 95], color="m")

    Show the standard deviation of the observations:

    .. plot::
        :context: close-figs

        >>> ax = sns.tsplot(data=data, ci="sd")

    Use a different estimator:

    .. plot::
        :context: close-figs

        >>> ax = sns.tsplot(data=data, estimator=np.median)

    Show each bootstrap resample:

    .. plot::
        :context: close-figs

        >>> ax = sns.tsplot(data=data, err_style="boot_traces", n_boot=500)

    Show the trace from each sampling unit:


    .. plot::
        :context: close-figs

        >>> ax = sns.tsplot(data=data, err_style="unit_traces")

    zThe `tsplot` function is deprecated and will be removed in a future release. Please update your code to use the new `lineplot` function.Nr   )indexFT   unitnametimez.Must have condition names if using color dict.condvalue)r   r   r   r   __iter__Zhusl)Zn_colorsc                s   g | ]} | qS  r   ).0c)colorr   5/tmp/pip-build-riy7u7_k/seaborn/seaborn/timeseries.py
<listcomp>  s    ztsplot.<locals>.<listcomp>)sortsdr   )axis)n_bootr   funcc                s   g | ]}t j |d dqS )r   )r   )r   ci)r   v)	boot_datar   r   r   4  s    z_plot_%sz%s is not a valid err_style)axxdatar!   central_datar   err_kwsr   marker ols-Z	linestyle
_nolegend_)r   labelzInvalid input data for tsplot.)loctitle)8warningswarnUserWarningpltZgca
isinstancepdZ	DataFrameZSeriesr   lenuniquenpZasarrayndimZnewaxisshapeZarangerepeathasattrr   Ztilerangedict
ValueErrorZravelr   r   Zget_color_cycler	   mplcolorsZcolorConverterto_rgb	enumerategroupbyZpivotcolumnsvaluesZastypefloatZstdalgoZ	bootstrapglobalsKeyError
setdefaultpopplotRuntimeErrorZset_xlimminmaxZ
set_xlabelZ
set_ylabellegend)-r$   r   r   	conditionr   Z	err_styler   r   r   Z	estimatorr   Zerr_paletter&   rQ   r"   kwargsmsgZxlabelZylabelZlegend_nameZn_condZn_unitZn_timeZunitstimesZcondserrZcurrent_paletterA   r   r   Zdf_cr#   Zestr   Zcisr%   styleZ	plot_funcZ
orig_colorZplot_kwargsZci_ir*   r-   Zx_diffr   )r!   r   r   r
      s      













$








 




c             K   s6   |\}}d|krd|d< | j |||fd|i| dS )z9Plot translucent error bands around the central tendancy.alphag?Z	facecolorN)Zfill_between)r"   r#   r   r   r&   rS   lowhighr   r   r   _plot_ci_bandx  s    r[   c             K   sH   xBt |||jD ]0\}}\}	}
| j||g|	|
gf|dd| qW dS )z#Plot error bars at each data point.round)r   Zsolid_capstyleN)zipTrM   )r"   r#   r%   r   r   r&   rS   Zx_iZy_irY   rZ   r   r   r   _plot_ci_bars  s    r_   c             K   sN   |j dd |j dd d|kr.|jd|d< | j||jf|dd| dS )zPlot 250 traces from bootstrap.rX   g      ?Z	linewidthZlwr,   )r   r-   N)rK   rL   rM   r^   )r"   r#   r!   r   r&   rS   r   r   r   _plot_boot_traces  s
    r`   c       	      K   s   t |trPd|krd|d< x`t|D ]&\}}| j||f|| dd| q$W n,d|kr`d|d< | j||jf|dd| dS )z7Plot a trace for each observation in the original data.rX   g      ?r,   )r   r-   g?N)r4   listrC   rM   r^   )	r"   r#   r$   r   r   r&   rS   iobsr   r   r   _plot_unit_traces  s    
$rd   c             K   sl   t |trFx\t|D ],\}}| j||df|| dddd| qW n"| j||jdf|dddd| dS )z)Plot each original data point discretely.r)   g?   r,   )r   rX   Z
markersizer-   g      ?N)r4   ra   rC   rM   r^   )r"   r#   r$   r   r&   rS   rb   rc   r   r   r   _plot_unit_points  s    
rf   c             K   s    |j d t| |||f| dS )z?Plot the kernal density estimate of the bootstrap distribution.r$   N)rL   _ts_kde)r"   r#   r!   r   rS   r   r   r   _plot_boot_kde  s    
rh   c             K   s   t | |||f| dS )z1Plot the kernal density estimate over the sample.N)rg   )r"   r#   r$   r   rS   r   r   r   _plot_unit_kde  s    ri   c             K   s   g }|j  |j  }}tj||d}tj||}	|	tj|j  |j d}
x(|
jD ]}tjj	|}|j
|| qRW tj|}tjj j|}tj|jd |jd df}||ddddddf< ||jdd }d||dk< ||dddddf< | j|dd	|j  |j ||fd
dd dS )z@Upsample over time and plot a KDE of the bootstrap distribution.d   r   r   re   N   )r   Zspline16r   autolower)interpolationZzorderZextentZaspectorigin)rO   rP   r8   Zlinspacer   Zinterp1dr^   r   ZkdeZgaussian_kdeappendZ	transposer@   rA   ZColorConverterrB   zerosr:   Zimshow)r"   r#   r$   r   rS   Zkde_dataZy_minZy_maxZy_valsZ	upsamplerZdata_upsampleZpt_dataZpt_kdeZrgbimgr   r   r   rg     s$    

rg   )#__doc__
__future__r   Znumpyr8   Zpandasr5   Zscipyr   r   Z
matplotlibr@   Zmatplotlib.pyplotZpyplotr3   r0   Zexternal.sixr   r(   r   r   rH   Zpalettesr	   __all__Zmeanr
   r[   r_   r`   rd   rf   rh   ri   rg   r   r   r   r   <module>   s4   

  b	