
    cQP                        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j        d          Z ej        d          Z ej        d	          Zd
 ZddZddZd Zd Zd Zd Zd Zd dZd Zd Zd Z	 	 	 	 	 	 	 	 	 	 d!dZdS )"    )absolute_import)Number)
exceptionsoptional_importsN)
graph_objs)make_subplotspandasnumpyzscipy.statsc                 &   t                               | t           j                  }t                               |          }t                               |          }t                               |dd          }t                               |dd          }t                               |dd          }||z
  }d|z  }t                               ||||z
  k                       }	t                               ||||z   k                       }
||||||	|
d	S )
z6
    Calculate statistics for use in violin plot.
    2   linear)interpolation   lowerK   higher      ?)minmaxq1q2q3d1d2)npasarrayfloatr   r   
percentile)dataxvals_minvals_maxr   r   r   iqrwhisker_distr   r   s              =lib/python3.11/site-packages/plotly/figure_factory/_violin.py
calc_statsr&      s     	

4""AvvayyHvvayyH	q"H	5	5B	q"G	4	4B	q"H	5	5B
r'C9L 
!\)*+	,	,B	!\)*+	,	,B      #1f77b4rgb(0, 0, 0)c                       fdt          t                               D             }t          j         dd|d|t          j                            d|d          dd	
  
        S )
zG
    Produces a sideways probability distribution fig violin plot.
    c                     g | ]B}d d                     |                   z   dz   d                     |                   z   dz   CS )z(pdf(y), y)=({:0.2f}z, ))format).0ir    ys     r%   
<listcomp>z$make_half_violin.<locals>.<listcomp>/   sb        	)**1Q400047):J:J1Q4:P:PPSVV  r'   lines tonextxg      ?spline)widthcolorshapetext)
r    r1   modenamer:   fill	fillcolorline	hoverinfoopacity)rangelenr   ScatterscatterLine)r    r1   r>   	linecolorr:   s   ``   r%   make_half_violinrH   +   s        s1vv  D
 

$$3ix$PP   r'   c           	          t          j        | | |z
  gt          |           z  t           j                            |d          dddd          S )z2
    Returns a rugplot fig for a violin plot.
    zline-ew-open)r8   symbolmarkersr4   Fr1   )r1   r    markerr;   r<   
showlegendr@   )r   rD   rC   rE   Marker)valspdf_maxdistancer8   s       r%   make_violin_rugplotrR   B   s^     
8h
#d))
+!((u^(LL   r'   c           
      z    t          j        ddg| |gddt           j                            dd                    S )z?
    Returns the scatterplot fig of most of a violin plot.
    r   r4   r3   r   
rgb(0,0,0)r7   r8   )r    r1   r<   r;   r?   )r   rD   rE   rF   )r   r   s     r%   make_non_outlier_intervalrV   Q   sK     a&r($$3l$CC   r'   c           
          t          j        ddg| |gdd                    |           z   dd                    |          z   gdt           j                            dd          d	
          S )z@
    Makes the upper and lower quartiles for a violin plot.
    r   zlower-quartile: r,   zupper-quartile: r3      rT   rU   r:   )r    r1   r:   r;   r?   r@   )r   rD   r.   rE   rF   )r   r   s     r%   make_quartilesrY   ^   s~     a&r(!1!1"!5!55!1!1"!5!55
 $$1L$AA
 
 
 
r'   c           
          t          j        dg| gdd                    |           z   gdt          dd          d	          S )
z;
    Formats the 'median' hovertext for a violin plot.
    r   zmedian: r,   rK   squarezrgb(255,255,255))rJ   r8   r:   )r    r1   r:   r;   rL   r@   )r   rD   r.   dict)r   s    r%   make_medianr]   o   sX     #$9++B///08+=>>>   r'   c           
      T    t           j                            | |dddddd          }|S )z-
    Makes the x-axis for a violin plot.
    Fr4   )titlerB   showgridzerolineshowlinemirrorticksshowticklabels)r   layoutXAxis)xaxis_titlexaxis_rangexaxiss      r%   
make_XAxisrk   }   s@     ## $ 	 	E Lr'   c           
      T    t           j                            | ddddddd          }|S )z-
    Makes the y-axis for a violin plot.
    TrX   F)r_   re   	autorangeticklenrb   ra   r`   rc   )r   rf   YAxis)yaxis_titleyaxiss     r%   
make_YAxisrr      s@     ## $ 	 	E Lr'   Tc                 V   t                               | t           j                  } t          |           d         }t          |           d         }t          |           d         }t          |           d         }t          |           d         }t          |           d         }t          |           d         }	t                              |           }
t                               ||d          } |
|          }t                               |          }|rd	|z  d
z  nd}| |z
  dz
  |dz   g}t          | ||          t          |||          t          ||	          t          ||          t          |          g}|r&|                    t          | |||                     ||fS )z?
    Refer to FigureFactory.create_violin() for docstring.
    r   r   r   r   r   r   r   d   g       @
   r   g?)r>   )rQ   r8   )r   r   r   r&   scipy_statsgaussian_kdelinspacer   rH   rV   rY   r]   appendrR   )rO   r>   rugplotr!   r"   r   r   r   r   r   pdfxxyymax_pdfrQ   plot_xrange	plot_datas                    r%   
violinplotr      s    ::dBH%%D$&H$&H	D		$	B	D		$	B	D		$	B	D		$	B	D		$	B 
"
"4
(
(C	Xx	-	-B	RBffRjjG'.5g##AH8h&,gm<K"bI666R9555!"b))r2BI  
g	RRR	
 	
 	
 k!!r'   c                    g }| |         D ]}||vr|                     |           |r|                                 |                     |g          }t          |          }t	          d|ddd          }d}t          |          D ]\  }}t                              |                    |          |         t          j	                  }|t          |          k    rd}t          |||         |          \  }}t          j                    }|D ]}|                    |d|dz              |dz  }|d                             d	                    |dz             t!          ||         |          i           |d                             d
                    d          t#          d          i           |d                             |
ddd||	           |S )u
    Refer to FigureFactory.create_violin() for docstring.

    Returns fig for violin plot without colorscale.

       T皙?Frowscolsshared_yaxeshorizontal_spacing
print_gridr   r>   rz   rf   xaxis{}yaxis{}r4   closestr_   rM   	hovermodeautosizeheightr7   )ry   sortgroupbyrC   r   	enumerater   r   	get_groupr   r   r   Layoutappend_traceupdater.   rk   rr   )r   data_headergroup_headercolorsuse_colorscalegroup_statsrz   r   r   r7   r_   
group_namer<   gbLfigcolor_indexkgrrO   r   r   rf   items                           r%   violin_no_colorscaler      s   * J\" $ $z! 	$d### 	|n	%	%BJA
QTePU  C K:&& 
 
2zz",,r**;7BB#f++% 	K!+F;/"
 "
 "
	; "$$ 	- 	-DT1a!e,,,,q 	Ha!e$$jA&L&LM	
 	
 	
 	

 M)**1--z"~~>???M     Jr'   c                    g }| |         D ]}||vr|                     |           |r|                                 |D ]}||vrt          j        d          |                     |g          }t          |          }t          d|ddd          }t          j        |d         t          j	                  }t          j        |d         t          j	                  }g }|D ]}|                     ||                    t          |          }t          |          }t          |          D ]\  }}t                              |                    |          |         t          j                  }||         |z
  ||z
  z  }t          j        |||          }t%          |d                    |          |	          \  }}t)          j                    }|D ]}|                    |d|dz              |d
                             d                    |dz             t1          ||         |          i           t)          j        dgdgdt5          d||d|d         gd|d         ggd          d          } |                    | d|           |d
                             d                    d          t7          d          i           |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   Tr   Fr   r   zrgb{}r   rf   r   rK      )sizecmincmax
colorscale	showscale)r    r1   r;   rL   rM   r   r4   r   r   )ry   r   r   PlotlyErrorr   rC   r   clrscolor_parserunlabel_rgbr   r   r   r   r   r   r   find_intermediate_colorr   r.   r   r   r   r   rk   rD   r\   rr   )!r   r   r   r   r   r   rz   r   r   r7   r_   r   r<   groupr   r   r   lowcolor	highcolorgroup_stats_valueskey	max_value	min_valuer   r   rO   intermedintermed_colorr   r   rf   r   trace_dummys!                                    r%   violin_colorscaler   	  sa   * J\" $ $z! 	$d###    # 	(+  	 
|n	%	%BJA
QTePU  C
  D,<==H!&)T-=>>I  4 4!!+c"23333&''I&''I:&& 
 
2zz",,r**;7BB  Oi/I	4IJ5h	8TT!+GNN>::G"
 "
 "
	; "$$ 	- 	-DT1a!e,,,,Ha!e$$jA&L&LM	
 	
 	
 	
 $##F1IF1I7
 
 
   K [!Q''' M)**1--z"~~>???M     Jr'   c                    g }| |         D ]}||vr|                     |           |r|                                 |D ]}||vrt          j        d          |                     |g          }t          |          }t          d|ddd          }t          |          D ]\  }}t          	                    |
                    |          |         t          j                  }t          |||         |          \  }}t          j                    }|D ]}|                    |d|dz              |d                             d	                    |dz             t%          ||         |          i           |d                             d
                    d          t'          d          i           |d                             |
ddd||	           |S )r   zMIf colors is a dictionary, all the group names must appear as keys in colors.r   Tr   Fr   r   rf   r   r   r4   r   r   )ry   r   r   r   r   rC   r   r   r   r   r   r   r   r   r   r   r   r.   rk   rr   )r   r   r   r   r   r   rz   r   r   r7   r_   r   r<   r   r   r   r   r   r   rO   r   r   rf   r   s                           r%   violin_dictr   p  s)   * J\" $ $z! 	$d###     	("  	 
|n	%	%BJA
QTePU  C :&& 
 
2zz",,r**;7BB!+DF2JPW!X!X!X	;"$$ 	- 	-DT1a!e,,,, 	Ha!e$$jA&L&LM	
 	
 	
 	

 M)**1--z"~~>???M     Jr'   F  X  Violin and Rug Plotc                    t          |t                    rt          j        |d          }nt          j        |d          }|}t          | t
                    rTt          |           dk    rt          j        d          t          d | D                       st          j        d          t          rYt          | t          j        j        j                  r5|t          j        d          | |         j                                        } t!          | |d         |          \  }}t#          j        |
d	t"          j                            d
          |d	|	t+          d|          t-          d          d	  	        }|d                             t          d	d	d                     t#          j        ||          }|S t          | t          j        j        j                  st          j        d          |t          j        d          |d	u rKt          |t                    rt3          | |||||||||	|
          }|S t5          | |||||||||	|
          }|S t          |t                    rt          j        d          t          |          dk     rt          j        d          t          |t                    st          j        d          t7          | |||||||||	|
          }|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 dictionary 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              3   @   K   | ]}t          |t                    V  d S )N)
isinstancer   )r/   elements     r%   	<genexpr>z create_violin.<locals>.<genexpr>R  s,      GGwz'622GGGGGGr'   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.r   F   )r   r4   r   )	r_   r   fontr   rM   r7   rj   rq   r   rq   )rb   re   rd   )r   rf   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.r   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   r\   r   validate_colors_dictvalidate_colorslistrC   r   r   allpdcoreframe	DataFramevaluestolistr   r   r   rf   Fontrk   rr   r   Figurer   r   r   )r   r   r   r   r   r   rz   r   r   r7   r_   valid_colorsr   r   rf   r   s                   r%   create_violinr     s   V &$ ;0??+FE::  dD!! 	4yyA~  ,/   GG$GGGGG  ,I    		5*T27=#:;; 		5  ,'   $+2244D ",LOW"
 "
 "
	; ""''R'00R--R..

 

 

 	wtU5PRSSSTTTYv>>>
 $ 788 	(     	(,   U" A	,-- !  "  
*  "  
,--  ,*   <  1$  ,/   k400  ,E   $ C Jr'   )r(   r)   )r(   )r(   T)
NNNFNTFr   r   r   )
__future__r   numbersr   plotlyr   r   plotly.colorsr   r   plotly.graph_objsr   plotly.subplotsr   
get_moduler   r   rv   r&   rH   rR   rV   rY   r]   rk   rr   r   r   r   r   r    r'   r%   <module>r      s   & & & & & &       / / / / / / / /       ( ( ( ( ( ( ) ) ) ) ) )  **  ))))-88  8   .   
 
 
  "    "  "$" $" $" $"N@ @ @Fd d dNE E ET 	

P P P P P Pr'   