B
    =Œ¶cQP  ã            
   @   sÞ   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 d dlmZ e d¡Ze d¡Ze d	¡Zd
d„ Zd+dd„Zd,dd„Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zd-dd„Zdd „ Zd!d"„ Zd#d$„ Zd.d)d*„ZdS )/é    )Úabsolute_import)ÚNumber)Ú
exceptionsÚoptional_importsN)Ú
graph_objs)Úmake_subplotsZpandasÚnumpyzscipy.statsc             C   s¢   t  | t j¡}t  |¡}t  |¡}t j|ddd}t j|ddd}t j|ddd}|| }d| }t  |||| k ¡}	t  |||| k ¡}
||||||	|
d	œS )
z6
    Calculate statistics for use in violin plot.
    é2   Zlinear)Úinterpolationé   ÚloweréK   Zhigherg      ø?)ÚminÚmaxÚq1Úq2Úq3Úd1Úd2)ÚnpÚasarrayÚfloatr   r   Z
percentile)ÚdataÚxÚvals_minÚvals_maxr   r   r   ZiqrZwhisker_distr   r   © r   úN/var/www/cleansys/lib/python3.7/site-packages/plotly/figure_factory/_violin.pyÚ
calc_stats   s"    

r   ú#1f77b4úrgb(0, 0, 0)c                sH   ‡ ‡fdd„t tˆ ƒƒD ƒ}tjˆ ˆdd|d|tjjd|ddd	dd

S )zG
    Produces a sideways probability distribution fig violin plot.
    c                s4   g | ],}d d  ˆ | ¡ d d  ˆ| ¡ d ‘qS )z(pdf(y), y)=(z{:0.2f}z, ú))Úformat)Ú.0Úi)r   Úyr   r   ú
<listcomp>0   s   z$make_half_violin.<locals>.<listcomp>ÚlinesÚ Ztonextxg      à?Zspline)ÚwidthÚcolorÚshapeÚtext)
r   r%   ÚmodeÚnamer,   ÚfillÚ	fillcolorÚlineÚ	hoverinfoZopacity)ÚrangeÚlenr   ÚScatterÚscatterÚLine)r   r%   r0   Z	linecolorr,   r   )r   r%   r   Úmake_half_violin+   s    r8   c          	   C   s4   t j| | | gt| ƒ t jj|dddddddS )z2
    Returns a rugplot fig for a violin plot.
    zline-ew-open)r*   ÚsymbolÚmarkersr(   Fr%   )r%   r   Úmarkerr-   r.   Ú
showlegendr2   )r   r5   r4   r6   ÚMarker)ÚvalsZpdf_maxÚdistancer*   r   r   r   Úmake_violin_rugplotB   s    r@   c          	   C   s(   t jddg| |gddt jjddddS )z?
    Returns the scatterplot fig of most of a violin plot.
    r   r(   r'   g      ø?z
rgb(0,0,0))r)   r*   )r   r%   r.   r-   r1   )r   r5   r6   r7   )r   r   r   r   r   Úmake_non_outlier_intervalQ   s    rA   c          	   C   sB   t jddg| |gdd | ¡ dd |¡ gdt jjdddd	d
S )z@
    Makes the upper and lower quartiles for a violin plot.
    r   zlower-quartile: z{:0.2f}zupper-quartile: r'   é   z
rgb(0,0,0))r)   r*   r,   )r   r%   r,   r-   r1   r2   )r   r5   r"   r6   r7   )r   r   r   r   r   Úmake_quartiles^   s    rC   c          	   C   s.   t jdg| gdd | ¡ gdtddddd	S )
z;
    Formats the 'median' hovertext for a violin plot.
    r   zmedian: z{:0.2f}r:   Zsquarezrgb(255,255,255))r9   r*   r,   )r   r%   r,   r-   r;   r2   )r   r5   r"   Údict)r   r   r   r   Úmake_mediano   s    
rE   c          
   C   s    t jj| |ddddddd}|S )z-
    Makes the x-axis for a violin plot.
    Fr(   )Útitler3   ÚshowgridÚzerolineÚshowlineÚmirrorÚticksÚshowticklabels)r   ÚlayoutZXAxis)Zxaxis_titleZxaxis_rangeÚxaxisr   r   r   Ú
make_XAxis}   s    rO   c          
   C   s    t jj| dddddddd}|S )z-
    Makes the y-axis for a violin plot.
    TrB   F)rF   rL   Z	autorangeZticklenrI   rH   rG   rJ   )r   rM   ZYAxis)Zyaxis_titleÚyaxisr   r   r   Ú
make_YAxisŽ   s    rQ   Tc             C   s  t  | t j¡} t| ƒd }t| ƒd }t| ƒd }t| ƒd }t| ƒd }t| ƒd }t| ƒd }	t | ¡}
t  ||d¡}|
|ƒ}t  |¡}|rœd	| d
 nd}| | d |d g}t| ||dt|||dt	||	ƒt
||ƒt|ƒg}|r| t| |||d¡ ||fS )z?
    Refer to FigureFactory.create_violin() for docstring.
    r   r   r   r   r   r   r   éd   g       @é
   r   gš™™™™™¹?)r0   )r?   r*   )r   r   r   r   Úscipy_statsZgaussian_kdeZlinspacer   r8   rA   rC   rE   Úappendr@   )r>   r0   Úrugplotr   r   r   r   r   r   r   ZpdfZxxÚyyZmax_pdfr?   Úplot_xrangeÚ	plot_datar   r   r   Ú
violinplotŸ   s.    


rZ   c             C   sB  g }x"| | D ]}||kr|  |¡ qW |r4| ¡  |  |g¡}t|ƒ}td|dddd}d}x¨t|ƒD ]œ\}}t | |¡| tj	¡}|t|ƒkr˜d}t
||| |d\}}t ¡ }x|D ]}| |d|d ¡ q¼W |d7 }|d  d	 |d ¡t|| |ƒi¡ qhW |d  d
 d¡tdƒi¡ |d j|
ddd||	d |S )zu
    Refer to FigureFactory.create_violin() for docstring.

    Returns fig for violin plot without colorscale.

    é   Tgš™™™™™™?F)ÚrowsÚcolsÚshared_yaxesÚhorizontal_spacingÚ
print_gridr   )r0   rV   rM   zxaxis{}zyaxis{}r(   Úclosest)rF   r<   Ú	hovermodeÚautosizeÚheightr)   )rU   ÚsortÚgroupbyr4   r   Ú	enumerater   r   Ú	get_groupr   rZ   r   ÚLayoutÚappend_traceÚupdater"   rO   rQ   )r   Údata_headerÚgroup_headerÚcolorsÚuse_colorscaleÚgroup_statsrV   re   rd   r)   rF   Ú
group_namer.   ÚgbÚLÚfigZcolor_indexÚkÚgrr>   rY   rX   rM   Úitemr   r   r   Úviolin_no_colorscaleÆ   s@    
"rx   c       !      C   s  g }x"| | D ]}||kr|  |¡ qW |r4| ¡  x|D ]}||kr:t d¡‚q:W |  |g¡}t|ƒ}td|dddd}t |d tj	¡}t |d tj	¡}g }x|D ]}|  || ¡ q¨W t
|ƒ}t|ƒ}x¶t|ƒD ]ª\}}t | |¡| tj¡}|| | ||  }t |||¡}t|d |¡|d	\}}t ¡ }x |D ]}| |d|d ¡ q@W |d
  d |d ¡t|| |ƒi¡ qØW tjdgdgdtd||d|d gd|d ggdddd} | | d|¡ |d
  d d¡tdƒi¡ |d
 j|
ddd||	d |S )zr
    Refer to FigureFactory.create_violin() for docstring.

    Returns fig for violin plot with colorscale.

    zRAll values/groups in the index column must be represented as a key in group_stats.r[   Tgš™™™™™™?F)r\   r]   r^   r_   r`   r   zrgb{})r0   rV   rM   zxaxis{}r:   é   )ÚsizeZcminZcmaxZ
colorscaleZ	showscale)r   r%   r-   r;   r<   zyaxis{}r(   ra   )rF   r<   rb   rc   rd   r)   )rU   re   r   ÚPlotlyErrorrf   r4   r   ÚclrsZcolor_parserZunlabel_rgbr   r   rg   r   r   rh   r   Zfind_intermediate_colorrZ   r"   r   ri   rj   rk   rO   r5   rD   rQ   )!r   rl   rm   rn   ro   rp   rV   re   rd   r)   rF   rq   r.   Úgrouprr   rs   rt   ZlowcolorZ	highcolorZgroup_stats_valuesÚkeyZ	max_valueZ	min_valueru   rv   r>   ZintermedZintermed_colorrY   rX   rM   rw   Ztrace_dummyr   r   r   Úviolin_colorscale	  sj    



"r   c             C   sF  g }x"| | D ]}||kr|  |¡ qW |r4| ¡  x|D ]}||kr:t d¡‚q:W |  |g¡}t|ƒ}td|dddd}xt|ƒD ]„\}}t 	| 
|¡| tj¡}t||| |d\}}t ¡ }x|D ]}| |d|d ¡ qÈW |d  d	 |d ¡t|| |ƒi¡ q„W |d  d
 d¡tdƒi¡ |d j|
ddd||	d |S )zu
    Refer to FigureFactory.create_violin() for docstring.

    Returns fig for violin plot without colorscale.

    zMIf colors is a dictionary, all the group names must appear as keys in colors.r[   Tgš™™™™™™?F)r\   r]   r^   r_   r`   )r0   rV   rM   zxaxis{}zyaxis{}r(   ra   )rF   r<   rb   rc   rd   r)   )rU   re   r   r{   rf   r4   r   rg   r   r   rh   r   rZ   r   ri   rj   rk   r"   rO   rQ   )r   rl   rm   rn   ro   rp   rV   re   rd   r)   rF   rq   r.   r}   rr   rs   rt   ru   rv   r>   rY   rX   rM   rw   r   r   r   Úviolin_dictp  s>    


"r€   FéÂ  éX  úViolin and Rug Plotc             C   sþ  t |tƒrt |d¡}nt |d¡}|dkrt | tƒrjt| ƒdkrNt d¡‚t	dd„ | D ƒƒsjt d¡‚t
ržt | t
jjjƒrž|dkrt d¡‚| | j ¡ } t| |d |d	\}}tj|
d
tjjdd|d
|	td|ƒtdƒdd	}|d  td
d
dd¡ tj||d}|S t | t
jjjƒs*t d¡‚|dkr>t d¡‚|d
kr–t |tƒrtt| |||||||||	|
ƒ}|S t| |||||||||	|
ƒ}|S ndt |tƒr¬t d¡‚t|ƒdk rÄt d¡‚t |tƒsÚt d¡‚t| |||||||||	|
ƒ}|S dS )a}  
    **deprecated**, use instead the plotly.graph_objects trace
    :class:`plotly.graph_objects.Violin`.

    :param (list|array) data: accepts either a list of numerical values,
        a list of dictionaries all with identical keys and at least one
        column of numeric values, or a pandas dataframe with at least one
        column of numbers.
    :param (str) data_header: the header of the data column to be used
        from an inputted pandas dataframe. Not applicable if 'data' is
        a list of numeric values.
    :param (str) group_header: applicable if grouping data by a variable.
        'group_header' must be set to the name of the grouping variable.
    :param (str|tuple|list|dict) colors: either a plotly scale name,
        an rgb or hex color, a color tuple, a list of colors or a
        dictionary. An rgb color is of the form 'rgb(x, y, z)' where
        x, y and z belong to the interval [0, 255] and a color tuple is a
        tuple of the form (a, b, c) where a, b and c belong to [0, 1].
        If colors is a list, it must contain valid color types as its
        members.
    :param (bool) use_colorscale: only applicable if grouping by another
        variable. Will implement a colorscale based on the first 2 colors
        of param colors. This means colors must be a list with at least 2
        colors in it (Plotly colorscales are accepted since they map to a
        list of two rgb colors). Default = False
    :param (dict) group_stats: a dictioanry where each key is a unique
        value from the group_header column in data. Each value must be a
        number and will be used to color the violin plots if a colorscale
        is being used.
    :param (bool) rugplot: determines if a rugplot is draw on violin plot.
        Default = True
    :param (bool) sort: determines if violins are sorted
        alphabetically (True) or by input order (False). Default = False
    :param (float) height: the height of the violin plot.
    :param (float) width: the width of the violin plot.
    :param (str) title: the title of the violin plot.

    Example 1: Single Violin Plot

    >>> from plotly.figure_factory import create_violin
    >>> import plotly.graph_objs as graph_objects

    >>> import numpy as np
    >>> from scipy import stats

    >>> # create list of random values
    >>> data_list = np.random.randn(100)

    >>> # create violin fig
    >>> fig = create_violin(data_list, colors='#604d9e')

    >>> # plot
    >>> fig.show()

    Example 2: Multiple Violin Plots with Qualitative Coloring

    >>> from plotly.figure_factory import create_violin
    >>> import plotly.graph_objs as graph_objects

    >>> import numpy as np
    >>> import pandas as pd
    >>> from scipy import stats

    >>> # create dataframe
    >>> np.random.seed(619517)
    >>> Nr=250
    >>> y = np.random.randn(Nr)
    >>> gr = np.random.choice(list("ABCDE"), Nr)
    >>> norm_params=[(0, 1.2), (0.7, 1), (-0.5, 1.4), (0.3, 1), (0.8, 0.9)]

    >>> for i, letter in enumerate("ABCDE"):
    ...     y[gr == letter] *=norm_params[i][1]+ norm_params[i][0]
    >>> df = pd.DataFrame(dict(Score=y, Group=gr))

    >>> # create violin fig
    >>> fig = create_violin(df, data_header='Score', group_header='Group',
    ...                    sort=True, height=600, width=1000)

    >>> # plot
    >>> fig.show()

    Example 3: Violin Plots with Colorscale

    >>> from plotly.figure_factory import create_violin
    >>> import plotly.graph_objs as graph_objects

    >>> import numpy as np
    >>> import pandas as pd
    >>> from scipy import stats

    >>> # create dataframe
    >>> np.random.seed(619517)
    >>> Nr=250
    >>> y = np.random.randn(Nr)
    >>> gr = np.random.choice(list("ABCDE"), Nr)
    >>> norm_params=[(0, 1.2), (0.7, 1), (-0.5, 1.4), (0.3, 1), (0.8, 0.9)]

    >>> for i, letter in enumerate("ABCDE"):
    ...     y[gr == letter] *=norm_params[i][1]+ norm_params[i][0]
    >>> df = pd.DataFrame(dict(Score=y, Group=gr))

    >>> # define header params
    >>> data_header = 'Score'
    >>> group_header = 'Group'

    >>> # make groupby object with pandas
    >>> group_stats = {}
    >>> groupby_data = df.groupby([group_header])

    >>> for group in "ABCDE":
    ...     data_from_group = groupby_data.get_group(group)[data_header]
    ...     # take a stat of the grouped data
    ...     stat = np.median(data_from_group)
    ...     # add to dictionary
    ...     group_stats[group] = stat

    >>> # create violin fig
    >>> fig = create_violin(df, data_header='Score', group_header='Group',
    ...                     height=600, width=1000, use_colorscale=True,
    ...                     group_stats=group_stats)

    >>> # plot
    >>> fig.show()
    ÚrgbNr   zRIf data is a list, it must be nonempty and contain either numbers or dictionaries.c             s   s   | ]}t |tƒV  qd S )N)Ú
isinstancer   )r#   Úelementr   r   r   ú	<genexpr>R  s    z create_violin.<locals>.<genexpr>z0If data is a list, it must contain only numbers.zVdata_header must be the column name with the desired numeric data for the violin plot.)r0   rV   Fé   )rz   r(   ra   )	rF   rc   Zfontrd   r<   r)   rN   rP   rb   rP   )rI   rL   rK   )r   rM   zGError. You must use a pandas DataFrame if you are using a group header.zFThe colors param cannot be a dictionary if you are using a colorscale.ry   zHcolors must be a list with at least 2 colors. A Plotly scale is allowed.z,Your group_stats param must be a dictionary.)r…   rD   r|   Zvalidate_colors_dictZvalidate_colorsÚlistr4   r   r{   ÚallÚpdÚcoreÚframeZ	DataFrameÚvaluesÚtolistrZ   r   ri   rM   ZFontrO   rQ   rk   ZFigurer€   rx   r   )r   rl   rm   rn   ro   rp   rV   re   rd   r)   rF   Zvalid_colorsrY   rX   rM   rt   r   r   r   Úcreate_violin¸  s°     




r   )r   r    )r   )r   T)
NNNFNTFr   r‚   rƒ   )Ú
__future__r   Únumbersr   Zplotlyr   r   Zplotly.colorsrn   r|   Zplotly.graph_objsr   Zplotly.subplotsr   Z
get_moduler‹   r   rT   r   r8   r@   rA   rC   rE   rO   rQ   rZ   rx   r   r€   r   r   r   r   r   Ú<module>   s<   





'CgJ         