
    M/Ph                         d dl m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 dlmZ dd	lmZ g d
Z G d d          Zej        dd d ddddfdZ	 ddZddZddZd Z	 ddZddZdS )    )lzipN)stats)ECDF)OLS)cache_readonly)add_constant   )utils)qqplotqqplot_2samplesqqlineProbPlotc                       e Zd ZdZej        dddddfdZed             Zed             Z	ed	             Z
ed
             Zed             Z	 	 	 	 	 ddZ	 	 	 	 	 	 ddefdZ	 	 	 	 	 ddZdS )r   a  
    Q-Q and P-P Probability Plots

    Can take arguments specifying the parameters for dist or fit them
    automatically. (See fit under kwargs.)

    Parameters
    ----------
    data : array_like
        A 1d data array
    dist : callable
        Compare x against dist. A scipy.stats or statsmodels distribution. The
        default is scipy.stats.distributions.norm (a standard normal). Can be
        a SciPy frozen distribution.
    fit : bool
        If fit is false, loc, scale, and distargs are passed to the
        distribution. If fit is True then the parameters for dist are fit
        automatically using dist.fit. The quantiles are formed from the
        standardized data, after subtracting the fitted loc and dividing by
        the fitted scale. fit cannot be used if dist is a SciPy frozen
        distribution.
    distargs : tuple
        A tuple of arguments passed to dist to specify it fully so dist.ppf
        may be called. distargs must not contain loc or scale. These values
        must be passed using the loc or scale inputs. distargs cannot be used
        if dist is a SciPy frozen distribution.
    a : float
        Offset for the plotting position of an expected order statistic, for
        example. The plotting positions are given by
        (i - a)/(nobs - 2*a + 1) for i in range(0,nobs+1)
    loc : float
        Location parameter for dist. Cannot be used if dist is a SciPy frozen
        distribution.
    scale : float
        Scale parameter for dist. Cannot be used if dist is a SciPy frozen
        distribution.

    See Also
    --------
    scipy.stats.probplot

    Notes
    -----
    1) Depends on matplotlib.
    2) If `fit` is True then the parameters are fit using the
        distribution's `fit()` method.
    3) The call signatures for the `qqplot`, `ppplot`, and `probplot`
        methods are similar, so examples 1 through 4 apply to all
        three methods.
    4) The three plotting methods are summarized below:
        ppplot : Probability-Probability plot
            Compares the sample and theoretical probabilities (percentiles).
        qqplot : Quantile-Quantile plot
            Compares the sample and theoretical quantiles
        probplot : Probability plot
            Same as a Q-Q plot, however probabilities are shown in the scale of
            the theoretical distribution (x-axis) and the y-axis contains
            unscaled quantiles of the sample data.

    Examples
    --------
    The first example shows a Q-Q plot for regression residuals

    >>> # example 1
    >>> import statsmodels.api as sm
    >>> from matplotlib import pyplot as plt
    >>> data = sm.datasets.longley.load()
    >>> data.exog = sm.add_constant(data.exog)
    >>> model = sm.OLS(data.endog, data.exog)
    >>> mod_fit = model.fit()
    >>> res = mod_fit.resid # residuals
    >>> pplot = sm.ProbPlot(res)
    >>> fig = pplot.qqplot()
    >>> h = plt.title("Ex. 1 - qqplot - residuals of OLS fit")
    >>> plt.show()

    qqplot of the residuals against quantiles of t-distribution with 4
    degrees of freedom:

    >>> # example 2
    >>> import scipy.stats as stats
    >>> pplot = sm.ProbPlot(res, stats.t, distargs=(4,))
    >>> fig = pplot.qqplot()
    >>> h = plt.title("Ex. 2 - qqplot - residuals against quantiles of t-dist")
    >>> plt.show()

    qqplot against same as above, but with mean 3 and std 10:

    >>> # example 3
    >>> pplot = sm.ProbPlot(res, stats.t, distargs=(4,), loc=3, scale=10)
    >>> fig = pplot.qqplot()
    >>> h = plt.title("Ex. 3 - qqplot - resids vs quantiles of t-dist")
    >>> plt.show()

    Automatically determine parameters for t distribution including the
    loc and scale:

    >>> # example 4
    >>> pplot = sm.ProbPlot(res, stats.t, fit=True)
    >>> fig = pplot.qqplot(line="45")
    >>> h = plt.title("Ex. 4 - qqplot - resids vs. quantiles of fitted t-dist")
    >>> plt.show()

    A second `ProbPlot` object can be used to compare two separate sample
    sets by using the `other` kwarg in the `qqplot` and `ppplot` methods.

    >>> # example 5
    >>> import numpy as np
    >>> x = np.random.normal(loc=8.25, scale=2.75, size=37)
    >>> y = np.random.normal(loc=8.75, scale=3.25, size=37)
    >>> pp_x = sm.ProbPlot(x, fit=True)
    >>> pp_y = sm.ProbPlot(y, fit=True)
    >>> fig = pp_x.qqplot(line="45", other=pp_y)
    >>> h = plt.title("Ex. 5 - qqplot - compare two sample sets")
    >>> plt.show()

    In qqplot, sample size of `other` can be equal or larger than the first.
    In case of larger, size of `other` samples will be reduced to match the
    size of the first by interpolation

    >>> # example 6
    >>> x = np.random.normal(loc=8.25, scale=2.75, size=37)
    >>> y = np.random.normal(loc=8.75, scale=3.25, size=57)
    >>> pp_x = sm.ProbPlot(x, fit=True)
    >>> pp_y = sm.ProbPlot(y, fit=True)
    >>> fig = pp_x.qqplot(line="45", other=pp_y)
    >>> title = "Ex. 6 - qqplot - compare different sample sizes"
    >>> h = plt.title(title)
    >>> plt.show()

    In ppplot, sample size of `other` and the first can be different. `other`
    will be used to estimate an empirical cumulative distribution function
    (ECDF). ECDF(x) will be plotted against p(x)=0.5/n, 1.5/n, ..., (n-0.5)/n
    where x are sorted samples from the first.

    >>> # example 7
    >>> x = np.random.normal(loc=8.25, scale=2.75, size=37)
    >>> y = np.random.normal(loc=8.75, scale=3.25, size=57)
    >>> pp_x = sm.ProbPlot(x, fit=True)
    >>> pp_y = sm.ProbPlot(y, fit=True)
    >>> pp_y.ppplot(line="45", other=pp_x)
    >>> plt.title("Ex. 7A- ppplot - compare two sample sets, other=pp_x")
    >>> pp_x.ppplot(line="45", other=pp_y)
    >>> plt.title("Ex. 7B- ppplot - compare two sample sets, other=pp_y")
    >>> plt.show()

    The following plot displays some options, follow the link to see the
    code.

    .. plot:: plots/graphics_gofplots_qqplot.py
    F r   r	   c                    || _         || _        |j        d         | _        || _        || _        t          |t          j        j	                  | _
        | j
        r#|s|dk    s|dk    s|dk    rt          d          i | _        | j
        rk|| _        |j        }|j        }	|	;t          t!          t"          j        |	                    d                              }
nd}
t)          |
          }|j        }t)          |          |dz   k    r||         | _        n |j                            d|          | _        t)          |          |dz   k    r||dz            | _        n |j                            d|          | _        g }t5          |
          D ]>\  }}||j        v r|j        |         }n|j        |         }|                    |           ?t8          j        || j        | j        f         | _        d S |r|                    |          | _        | j        d	         | _        | j        d
         | _        t)          | j                  dk    r+ || j        d d	         i t?          dd          | _        d S  |dd          | _        d S |s|dk    s|dk    r	  ||i t?          ||          | _        nj# t@          $ r] d!                    d |D                       }d}|"                    |||          }tG          d"                    |                    w xY w|| _        || _        t8          j        |||f         | _        d S || _        || _        || _        t8          j        ||f         | _        d S )Nr   r	   r   zIFrozen distributions cannot be combined with fit, loc, scale or distargs.,loc   scale)r   r   z, c                 ,    g | ]}t          |          S r   str).0das     ]/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/graphics/gofplots.py
<listcomp>z%ProbPlot.__init__.<locals>.<listcomp>   s    %A%A%A"c"gg%A%A%A    z*dist({distargs}, loc={loc}, scale={scale}))distargsr   r   zInitializing the distribution failed.  This can occur if distargs contains loc or scale. The distribution initialization command is:
{cmd})cmd)$dataashapenobsr    fit
isinstancer   distributions	rv_frozen
_is_frozen
ValueError_cachedistshapestuplemapr   stripsplitlenargsr   kwdsgetr   	enumerateappendnpr_
fit_paramsdict	Exceptionjoinformat	TypeError)selfr"   r-   r&   r    r#   r   r   dist_genr.   
shape_argsnumargsr4   r;   iargvaluer!   s                     r   __init__zProbPlot.__init__   s    	JqM	 $T5+>+HII? 		!88uzzX^^   
 ? 6	0DIyH_F!"3sy&,,s2C2C#D#DEE


*ooG9D4yyGaK''=9==444yyGaK''!'A+.

!Y]]7E::
J#J// ) )3$)## IcNEE IaLE!!%(((( eJ$*$DEDOOO 	0"hhtnnDOr*DH,DJ4?##a'' D$/#2#"6O$1A:N:N:NOO			 DQa000			 	0UaZZ D(Ids%.H.H.HII		 	 	 	99%A%A%A%A%ABBBjj(5jII! "(C	  		 DHDJ eHc5$89DOOODIDHDJ eCJ/DOOOs   J: :A'L!c                 6    t          | j        | j                  S )zTheoretical percentiles)plotting_posr%   r#   rA   s    r   theoretical_percentilesz ProbPlot.theoretical_percentiles   s     DItv...r   c                    	 | j                             | j                  S # t          $ r | j         j         d}t          |          t
          $ r,}d| j         j         } t          |          |          d}~ww xY w)zTheoretical quantilesz( requires more parameters to compute ppfzfailed to compute the ppf of N)r-   ppfrL   r@   namer=   type)rA   msgexcs      r   theoretical_quantileszProbPlot.theoretical_quantiles  s    	!9==!=>>> 	! 	! 	!Y^MMMCC..  	! 	! 	!B$).BBC$s))C.. 	!s   ! 1A>'A99A>c                 X    t          j        t          j        | j                            S )zsorted data)r9   sortarrayr"   rK   s    r   sorted_datazProbPlot.sorted_data  s      wrx	**+++r   c                 x    | j         r-| j        dk    r"| j        dk    r| j        | j        z
  | j        z  S | j        S )zsample quantilesr   r	   )r&   r   r   rW   rK   s    r   sample_quantileszProbPlot.sample_quantiles  sB     8 	$A$*//$tx/4:==##r   c                     t          | j        d           | j        r| j                            | j                  S | j        | j        d         z
  | j        d         z  }| j                            |          S )zSample percentilescdfr   r   )
_check_forr-   r*   r[   rW   r;   )rA   	quantiless     r   sample_percentileszProbPlot.sample_percentiles  ss     	49e$$$? 	39==!1222%(;;t@
 
	 y}}Y'''r   Nc                    |rt          |t                    }|st          |          }| j        } t          |j                  | j                  }	t          ||	| j        f||d|\  }
}|d}|d}n,t          | j        | j        | j        f||d|\  }
}|d}|d}|                    |           |	                    |           |
                    ddg           |                    ddg           |
S )	a  
        Plot of the percentiles of x versus the percentiles of a distribution.

        Parameters
        ----------
        xlabel : str or None, optional
            User-provided labels for the x-axis. If None (default),
            other values are used depending on the status of the kwarg `other`.
        ylabel : str or None, optional
            User-provided labels for the y-axis. If None (default),
            other values are used depending on the status of the kwarg `other`.
        line : {None, "45", "s", "r", q"}, optional
            Options for the reference line to which the data is compared:

            - "45": 45-degree line
            - "s": standardized line, the expected order statistics are
              scaled by the standard deviation of the given sample and have
              the mean added to them
            - "r": A regression line is fit
            - "q": A line is fit through the quartiles.
            - None: by default no reference line is added to the plot.

        other : ProbPlot, array_like, or None, optional
            If provided, ECDF(x) will be plotted against p(x) where x are
            sorted samples from `self`. ECDF is an empirical cumulative
            distribution function estimated from `other` and
            p(x) = 0.5/n, 1.5/n, ..., (n-0.5)/n where n is the number of
            samples in `self`. If an array-object is provided, it will be
            turned into a `ProbPlot` instance default parameters. If not
            provided (default), `self.dist(x)` is be plotted against p(x).

        ax : AxesSubplot, optional
            If given, this subplot is used to plot in instead of a new figure
            being created.
        **plotkwargs
            Additional arguments to be passed to the `plot` command.

        Returns
        -------
        Figure
            If `ax` is None, the created figure.  Otherwise the figure to which
            `ax` is connected.
        NaxlinezProbabilities of 2nd SamplezProbabilities of 1st SamplezTheoretical ProbabilitieszSample Probabilities              ?)r'   r   rL   r   rY   _do_plotr-   r^   
set_xlabel
set_ylabelset_xlimset_ylim)rA   xlabelylabelrb   otherra   
plotkwargscheck_otherp_xecdf_xfigs              r   ppplotzProbPlot.ppplot%  sI   h $UH55K ( .C1T%011$2GHHFVTY+-D <F GC ~6~6 ,'	    GC ~4~/
f
f
S#J
S#J
r   swapc                    |t          |t                    }|st          |          }| j        }	|j        }
t          |	          t          |
          k    rt	          d          t          |	          t          |
          k     r:t          | j        | j                  }t          j	        
                    |
|          }
t          |
|	| j        f||d|\  }}|d}|d}|r||}}n,t          | j        | j        | j        f||d|\  }}|d}|d}|                    |           |                    |           |S )a  
        Plot of the quantiles of x versus the quantiles/ppf of a distribution.

        Can also be used to plot against the quantiles of another `ProbPlot`
        instance.

        Parameters
        ----------
        xlabel : {None, str}
            User-provided labels for the x-axis. If None (default),
            other values are used depending on the status of the kwarg `other`.
        ylabel : {None, str}
            User-provided labels for the y-axis. If None (default),
            other values are used depending on the status of the kwarg `other`.
        line : {None, "45", "s", "r", q"}, optional
            Options for the reference line to which the data is compared:

            - "45" - 45-degree line
            - "s" - standardized line, the expected order statistics are scaled
              by the standard deviation of the given sample and have the mean
              added to them
            - "r" - A regression line is fit
            - "q" - A line is fit through the quartiles.
            - None - by default no reference line is added to the plot.

        other : {ProbPlot, array_like, None}, optional
            If provided, the sample quantiles of this `ProbPlot` instance are
            plotted against the sample quantiles of the `other` `ProbPlot`
            instance. Sample size of `other` must be equal or larger than
            this `ProbPlot` instance. If the sample size is larger, sample
            quantiles of `other` will be interpolated to match the sample size
            of this `ProbPlot` instance. If an array-like object is provided,
            it will be turned into a `ProbPlot` instance using default
            parameters. If not provided (default), the theoretical quantiles
            are used.
        ax : AxesSubplot, optional
            If given, this subplot is used to plot in instead of a new figure
            being created.
        swap : bool, optional
            Flag indicating to swap the x and y labels.
        **plotkwargs
            Additional arguments to be passed to the `plot` command.

        Returns
        -------
        Figure
            If `ax` is None, the created figure.  Otherwise the figure to which
            `ax` is connected.
        NzLSample size of `other` must be equal or larger than this `ProbPlot` instancer`   zQuantiles of 2nd SamplezQuantiles of 1st SamplezTheoretical QuantilesSample Quantiles)r'   r   rY   r3   r+   rJ   r%   r#   r   mstats
mquantilesre   r-   rS   rf   rg   )rA   rj   rk   rb   rl   ra   rs   rm   rn   s_selfs_otherprq   s                r   r   zProbPlot.qqplot  s   v $UH55K ( *F,G6{{S\\)) =   Vs7||++ !DF33,11'1==/1 @J GC ~2~2 0!' *%	    GC ~0~+
f
f
r   c                 P   |r2t          | j        ddd         | j        | j        f||d|\  }}|d}n(t          | j        | j        | j        f||d|\  }}|d}|d}|                    |           |                    |           t          || j        | j                   |S )aw  
        Plot of unscaled quantiles of x against the prob of a distribution.

        The x-axis is scaled linearly with the quantiles, but the probabilities
        are used to label the axis.

        Parameters
        ----------
        xlabel : {None, str}, optional
            User-provided labels for the x-axis. If None (default),
            other values are used depending on the status of the kwarg `other`.
        ylabel : {None, str}, optional
            User-provided labels for the y-axis. If None (default),
            other values are used depending on the status of the kwarg `other`.
        line : {None, "45", "s", "r", q"}, optional
            Options for the reference line to which the data is compared:

            - "45" - 45-degree line
            - "s" - standardized line, the expected order statistics are scaled
              by the standard deviation of the given sample and have the mean
              added to them
            - "r" - A regression line is fit
            - "q" - A line is fit through the quartiles.
            - None - by default no reference line is added to the plot.

        exceed : bool, optional
            If False (default) the raw sample quantiles are plotted against
            the theoretical quantiles, show the probability that a sample will
            not exceed a given value. If True, the theoretical quantiles are
            flipped such that the figure displays the probability that a
            sample will exceed a given value.
        ax : AxesSubplot, optional
            If given, this subplot is used to plot in instead of a new figure
            being created.
        **plotkwargs
            Additional arguments to be passed to the `plot` command.

        Returns
        -------
        Figure
            If `ax` is None, the created figure.  Otherwise the figure to which
            `ax` is connected.
        Nr   r`   zProbability of Exceedance (%)zNon-exceedance Probability (%)ru   )re   rS   rW   r-   rf   rg   _fmt_probplot_axisr%   )rA   rj   rk   rb   exceedra   rm   rq   s           r   probplotzProbPlot.probplot  s    h  	:*44R40 	    GC ~8 * 	    GC ~9>'F
f
f2ty$)444
r   )NNNNN)NNNNNF)NNNFN)__name__
__module____qualname____doc__r   normrH   r   rL   rS   rW   rY   r^   rr   boolr   r~   r   r   r   r   r      sj       V Vv Z
Q0 Q0 Q0 Q0f / / ^/ 	! 	! ^	! , , ^, $ $ ^$ ( ( ^( Y Y Y Yz i i i i i iZ S S S S S Sr   r   r   Fc	           	      R    t          | ||||||          }
 |
j        d||d|	}|S )ak  
    Q-Q plot of the quantiles of x versus the quantiles/ppf of a distribution.

    Can take arguments specifying the parameters for dist or fit them
    automatically. (See fit under Parameters.)

    Parameters
    ----------
    data : array_like
        A 1d data array.
    dist : callable
        Comparison distribution. The default is
        scipy.stats.distributions.norm (a standard normal).
    distargs : tuple
        A tuple of arguments passed to dist to specify it fully
        so dist.ppf may be called.
    a : float
        Offset for the plotting position of an expected order statistic, for
        example. The plotting positions are given by (i - a)/(nobs - 2*a + 1)
        for i in range(0,nobs+1)
    loc : float
        Location parameter for dist
    scale : float
        Scale parameter for dist
    fit : bool
        If fit is false, loc, scale, and distargs are passed to the
        distribution. If fit is True then the parameters for dist
        are fit automatically using dist.fit. The quantiles are formed
        from the standardized data, after subtracting the fitted loc
        and dividing by the fitted scale.
    line : {None, "45", "s", "r", "q"}
        Options for the reference line to which the data is compared:

        - "45" - 45-degree line
        - "s" - standardized line, the expected order statistics are scaled
          by the standard deviation of the given sample and have the mean
          added to them
        - "r" - A regression line is fit
        - "q" - A line is fit through the quartiles.
        - None - by default no reference line is added to the plot.

    ax : AxesSubplot, optional
        If given, this subplot is used to plot in instead of a new figure being
        created.
    **plotkwargs
        Additional matplotlib arguments to be passed to the `plot` command.

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

    See Also
    --------
    scipy.stats.probplot

    Notes
    -----
    Depends on matplotlib. If `fit` is True then the parameters are fit using
    the distribution's fit() method.

    Examples
    --------
    >>> import statsmodels.api as sm
    >>> from matplotlib import pyplot as plt
    >>> data = sm.datasets.longley.load()
    >>> exog = sm.add_constant(data.exog)
    >>> mod_fit = sm.OLS(data.endog, exog).fit()
    >>> res = mod_fit.resid # residuals
    >>> fig = sm.qqplot(res)
    >>> plt.show()

    qqplot of the residuals against quantiles of t-distribution with 4 degrees
    of freedom:

    >>> import scipy.stats as stats
    >>> fig = sm.qqplot(res, stats.t, distargs=(4,))
    >>> plt.show()

    qqplot against same as above, but with mean 3 and std 10:

    >>> fig = sm.qqplot(res, stats.t, distargs=(4,), loc=3, scale=10)
    >>> plt.show()

    Automatically determine parameters for t distribution including the
    loc and scale:

    >>> fig = sm.qqplot(res, stats.t, fit=True, line="45")
    >>> plt.show()

    The following plot displays some options, follow the link to see the code.

    .. plot:: plots/graphics_gofplots_qqplot.py
    )r-   r    r&   r#   r   r   r`   r   )r   r   )r"   r-   r    r#   r   r   r&   rb   ra   rm   r~   rq   s               r   r   r   A  sM    V 4(qc  H (/
9Rd
9
9j
9
9CJr   c                 N   t          | t                    st          |           } t          |t                    st          |          }|j        j        d         | j        j        d         k    r|                     |||||          }n|                    |||| |d          }|S )a
  
    Q-Q Plot of two samples' quantiles.

    Can take either two `ProbPlot` instances or two array-like objects. In the
    case of the latter, both inputs will be converted to `ProbPlot` instances
    using only the default values - so use `ProbPlot` instances if
    finer-grained control of the quantile computations is required.

    Parameters
    ----------
    data1 : {array_like, ProbPlot}
        Data to plot along x axis. If the sample sizes are unequal, the longer
        series is always plotted along the x-axis.
    data2 : {array_like, ProbPlot}
        Data to plot along y axis. Does not need to have the same number of
        observations as data 1. If the sample sizes are unequal, the longer
        series is always plotted along the x-axis.
    xlabel : {None, str}
        User-provided labels for the x-axis. If None (default),
        other values are used.
    ylabel : {None, str}
        User-provided labels for the y-axis. If None (default),
        other values are used.
    line : {None, "45", "s", "r", q"}
        Options for the reference line to which the data is compared:

        - "45" - 45-degree line
        - "s" - standardized line, the expected order statistics are scaled
          by the standard deviation of the given sample and have the mean
          added to them
        - "r" - A regression line is fit
        - "q" - A line is fit through the quartiles.
        - None - by default no reference line is added to the plot.

    ax : AxesSubplot, optional
        If given, this subplot is used to plot in instead of a new figure being
        created.

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

    See Also
    --------
    scipy.stats.probplot

    Notes
    -----
    1) Depends on matplotlib.
    2) If `data1` and `data2` are not `ProbPlot` instances, instances will be
       created using the default parameters. Therefore, it is recommended to use
       `ProbPlot` instance if fine-grained control is needed in the computation
       of the quantiles.

    Examples
    --------
    >>> import statsmodels.api as sm
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from statsmodels.graphics.gofplots import qqplot_2samples
    >>> x = np.random.normal(loc=8.5, scale=2.5, size=37)
    >>> y = np.random.normal(loc=8.0, scale=3.0, size=37)
    >>> pp_x = sm.ProbPlot(x)
    >>> pp_y = sm.ProbPlot(y)
    >>> qqplot_2samples(pp_x, pp_y)
    >>> plt.show()

    .. plot:: plots/graphics_gofplots_qqplot_2samples.py

    >>> fig = qqplot_2samples(pp_x, pp_y, xlabel=None, ylabel=None,
    ...                       line=None, ax=None)
    r   )rj   rk   rb   rl   ra   T)rj   rk   rb   rl   ra   rs   )r'   r   r"   r$   r   )data1data2rj   rk   rb   ra   rq   s          r   r   r     s    Z eX&&  eX&&  zUZ-a000ll&t5R  
 
 ll  
 
 Jr   r-c                 J   |                                 }dD ]4}||v r.|                    d|           |                    |d          } n5dD ]4}||v r.|                    d|           |                    |d          } n5|r|                    d|           |dk    rt          |                                 |                                           }	t          |	d                   |	d<   t          |	d	                   |	d	<    | j        |	|	fi | | 	                    |	           | 
                    |	           d
S ||t          d          t          j        |          }t          j        |          }|dk    rEt          |t          |                                                    j        } | j        ||fi | d
S |dk    rAt          j        |          t          j        |          }}
||
z  |z   } | j        ||fi | d
S |dk    rt)          |d           t+          j        |d          }t+          j        |d          }|                    ddg          }||z
  t          j        |          z  }
||
|d         z  z
  } | j        ||
|z  |z   fi | d
S d
S )a  
    Plot a reference line for a qqplot.

    Parameters
    ----------
    ax : matplotlib axes instance
        The axes on which to plot the line
    line : str {"45","r","s","q"}
        Options for the reference line to which the data is compared.:

        - "45" - 45-degree line
        - "s"  - standardized line, the expected order statistics are scaled by
                 the standard deviation of the given sample and have the mean
                 added to them
        - "r"  - A regression line is fit
        - "q"  - A line is fit through the quartiles.
        - None - By default no reference line is added to the plot.

    x : ndarray
        X data for plot. Not needed if line is "45".
    y : ndarray
        Y data for plot. Not needed if line is "45".
    dist : scipy.stats.distribution
        A scipy.stats distribution, needed if line is "q".
    fmt : str, optional
        Line format string passed to `plot`.
    **lineoptions
        Additional arguments to be passed to the `plot` command.

    Notes
    -----
    There is no return value. The line is plotted on the given `ax`.

    Examples
    --------
    Import the food expenditure dataset.  Plot annual food expenditure on x-axis
    and household income on y-axis.  Use qqline to add regression line into the
    plot.

    >>> import statsmodels.api as sm
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from statsmodels.graphics.gofplots import qqline

    >>> foodexp = sm.datasets.engel.load()
    >>> x = foodexp.exog
    >>> y = foodexp.endog
    >>> ax = plt.subplot(111)
    >>> plt.scatter(x, y)
    >>> ax.set_xlabel(foodexp.exog_name[0])
    >>> ax.set_ylabel(foodexp.endog_name)
    >>> qqline(ax, "r", x, y)
    >>> plt.show()

    .. plot:: plots/graphics_gofplots_qqplot_qqline.py
    )-z--z-.:	linestyle ).r   ov^<>12348srz   P*hH+xXDd|_markercolor45r   r	   Nz*If line is not 45, x and y cannot be None.rr   qrN      K   g      ?g      ?)copy
setdefaultreplacer   get_xlimget_ylimminmaxplotrh   ri   r+   r9   rV   r   r   r&   fittedvaluesstdmeanr\   r   scoreatpercentilerN   diff)ra   rb   r   yr-   fmtlineoptionslsr   end_ptsmbref_lineq25q75theoretical_quartiless                   r   r   r     s   r ""$$K$  99"";333++b"%%CE   6 S==""8V444++fb))CE   -w,,,t||r{{}}bkkmm44__
__
00K000
G
GyAIEFFF
A
As{{ <??##''))61$$$$$$$	vayy"'!**1q5198++{+++++	4%a,,%a,, $$ 6 63Y"'"7888!+A...1q519,,,,,,, 
r   rc   c                 \    ||n|}t          j        d| dz             |z
  | dz   |z
  |z
  z  S )a  
    Generates sequence of plotting positions

    Parameters
    ----------
    nobs : int
        Number of probability points to plot
    a : float, default 0.0
        alpha parameter for the plotting position of an expected order
        statistic
    b : float, default None
        beta parameter for the plotting position of an expected order
        statistic. If None, then b is set to a.

    Returns
    -------
    ndarray
        The plotting positions

    Notes
    -----
    The plotting positions are given by (i - a)/(nobs + 1 - a - b) for i in
    range(1, nobs+1)

    See Also
    --------
    scipy.stats.mstats.plotting_positions
        Additional information on alpha and beta
    Nrd   r	   )r9   arange)r%   r#   r   s      r   rJ   rJ     s>    < YAAIc4!8$$q(TAX\A-=>>r   c                    t          |d           t          j        dddt                    }t          j        g d          }t          j        ||d|ddd	         z
  f         }|d
k    r't          j        |dz  |d|ddd	         dz  z
  f         }|dk    r't          j        |dz  |d|ddd	         dz  z
  f         }|dz  }|                    |          }|                     |           |                     d |dz  D             dddd           | 	                    |
                                |                                g           dS )a  
    Formats a theoretical quantile axis to display the corresponding
    probabilities on the quantiles' scale.

    Parameters
    ----------
    ax : AxesSubplot, optional
        The axis to be formatted
    nobs : scalar
        Number of observations in the sample
    dist : scipy.stats.distribution
        A scipy.stats distribution sufficiently specified to implement its
        ppf() method.

    Returns
    -------
    There is no return value. This operates on `ax` in place
    rN   
   Z   	   )dtype)rd   r      d   Nr   2   i  g      Y@c                 ,    g | ]}t          |          S r   r   )r   lbls     r   r   z&_fmt_probplot_axis.<locals>.<listcomp>  s    000cS000r   -   anchorrightcenter)rotationrotation_modehorizontalalignmentverticalalignment)r\   r9   linspacefloatrV   r:   rN   
set_xticksset_xticklabelsrh   r   r   )ra   r-   r%   
axis_probssmall
axis_qntlss         r   r|   r|     sh   & tURQe444JH[[[!!Euj#ddd*;;<JrzzU52:z3tttr9I3IIJ
s{{U53;
C%"+:K4KKL
%J*%%JMM*00j3.000#"     KK!!:>>#3#3455555r   r   c                 \   ddddd} |j         di | |                    dd          }	t          j        |          \  }
}|                    d           |r |j        | ||fd|	i| n |j        | ||fi | |r,|dvrd	|z  }t          |          t          ||| ||
           |
|fS )a  
    Boiler plate plotting function for the `ppplot`, `qqplot`, and
    `probplot` methods of the `ProbPlot` class

    Parameters
    ----------
    x : array_like
        X-axis data to be plotted
    y : array_like
        Y-axis data to be plotted
    dist : scipy.stats.distribution
        A scipy.stats distribution, needed if `line` is "q".
    line : {"45", "s", "r", "q", None}, default None
        Options for the reference line to which the data is compared.
    ax : AxesSubplot, optional
        If given, this subplot is used to plot in instead of a new figure being
        created.
    fmt : str, optional
        matplotlib-compatible formatting string for the data markers
    kwargs : keywords
        These are passed to matplotlib.plot

    Returns
    -------
    fig : Figure
        The figure containing `ax`.
    ax : AxesSubplot
        The original axes if provided.  Otherwise a new instance.
    r   C0none)r   markerfacecolormarkeredgecolorr   wherepreg{Gz?)r   r   r   r   z!%s option for line not understood)r   r   r-   r   )	updatepopr
   create_mpl_axset_xmarginstepr   r+   r   )r   r   r-   rb   ra   r   r   kwargs
plot_styler   rq   rQ   s               r   re   re     s	   B 	 J JNN7E**E!"%%GCNN4 )1c555*55551c((Z((( .,,,5<CS//!r41----7Nr   rN   c                 L    t          | |          st          d| d          d S )Nzdistribution must have a z method)hasattrAttributeError)r-   attrs     r   r\   r\     s;    4 HFFFFGGGH Hr   )NNNN)NNNr   )rc   N)NNNr   F)rN   )statsmodels.compat.pythonr   numpyr9   scipyr   statsmodels.distributionsr   #statsmodels.regression.linear_modelr   statsmodels.tools.decoratorsr   statsmodels.tools.toolsr   r   r
   __all__r   r   r   r   r   rJ   r|   re   r\   r   r   r   <module>r      s   * * * * * *           * * * * * * 3 3 3 3 3 3 7 7 7 7 7 7 0 0 0 0 0 0      
=
=
=n n n n n n n nf 
	
	o o o of ;?` ` ` `F}- }- }- }-B? ? ? ?D%6 %6 %6R 8=8 8 8 8vH H H H H Hr   