
    M/Ph-A                     j    d Z ddlZddlmZ ddlmZ ddgZ	 	 dd
Zd Z	d Z
dddddi fdZd Zd ZdS )zVariations on boxplots.    N)gaussian_kde   )utils
violinplotbeanplotbothTc           	         |i n|}t          d | D                       dk    rd}t          |          t          j        |          \  }}t	          t          t          j        |                     } |$t          j        t          |                     dz   }t          j         |          t          j
        |          z
  }	t          j
        dt          j         |	dg          z  |                    dd	          d
z  g          }
t          | |          D ]\  }}t          ||||
||           |r|                    | d|d           t          || |||           |S )a  
    Make a violin plot of each dataset in the `data` sequence.

    A violin plot is a boxplot combined with a kernel density estimate of the
    probability density function per point.

    Parameters
    ----------
    data : sequence[array_like]
        Data arrays, one array per value in `positions`.
    ax : AxesSubplot, optional
        If given, this subplot is used to plot in instead of a new figure being
        created.
    labels : list[str], optional
        Tick labels for the horizontal axis.  If not given, integers
        ``1..len(data)`` are used.
    positions : array_like, optional
        Position array, used as the horizontal axis of the plot.  If not given,
        spacing of the violins will be equidistant.
    side : {'both', 'left', 'right'}, optional
        How to plot the violin.  Default is 'both'.  The 'left', 'right'
        options can be used to create asymmetric violin plots.
    show_boxplot : bool, optional
        Whether or not to show normal box plots on top of the violins.
        Default is True.
    plot_opts : dict, optional
        A dictionary with plotting options.  Any of the following can be
        provided, if not present in `plot_opts` the defaults will be used::

          - 'violin_fc', MPL color.  Fill color for violins.  Default is 'y'.
          - 'violin_ec', MPL color.  Edge color for violins.  Default is 'k'.
          - 'violin_lw', scalar.  Edge linewidth for violins.  Default is 1.
          - 'violin_alpha', float.  Transparancy of violins.  Default is 0.5.
          - 'cutoff', bool.  If True, limit violin range to data range.
                Default is False.
          - 'cutoff_val', scalar.  Where to cut off violins if `cutoff` is
                True.  Default is 1.5 standard deviations.
          - 'cutoff_type', {'std', 'abs'}.  Whether cutoff value is absolute,
                or in standard deviations.  Default is 'std'.
          - 'violin_width' : float.  Relative width of violins.  Max available
                space is 1, default is 0.8.
          - 'label_fontsize', MPL fontsize.  Adjusts fontsize only if given.
          - 'label_rotation', scalar.  Adjusts label rotation only if given.
                Specify in degrees.
          - 'bw_factor', Adjusts the scipy gaussian_kde kernel. default: None.
                Options for scalar or callable.

    Returns
    -------
    Figure
        If `ax` is None, the created figure.  Otherwise the figure to which
        `ax` is connected.

    See Also
    --------
    beanplot : Bean plot, builds on `violinplot`.
    matplotlib.pyplot.boxplot : Standard boxplot.

    Notes
    -----
    The appearance of violins can be customized with `plot_opts`.  If
    customization of boxplot elements is required, set `show_boxplot` to False
    and plot it on top of the violins by calling the Matplotlib `boxplot`
    function directly.  For example::

        violinplot(data, ax=ax, show_boxplot=False)
        ax.boxplot(data, sym='cv', whis=2.5)

    It can happen that the axis labels or tick labels fall outside the plot
    area, especially with rotated labels on the horizontal axis.  With
    Matplotlib 1.1 or higher, this can easily be fixed by calling
    ``ax.tight_layout()``.  With older Matplotlib one has to use ``plt.rc`` or
    ``plt.rcParams`` to fix this, for example::

        plt.rc('figure.subplot', bottom=0.25)
        violinplot(data, ax=ax)

    References
    ----------
    J.L. Hintze and R.D. Nelson, "Violin Plots: A Box Plot-Density Trace
    Synergism", The American Statistician, Vol. 52, pp.181-84, 1998.

    Examples
    --------
    We use the American National Election Survey 1996 dataset, which has Party
    Identification of respondents as independent variable and (among other
    data) age as dependent variable.

    >>> data = sm.datasets.anes96.load_pandas()
    >>> party_ID = np.arange(7)
    >>> labels = ["Strong Democrat", "Weak Democrat", "Independent-Democrat",
    ...           "Independent-Indpendent", "Independent-Republican",
    ...           "Weak Republican", "Strong Republican"]

    Group age by party ID, and create a violin plot with it:

    >>> plt.rcParams['figure.subplot.bottom'] = 0.23  # keep labels visible
    >>> age = [data.exog['age'][data.endog == id] for id in party_ID]
    >>> fig = plt.figure()
    >>> ax = fig.add_subplot(111)
    >>> sm.graphics.violinplot(age, ax=ax, labels=labels,
    ...                        plot_opts={'cutoff_val':5, 'cutoff_type':'abs',
    ...                                   'label_fontsize':'small',
    ...                                   'label_rotation':30})
    >>> ax.set_xlabel("Party identification of respondent.")
    >>> ax.set_ylabel("Age")
    >>> plt.show()

    .. plot:: plots/graphics_boxplot_violinplot.py
    Nc                 6    g | ]}t          j        |          S  )npsize).0arrs     ]/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/graphics/boxplots.py
<listcomp>zviolinplot.<locals>.<listcomp>   s     )))SBGCLL)))    r   z"No Data to make Violin: Try again!r   333333?      ?violin_width皙?       @)notch	positionsvert)max
ValueErrorr   create_mpl_axlistmapr   asarrayarangelenmingetzip_single_violinboxplot_set_ticks_labels)dataaxlabelsr   sideshow_boxplot	plot_optsmsgfigpos_spanwidthpos_dataposs                r   r   r      so   `  'YI
))D)))**a//2oo!"%%GCBJ%%&&DIc$ii((1,	 vi  26)#4#44HFD268R.111MM.#66;= > >E T9-- B B#r3%yAAAA ?


4qIA
>>> b$	9===Jr   c                 Z   |                     dd          }fd}t          j        |          }t          ||           |||          }                    |          }	||	z  |	                                z  }	|dk    r|	 |z   |	|z   }}
n.|dk    r||	|z   }}
n |dk    r	|	 |z   |}}
nd}t          |          |                     ||
||                     d	d
          |                     dd          |                     dd          |                     dd                     ||	fS ) 	bw_factorNc                 l   |                     dd          }|                     dd          }|                     dd          }d}|s |dk    r|t          j        |           z  }n|}j                                        |z
  }j                                        |z   }t          j        ||d          S )	zCReturn array with correct range, with which violins can be plotted.cutoffFcutoff_typestd
cutoff_valg      ?g        d   )r$   r   r;   datasetr#   r   linspace)	r3   r.   r9   r:   r<   sx_lowerx_upperkdes	           r   _violin_rangez%_single_violin.<locals>._violin_range   s    x//mmM599]]<55
 	e##!1!11+//##a'+//##a'{7GS111r   )	bw_methodr   rightleftz<`side` parameter should be one of {'left', 'right', 'both'}.	violin_fcz#66c2a5	violin_eck	violin_lwr   violin_alpha      ?)	facecolor	edgecolorlwalpha)r$   r   r    r   evaluater   r   fill_betweenx)r*   r4   r3   r2   r,   r.   r7   rD   xvalsviolin
envelope_l
envelope_rr/   rC   s                @r   r&   r&      sb   k400I2 2 2 2 2" z(##H
x9
5
5
5C M(I..E\\%  FV^fjjll*Fv~~#)'C-#J

	"%v|J

	#)'C-J

Loo UJ
(}}[)DD(}}[#>>!k155$====	  ? ? ? &=r   c                    |                      t          j        |          dz
  t          j        |          dz   g           |                     |           |                    d          }|                    d          }|s|rddlm} |dt          |          t          |          k    sd}t          |          | 
                    |          }	|r ||	|           |r ||	|	           dS )
z(Set ticks and labels on horizontal axis.rM   label_fontsizelabel_rotationr   setpNz1Length of `labels` should equal length of `data`.fontsize)rotation)set_xlimr   r#   r   
set_xticksr$   matplotlib.artistr\   r"   r   set_xticklabels)
r*   r)   r+   r   r.   rY   rZ   r\   r/   
xticknamess
             r   r(   r(      s    KK	""S("&*;*;c*ABCCCMM)]]#344N]]#344N + +******6{{c$ii''ECS//!''//
 	6Dn5555 	6Dn5555
Fr   Fc                    t          j        |          \  }}t          t          t          j        |                     } |$t	          j        t          |                     dz   }t	          j        |          t	          j	        |          z
  }t	          j	        dt	          j        |dg          z  |
                    dd          dz  g          }	t	          j	        dt	          j        |dg          z  |
                    dd	          dz  g          }
t	          j	        dt	          j        |dg          z  |
                    d
d	          dz  g          }|
                    dd          }t          | |          D ]\  }}t          ||||	||          \  }}|r|t          ||||          z   }|                    ||d|
                    dd          |
                    dd          |
                    dd          d|
                    dd          |	  	         nI|                    |||
z
  ||
z   |
                    dd	          |
                    dd          |           |t!          |           d}|
                    dd          rZ|                    t	          j        |          ||z
  ||z   |
                    dd          |
                    dd                     |
                    dd          rS|                    |t	          j        |          |
                    dd           |
                    d!d"          #           t'          || |||           |S )$aH  
    Bean plot of each dataset in a sequence.

    A bean plot is a combination of a `violinplot` (kernel density estimate of
    the probability density function per point) with a line-scatter plot of all
    individual data points.

    Parameters
    ----------
    data : sequence[array_like]
        Data arrays, one array per value in `positions`.
    ax : AxesSubplot
        If given, this subplot is used to plot in instead of a new figure being
        created.
    labels : list[str], optional
        Tick labels for the horizontal axis.  If not given, integers
        ``1..len(data)`` are used.
    positions : array_like, optional
        Position array, used as the horizontal axis of the plot.  If not given,
        spacing of the violins will be equidistant.
    side : {'both', 'left', 'right'}, optional
        How to plot the violin.  Default is 'both'.  The 'left', 'right'
        options can be used to create asymmetric violin plots.
    jitter : bool, optional
        If True, jitter markers within violin instead of plotting regular lines
        around the center.  This can be useful if the data is very dense.
    plot_opts : dict, optional
        A dictionary with plotting options.  All the options for `violinplot`
        can be specified, they will simply be passed to `violinplot`.  Options
        specific to `beanplot` are:

          - 'violin_width' : float.  Relative width of violins.  Max available
                space is 1, default is 0.8.
          - 'bean_color', MPL color.  Color of bean plot lines.  Default is 'k'.
                Also used for jitter marker edge color if `jitter` is True.
          - 'bean_size', scalar.  Line length as a fraction of maximum length.
                Default is 0.5.
          - 'bean_lw', scalar.  Linewidth, default is 0.5.
          - 'bean_show_mean', bool.  If True (default), show mean as a line.
          - 'bean_show_median', bool.  If True (default), show median as a
                marker.
          - 'bean_mean_color', MPL color.  Color of mean line.  Default is 'b'.
          - 'bean_mean_lw', scalar.  Linewidth of mean line, default is 2.
          - 'bean_mean_size', scalar.  Line length as a fraction of maximum length.
                Default is 0.5.
          - 'bean_median_color', MPL color.  Color of median marker.  Default
                is 'r'.
          - 'bean_median_marker', MPL marker.  Marker type, default is '+'.
          - 'jitter_marker', MPL marker.  Marker type for ``jitter=True``.
                Default is 'o'.
          - 'jitter_marker_size', int.  Marker size.  Default is 4.
          - 'jitter_fc', MPL color.  Jitter marker face color.  Default is None.
          - 'bean_legend_text', str.  If given, add a legend with given text.

    Returns
    -------
    Figure
        If `ax` is None, the created figure.  Otherwise the figure to which
        `ax` is connected.

    See Also
    --------
    violinplot : Violin plot, also used internally in `beanplot`.
    matplotlib.pyplot.boxplot : Standard boxplot.

    References
    ----------
    P. Kampstra, "Beanplot: A Boxplot Alternative for Visual Comparison of
    Distributions", J. Stat. Soft., Vol. 28, pp. 1-9, 2008.

    Examples
    --------
    We use the American National Election Survey 1996 dataset, which has Party
    Identification of respondents as independent variable and (among other
    data) age as dependent variable.

    >>> data = sm.datasets.anes96.load_pandas()
    >>> party_ID = np.arange(7)
    >>> labels = ["Strong Democrat", "Weak Democrat", "Independent-Democrat",
    ...           "Independent-Indpendent", "Independent-Republican",
    ...           "Weak Republican", "Strong Republican"]

    Group age by party ID, and create a violin plot with it:

    >>> plt.rcParams['figure.subplot.bottom'] = 0.23  # keep labels visible
    >>> age = [data.exog['age'][data.endog == id] for id in party_ID]
    >>> fig = plt.figure()
    >>> ax = fig.add_subplot(111)
    >>> sm.graphics.beanplot(age, ax=ax, labels=labels,
    ...                      plot_opts={'cutoff_val':5, 'cutoff_type':'abs',
    ...                                 'label_fontsize':'small',
    ...                                 'label_rotation':30})
    >>> ax.set_xlabel("Party identification of respondent.")
    >>> ax.set_ylabel("Age")
    >>> plt.show()

    .. plot:: plots/graphics_boxplot_beanplot.py
    Nr   r   r   r   r   r   	bean_sizerM   bean_mean_sizebean_legend_textr6   jitter_markerojitter_marker_size   
bean_colorrJ   	jitter_fcnone)lsmarkermsmecmewmfclabelbean_lw)rP   colorrv   bean_show_meanTbean_mean_lwbean_mean_colorb)rP   rx   bean_show_medianbean_median_marker+bean_median_colorr)rq   rx   )r   r   r   r   r   r    r!   r"   r   r#   r$   r%   r&   _jitter_envelopeplothlines_show_legendmeanmedianr(   )r)   r*   r+   r   r,   jitterr.   r0   r1   r   
bean_widthbean_mean_width
legend_txtr3   r4   rT   rU   jitter_coords                     r   r   r      s   H !"%%GCBJ%%&&DIc$ii((1,	 vi  26)#4#44H64"&(B"8"88MM.#66;= > >L"~ 6 66MM+s33b8: ; ;JfdRVXrN%;%;;MM"2C882=? @ @O 1488JT9-- #C #C#&r3,iXXv 	(!1(E64!P!PPLGGL(r$==#>> }}%91==!lC88y}}[&AA$  & & & & IIhj 0#
2B"y#66%MM,<<&  ( ( ( !J ==)400 	CIIbgh'')>o@U"~r::%MM*;SAA  C C C
 ==+T22 	CGGC8,,$==)=sCC#--(;SAA  C C C
 b$	9===Jr   c                     |dk    rd\  }}n*|dk    rd\  }}n|dk    rd\  }}nt          d|z            t          j        | ||          }|t          j                            ||| j                  z  }|S )	z&Determine envelope for jitter markers.r   )      r   rF   )r   r   rG   )r   r   z`side` input incorrect: %s)lowhighr   )r   r   interprandomuniformr   )r3   rT   rU   r,   r   r   jitter_enveloper   s           r   r   r     s    v~~	TT		TT		TT5<===i%88O"RY%6%63T<DM &7 &K &K KL r   c                     |                      ddddd          }|                                }|                                }|                                }ddlm}  ||d	            ||d
           dS )z Utility function to show legend.r   Tg?r   )locshadowfancyboxlabelspacing	borderpadr   r[   smallr]   )	linewidthN)legend	get_texts	get_lines	get_framerb   r\   )r*   legltextllinesframer\   s         r   r   r     s    
))$C"  $ $C]]__E]]__F]]__E&&&&&&D!!!!D1r   )NNNr   TN)__doc__numpyr   scipy.statsr   r6   r   __all__r   r&   r(   r   r   r   r   r   r   <module>r      s     
     $ $ $ $ $ $      
$ AG,0J J J JZ/ / /d  6 44fR\ \ \ \~  $
 
 
 
 
r   