U
    Ãmœdè  ã                
   @   sb   d Z ddlmZ ddlZddlmZ ddlm  m	Z	 ej
dddddddddf
dd„Zd	d
„ ZdS )z@
Authors:    Josef Perktold, Skipper Seabold, Denis A. Engemann
é    )ÚlrangeN)ÚrainbowÚbÚbestc                 K   s  ddl m} t |¡\}}|p(t|ddƒ}d|j|f }|pFt| ddƒ}|pVt|ddƒ}| |¡ | |¡ d }}t| d t	ƒr¶d	d
„ t
 | ¡D ƒ}tt|ƒƒ}t| tt||ƒƒƒ} |t| ||d�ƒ}| ddg¡ |¡ ¡ }t|d  ¡ ƒ}|
dk�rdg| n|
}
|	dk�rdg| n|	}	|dk�r2t|ƒn|}t|
ƒ|k�rLtdƒ‚t|	ƒ|k�rbtdƒ‚t|ƒ|k�rxtdƒ‚|dk�sŒ|dk�rðt| d¡ƒD ]R\}\}}t	|d jd ƒ}|j|d |d f|| |	| ||
| dœ|—Ž �qšnð|dk�s|dk�rbt| d¡ƒD ]L\}\}}t	|d jd ƒ}|j|d |d f|| ||
| dœ|—Ž �qn~|dk�sv|dk�rÔt| d¡ƒD ]L\}\}}t	|d jd ƒ}|j|d |d f|| ||	| dœ|—Ž �q„ntd| ƒ‚|j||d� | d¡ t||gƒ�r| |¡ | |¡ |S )a  
    Interaction plot for factor level statistics.

    Note. If categorial factors are supplied levels will be internally
    recoded to integers. This ensures matplotlib compatibility. Uses
    a DataFrame to calculate an `aggregate` statistic for each level of the
    factor or group given by `trace`.

    Parameters
    ----------
    x : array_like
        The `x` factor levels constitute the x-axis. If a `pandas.Series` is
        given its name will be used in `xlabel` if `xlabel` is None.
    trace : array_like
        The `trace` factor levels will be drawn as lines in the plot.
        If `trace` is a `pandas.Series` its name will be used as the
        `legendtitle` if `legendtitle` is None.
    response : array_like
        The reponse or dependent variable. If a `pandas.Series` is given
        its name will be used in `ylabel` if `ylabel` is None.
    func : function
        Anything accepted by `pandas.DataFrame.aggregate`. This is applied to
        the response variable grouped by the trace levels.
    ax : axes, optional
        Matplotlib axes instance
    plottype : str {'line', 'scatter', 'both'}, optional
        The type of plot to return. Can be 'l', 's', or 'b'
    xlabel : str, optional
        Label to use for `x`. Default is 'X'. If `x` is a `pandas.Series` it
        will use the series names.
    ylabel : str, optional
        Label to use for `response`. Default is 'func of response'. If
        `response` is a `pandas.Series` it will use the series names.
    colors : list, optional
        If given, must have length == number of levels in trace.
    markers : list, optional
        If given, must have length == number of levels in trace
    linestyles : list, optional
        If given, must have length == number of levels in trace.
    legendloc : {None, str, int}
        Location passed to the legend command.
    legendtitle : {None, str}
        Title of the legend.
    **kwargs
        These will be passed to the plot command used either plot or scatter.
        If you want to control the overall plotting options, use kwargs.

    Returns
    -------
    Figure
        The figure given by `ax.figure` or a new instance.

    Examples
    --------
    >>> import numpy as np
    >>> np.random.seed(12345)
    >>> weight = np.random.randint(1,4,size=60)
    >>> duration = np.random.randint(1,3,size=60)
    >>> days = np.log(np.random.randint(1,30, size=60))
    >>> fig = interaction_plot(weight, duration, days,
    ...             colors=['red','blue'], markers=['D','^'], ms=10)
    >>> import matplotlib.pyplot as plt
    >>> plt.show()

    .. plot::

       import numpy as np
       from statsmodels.graphics.factorplots import interaction_plot
       np.random.seed(12345)
       weight = np.random.randint(1,4,size=60)
       duration = np.random.randint(1,3,size=60)
       days = np.log(np.random.randint(1,30, size=60))
       fig = interaction_plot(weight, duration, days,
                   colors=['red','blue'], markers=['D','^'], ms=10)
       import matplotlib.pyplot as plt
       #plt.show()
    r   )Ú	DataFrameÚnameÚresponsez%s of %sÚXÚTraceNc                 S   s   g | ]}|‘qS © r   )Ú.0Úlr   r   úY/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/statsmodels/graphics/factorplots.pyÚ
<listcomp>l   s     z$interaction_plot.<locals>.<listcomp>)ÚxÚtracer   r   r   ú-Ú.z(Must be a linestyle for each trace levelz%Must be a marker for each trace levelz$Must be a color for each trace levelZbothr   )ÚcolorÚmarkerÚlabelÚ	linestyleÚliner   )r   r   r   ÚscatterÚs)r   r   r   zPlot type %s not understood)ÚlocÚtitlegš™™™™™¹?)Úpandasr   ÚutilsZcreate_mpl_axÚgetattrÚ__name__Z
set_ylabelZ
set_xlabelÚ
isinstanceÚstrÚnpÚuniquer   ÚlenÚ_recodeÚdictÚzipÚgroupbyZ	aggregateZreset_indexr   Ú
ValueErrorÚ	enumerateÚvaluesZplotr   ZlegendZmarginsÚallZ
set_xticksZset_xticklabels)r   r   r   ÚfuncZaxZplottypeZxlabelZylabelÚcolorsÚmarkersZ
linestylesZ	legendlocZlegendtitleÚkwargsr   ZfigZresponse_nameZx_valuesZx_levelsÚdataZ	plot_dataZn_traceÚir,   Úgroupr   r   r   r   Úinteraction_plot   sx    R

 þþ ÿÿ ÿÿ


r5   c                 C   sØ   ddl m} d}d}t| |ƒr0| j}| j}| j} | jjtj	tj
fkrNtdƒ‚n†t|tƒsbtdƒ‚nrt | ¡t t| ¡ ƒ¡k ¡ sŒtdƒ‚nHtj| jd td�}| ¡ D ]\}}||| |k< q¨|rÐ||||d�}|S dS )	a8   Recode categorial data to int factor.

    Parameters
    ----------
    x : array_like
        array like object supporting with numpy array methods of categorially
        coded data.
    levels : dict
        mapping of labels to integer-codings

    Returns
    -------
    out : instance numpy.ndarray
    r   )ÚSeriesNz<This is not a categorial factor. Array of str type required.z4This is not a valid value for levels. Dict required.z)The levels do not match the array values.)Údtype)r   Úindex)r   r6   r!   r   r8   r,   r7   Útyper#   Zstr_Zobject_r*   r'   r$   ÚlistÚkeysr-   ÚemptyÚshapeÚintÚitems)r   Zlevelsr6   r   r8   ÚoutÚlevelZcodingr   r   r   r&   ¡   s&    



 
r&   )Ú__doc__Zstatsmodels.compat.pythonr   Únumpyr#   Zstatsmodels.graphics.plottoolsr   Zstatsmodels.graphics.utilsZgraphicsr   Zmeanr5   r&   r   r   r   r   Ú<module>   s        þ
 