
    M/Phɭ                        d Z ddlmZ ddlmZmZ ddl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mZmZ ddlmZ ddlmZ ddlmZmZmZm Z m!Z! g dZ"d Z#d2dZ$d3dZ%d4dZ&d Z'di di dddfdZ(d5dZ)d4dZ*d5dZ+	 	 d6dZ, e ej-        d7i ddi          	 	 	 d8d#            Z. e ej-        d7i dd$i          	 	 d9d%            Z/ e e j-        dd&i                    d:d'            Z0 e e j-        dd(i                    d:d)            Z1 eedd(iz            	 	 d;d*            Z2 ee!dd(iz            d4d+            Z3 eedd,iz            	 	 d<d.            Z4d=d/Z5d0 Z6	 	 d>d1Z7dS )?zPartial Regression plot and residual plots to find misspecification


Author: Josef Perktold
License: BSD-3
Created: 2011-01-23

update
2011-06-05 : start to convert example to usable functions
2011-10-27 : docstrings

    )Appender)lrangelzipN)dmatrix)GEE)GLM)utils)lowess)GLSOLSWLS)wls_prediction_std)maybe_unwrap_results   )_plot_added_variable_doc_plot_ceres_residuals_doc_plot_influence_doc_plot_leverage_resid2_doc_plot_partial_residuals_doc)plot_fitplot_regress_exogplot_partregress	plot_ccprr   plot_partregress_gridplot_ccpr_grid
add_lowessabline_plotinfluence_plotplot_leverage_resid2added_variable_residspartial_residsceres_residsplot_added_variableplot_partial_residualsplot_ceres_residualsc                 ,    d| j         dz   z  | j        z  S )N       @r   )df_modelnobs)resultss    d/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/graphics/regressionplots.py_high_leverager,   ,   s    !A%&w|33    皙?c                    |                                  |         j        }|                                  |         j        }t          ||fd|i|}|                     |dddf         |dddf         dd           | j        S )a  
    Add Lowess line to a plot.

    Parameters
    ----------
    ax : AxesSubplot
        The Axes to which to add the plot
    lines_idx : int
        This is the line on the existing plot to which you want to add
        a smoothed lowess line.
    frac : float
        The fraction of the points to use when doing the lowess fit.
    lowess_kwargs
        Additional keyword arguments are passes to lowess.

    Returns
    -------
    Figure
        The figure that holds the instance.
    fracNr   r   rg      ?)lw)	get_lines_y_xr
   plotfigure)ax	lines_idxr0   lowess_kwargsy0x0lress          r+   r   r   1   s    * 
		"	%B			"	%B"b55t5}55DGGDAJQQQT
CCG0009r-   Tc                 "   t          j        |          \  }}t          j        || j                  \  }}t	          |           } | j        j        }| j        j        dd|f         }	t          j        |	          }
||
         }|	|
         }	|	                    |	|d| j        j
                   ||	                    |	||
         dd           d|z  } |j	        |	| j        |
         dfdd	d
| |du r:t          |           \  }}}|                    |	||
         ||
         ddd           |                    |           |                    |           |                    | j        j
                   |                    dd           |S )aQ  
    Plot fit against one regressor.

    This creates one graph with the scatterplot of observed values
    compared to fitted values.

    Parameters
    ----------
    results : Results
        A result instance with resid, model.endog and model.exog as
        attributes.
    exog_idx : {int, str}
        Name or index of regressor in exog matrix.
    y_true : array_like. optional
        If this is not None, then the array is added to the plot.
    ax : AxesSubplot, optional
        If given, this subplot is used to plot in instead of a new figure being
        created.
    vlines : bool, optional
        If this not True, then the uncertainty (pointwise prediction intervals) of the fit is not
        plotted.
    **kwargs
        The keyword arguments are passed to the plot command for the fitted
        values points.

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

    Examples
    --------
    Load the Statewide Crime data set and perform linear regression with
    `poverty` and `hs_grad` as variables and `murder` as the response

    >>> import statsmodels.api as sm
    >>> import matplotlib.pyplot as plt

    >>> data = sm.datasets.statecrime.load_pandas().data
    >>> murder = data['murder']
    >>> X = data[['poverty', 'hs_grad']]

    >>> X["constant"] = 1
    >>> y = murder
    >>> model = sm.OLS(y, X)
    >>> results = model.fit()

    Create a plot just for the variable 'Poverty.'
    Note that vertical bars representing uncertainty are plotted since vlines is true

    >>> fig, ax = plt.subplots()
    >>> fig = sm.graphics.plot_fit(results, 0, ax=ax)
    >>> ax.set_ylabel("Murder Rate")
    >>> ax.set_xlabel("Poverty Level")
    >>> ax.set_title("Linear Regression")

    >>> plt.show()

    .. plot:: plots/graphics_plot_fit_ex.py
    Nbo)labelzb-zTrue valueszFitted values versus %sDr1   fitted)colorr@   Tr   kffffff?	linewidthrC   alphabest)loc	numpoints)r	   create_mpl_axmaybe_name_or_idxmodelr   endogexognpargsortr6   endog_namesfittedvaluesr   vlines	set_title
set_xlabel
set_ylabellegend)r*   exog_idxy_truer8   rU   kwargsfig	exog_nameyx1
x1_argsorttitle_iv_liv_us                  r+   r   r   M   s   ~ !"%%GC1(GMJJIx"7++G 	A		AAAxK	(BBJ	*A	JBGGB4w}8G999
F:&MBBB%	1EBGB$Z0# &S& &$& & &~~*7334
		"d:&Z(8A2 	 	' 	' 	' LLMM)MM'-+,,,II&AI&&&Jr-   c                 (   t          j        |          }t          j        || j                  \  }}t	          |           } | j        j        }| j        j        dd|f         }t          |           \  }}}|                    ddd          }	|		                    || j        j
        ddd|           |		                    || j        dd	d
d           |	                    |||ddd           |	                    dd           |	                    |           |	                    |           |	                    d           |                    ddd          }	|		                    || j        d           |	                    dd           |	                    d|z  d           |	                    |           |	                    d           |                    ddd          }	t'          j        | j        j        j        d         t,                    }
d|
|<   | j        j        dd|
f         }ddlm} t3          | j        j        j         |||| j        j        j                  |d|	          }|	                    dd           |                    ddd           }	t;          | ||	!          }|	                    d"d           |                    d#|z  d           |                                 |                     d$           |S )%a  Plot regression results against one regressor.

    This plots four graphs in a 2 by 2 figure: 'endog versus exog',
    'residuals versus exog', 'fitted versus exog' and
    'fitted plus residual versus exog'

    Parameters
    ----------
    results : result instance
        A result instance with resid, model.endog and model.exog as attributes.
    exog_idx : int or str
        Name or index of regressor in exog matrix.
    fig : Figure, optional
        If given, this figure is simply returned.  Otherwise a new figure is
        created.

    Returns
    -------
    Figure
        The value of `fig` if provided. Otherwise a new instance.

    Examples
    --------
    Load the Statewide Crime data set and build a model with regressors
    including the rate of high school graduation (hs_grad), population in urban
    areas (urban), households below poverty line (poverty), and single person
    households (single).  Outcome variable is the murder rate (murder).

    Build a 2 by 2 figure based on poverty showing fitted versus actual murder
    rate, residuals versus the poverty rate, partial regression plot of poverty,
    and CCPR plot for poverty rate.

    >>> import statsmodels.api as sm
    >>> import matplotlib.pyplot as plt
    >>> import statsmodels.formula.api as smf

    >>> fig = plt.figure(figsize=(8, 6))
    >>> crime_data = sm.datasets.statecrime.load_pandas()
    >>> results = smf.ols('murder ~ hs_grad + urban + poverty + single',
    ...                   data=crime_data.data).fit()
    >>> sm.graphics.plot_regress_exog(results, 'poverty', fig=fig)
    >>> plt.show()

    .. plot:: plots/graphics_regression_regress_exog.py
    N   r   obg?)rC   rH   r@   rA   r1   rB         ?)rC   r@   rH   rD   rE   rF   zY and Fitted vs. XlargefontsizerI   )rJ   r   black)r_   rC   zResiduals versus %sresid   F)Series)nameindex)
obs_labelsr8   zPartial regression plot   r8   z	CCPR PlotzRegression Plots for %stop)!r	   create_mpl_figrM   rN   r   rS   rP   r   add_subplotr6   rO   rT   rU   rV   rW   rX   rY   ro   axhlinerQ   onesshapeboolpandasrq   r   data
orig_endog
row_labelsr   suptitletight_layoutsubplots_adjust)r*   rZ   r]   r^   y_namer`   prstdrd   re   r8   	exog_notiexog_othersrq   s                r+   r   r      s   ^ 
s
#
#C1(GMJJIx"7++G ]&F		AAAxK	(B*733E4	Aq	!	!BGGB#S3fGMMMGGB$cH    IIb$BI???LL%L888MM)MM&II&I	Aq	!	!BGGBs###JJ'J"""LL&2WLEEEMM)MM'	Aq	!	!B*03T::IIh-$QQQ	\2K
7=-8!6"9(/(:(EG G G&5RA A AC LL*WL=== 
Aq	!	!B
GX"
-
-
-CLLwL/// LL*Y6LIIIC   Jr-   c                     t          | |                                          }t          ||                                          }t          |j        |j                                                  }|||ffS )a  Partial regression.

    regress endog on exog_i conditional on exog_others

    uses OLS

    Parameters
    ----------
    endog : array_like
    exog : array_like
    exog_others : array_like

    Returns
    -------
    res1c : OLS results instance

    (res1a, res1b) : tuple of OLS results instances
         results from regression of endog on exog_others and of exog_i on
         exog_others
    )r   fitro   )rO   exog_ir   res1ares1bres1cs         r+   _partial_regressionr     sh    , {##''))E$$((**EU[))--//E5%.  r-   Fc
           	         t          j        |          \  }}t          | t                    rt	          | dz   ||	          } t          |t                    rt	          |||	          }n?t          |t
                    r(d                    |          }t	          |||	          }n|}d}t          |t          j                  r|j	        dk    rd}n#t          |t          j                  r	|j        rd}t          |t                    rt	          |dz   ||	          }|rt          j        |           } t          j        |          } |j        | |dfi |
 t          | |                                          }t          |t          j                  rdn|j        }t          | t          j                  rd	n| j        j        d         }nt          | |                                          }t          ||                                          }|j        }|j        }|j        j        }|j        j        } |j        ||dfi |
 t          ||                                          }t/          dt          j        |j                  d         d
|          }|d	k    rd}|                    d|z             |                    d|z              |j        di | |du rQ||j        }n)t;          |d          r|j        }n|j        j        j        }|tA          tC          |                    }|durtC          |          tC          |          k    rtE          d          |#                    tI          dd                     t          j%        tA          tC          |                    |tM          |j        |j                  dgtC          |          z  dfd|i|}|r||j        |j        ffS |S )aN  Plot partial regression for a single regressor.

    Parameters
    ----------
    endog : {ndarray, str}
       The endogenous or response variable. If string is given, you can use a
       arbitrary translations as with a formula.
    exog_i : {ndarray, str}
        The exogenous, explanatory variable. If string is given, you can use a
        arbitrary translations as with a formula.
    exog_others : {ndarray, list[str]}
        Any other exogenous, explanatory variables. If a list of strings is
        given, each item is a term in formula. You can use a arbitrary
        translations as with a formula. The effect of these variables will be
        removed by OLS regression.
    data : {DataFrame, dict}
        Some kind of data structure with names if the other variables are
        given as strings.
    title_kwargs : dict
        Keyword arguments to pass on for the title. The key to control the
        fonts is fontdict.
    obs_labels : {bool, array_like}
        Whether or not to annotate the plot points with their observation
        labels. If obs_labels is a boolean, the point labels will try to do
        the right thing. First it will try to use the index of data, then
        fall back to the index of exog_i. Alternatively, you may give an
        array-like object corresponding to the observation numbers.
    label_kwargs : dict
        Keyword arguments that control annotate for the observation labels.
    ax : AxesSubplot, optional
        If given, this subplot is used to plot in instead of a new figure being
        created.
    ret_coords : bool
        If True will return the coordinates of the points in the plot. You
        can use this to add your own annotations.
    eval_env : int
        Patsy eval environment if user functions and formulas are used in
        defining endog or exog.
    **kwargs
        The keyword arguments passed to plot for the points.

    Returns
    -------
    fig : Figure
        If `ax` is None, the created figure.  Otherwise the figure to which
        `ax` is connected.
    coords : list, optional
        If ret_coords is True, return a tuple of arrays (x_coords, y_coords).

    See Also
    --------
    plot_partregress_grid : Plot partial regression for a set of regressors.

    Notes
    -----
    The slope of the fitted line is the that of `exog_i` in the full
    multiple regression. The individual points can be used to assess the
    influence of points on the estimated coefficient.

    Examples
    --------
    Load the Statewide Crime data set and plot partial regression of the rate
    of high school graduation (hs_grad) on the murder rate(murder).

    The effects of the percent of the population living in urban areas (urban),
    below the poverty line (poverty) , and in a single person household (single)
    are removed by OLS regression.

    >>> import statsmodels.api as sm
    >>> import matplotlib.pyplot as plt

    >>> crime_data = sm.datasets.statecrime.load_pandas()
    >>> sm.graphics.plot_partregress(endog='murder', exog_i='hs_grad',
    ...                              exog_others=['urban', 'poverty', 'single'],
    ...                              data=crime_data.data, obs_labels=False)
    >>> plt.show()

    .. plot:: plots/graphics_regression_partregress.py

    More detailed examples can be found in the Regression Plots notebook
    on the examples page.
    z-1)eval_env+Fr   Trh   xr_   rD   )rC   r8   z	e(%s | X)Partial Regression PlotNrs   z*obs_labels does not match length of exog_icenterbottom)havar      x-larger8   )r   )'r	   rL   
isinstancestrr   listjoinrQ   ndarraysizepd	DataFrameemptyasarrayr6   r   r   rr   design_infocolumn_namesro   rN   rS   r   paramsrW   rX   rV   rs   hasattrr   r   r   len
ValueErrorupdatedictannotate_axesr   )rO   r   r   r   title_kwargsrt   label_kwargsr8   
ret_coordsr   r\   r]   RHSRHS_isemtpyfitted_linex_axis_endog_namey_axis_endog_name	res_yaxis	res_xaxisxaxis_residyaxis_resids                        r+   r   r   /  s   n !"%%GC % ?dX>>>+s## k4(;;;	K	&	& hh{##c4(333K#rz"" sx{{	C	&	& 39 &# A$x@@@  :
5!!F##vs--f---%((,,..#-fbj#A#ARCCv{#-eRZ#@#@gCCeFWFdefFgsOO''))	$$((**	oo%O7%O7[#88888+{337799
aK$677:#"
M
M
MCCMM+ 11222MM+ 11222BL;;l;;; TJJVW%% 	9JJ"-8J F,,Jz??c&kk))IJJJDH:::;;; J!8!8*!%ioy!G!G"(C
OO!;Y1 1KM1 $01 1
  Y_io666
r-   c           	         ddl }t          j        |          }t          j        || j                  \  }}|                    | j        j        | j        j                  }| j        j        }|j	        d         }t          |          dz   dz  }	|	t          |          k    rdnd}
||\  }	}
|
dk    rdddii}t          j        | j        j                  }t          |          D ]\  }}t          |          }|                    |           |                    |dd|f         ||         	          }|                    |	|
|dz             }t'          ||                    |dd|f         ||                   |||d
           |                    d           |                    dd           |                                 |                    d           |S )a  
    Plot partial regression for a set of regressors.

    Parameters
    ----------
    results : Results instance
        A regression model results instance.
    exog_idx : {None, list[int], list[str]}
        The indices  or column names of the exog used in the plot, default is
        all.
    grid : {None, tuple[int]}
        If grid is given, then it is used for the arrangement of the subplots.
        The format of grid is  (nrows, ncols). If grid is None, then ncol is
        one, if there are only 2 subplots, and the number of columns is two
        otherwise.
    fig : Figure, optional
        If given, this figure is simply returned.  Otherwise a new figure is
        created.

    Returns
    -------
    Figure
        If `fig` is None, the created figure.  Otherwise `fig` itself.

    See Also
    --------
    plot_partregress : Plot partial regression for a single regressor.
    plot_ccpr : Plot CCPR against one regressor

    Notes
    -----
    A subplot is created for each explanatory variable given by exog_idx.
    The partial regression plot shows the relationship between the response
    and the given explanatory variable after removing the effect of all other
    explanatory variables in exog.

    References
    ----------
    See http://www.itl.nist.gov/div898/software/dataplot/refman1/auxillar/partregr.htm

    Examples
    --------
    Using the state crime dataset separately plot the effect of the each
    variable on the on the outcome, murder rate while accounting for the effect
    of all other variables in the model visualized with a grid of partial
    regression plots.

    >>> from statsmodels.graphics.regressionplots import plot_partregress_grid
    >>> import statsmodels.api as sm
    >>> import matplotlib.pyplot as plt
    >>> import statsmodels.formula.api as smf

    >>> fig = plt.figure(figsize=(8, 6))
    >>> crime_data = sm.datasets.statecrime.load_pandas()
    >>> results = smf.ols('murder ~ hs_grad + urban + poverty + single',
    ...                   data=crime_data.data).fit()
    >>> plot_partregress_grid(results, fig=fig)
    >>> plt.show()

    .. plot:: plots/graphics_regression_partregress_grid.py
    r   N)rr   r   rg   fontdictrm   small)columnsF)r8   r   rt    r   rk   rl   ffffff?rw   )r   r	   ry   rM   rN   rq   rO   rS   rP   r}   r   rQ   array
exog_names	enumerater   popr   rz   r   rV   r   r   r   )r*   rZ   gridr]   r   r^   r_   rP   k_varsnrowsncolsr   other_namesiidxothersr   r8   s                     r+   r   r     s   | MMM

s
#
#C1(GMJJIx 	gm)0IJJA=DZ]F ]]Q1$E#h--''AAQEuqyy"Z$9: (7=344KH%% 
 
3

3&&tAAAvI/:6/B ' D D__UE1q511FMM$qqq#v,/:3/? * A A$,$)	+ 	+ 	+ 	+ 	RLL*WL===C   Jr-   c                 H   t          j        |          \  }}t          j        || j                  \  }}t	          |           } | j        j        dd|f         }|| j        |         z  }|                    ||| j        z   d           ddl	m
} t          | ||                                                    }|j        }	t          |	i t          |          }|                    d           |                    d||fz             |                    d|z             |S )	a  
    Plot CCPR against one regressor.

    Generates a component and component-plus-residual (CCPR) plot.

    Parameters
    ----------
    results : result instance
        A regression results instance.
    exog_idx : {int, str}
        Exogenous, explanatory variable. If string is given, it should
        be the variable name that you want to use, and you can use arbitrary
        translations as with a formula.
    ax : AxesSubplot, optional
        If given, it 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
    --------
    plot_ccpr_grid : Creates CCPR plot for multiple regressors in a plot grid.

    Notes
    -----
    The CCPR plot provides a way to judge the effect of one regressor on the
    response variable by taking into account the effects of the other
    independent variables. The partial residuals plot is defined as
    Residuals + B_i*X_i versus X_i. The component adds the B_i*X_i versus
    X_i to show where the fitted line would lie. Care should be taken if X_i
    is highly correlated with any of the other independent variables. If this
    is the case, the variance evident in the plot will be an underestimate of
    the true variance.

    References
    ----------
    http://www.itl.nist.gov/div898/software/dataplot/refman1/auxillar/ccpr.htm

    Examples
    --------
    Using the state crime dataset plot the effect of the rate of single
    households ('single') on the murder rate while accounting for high school
    graduation rate ('hs_grad'), percentage of people in an urban area, and rate
    of poverty ('poverty').

    >>> import statsmodels.api as sm
    >>> import matplotlib.pyplot as plt
    >>> import statsmodels.formula.api as smf

    >>> crime_data = sm.datasets.statecrime.load_pandas()
    >>> results = smf.ols('murder ~ hs_grad + urban + poverty + single',
    ...                   data=crime_data.data).fit()
    >>> sm.graphics.plot_ccpr(results, 'single')
    >>> plt.show()

    .. plot:: plots/graphics_regression_ccpr.py
    Nrh   r   )add_constantrv   z*Component and component plus residual plotzResidual + %s*beta_%dz%s)r	   rL   rM   rN   r   rP   r   r6   ro   statsmodels.tools.toolsr   r   r   r   r   rV   rX   rW   )
r*   rZ   r8   r]   r^   r`   x1betar   modr   s
             r+   r   r   <  s(   | !"%%GC1(GMJJIx"7++G		AAAxK	(Bx((FGGB&,,,444444
fll2&&
'
'
+
+
-
-CZF
v
-
-
-CLL=>>>MM)Y,AABBBMM$"###Jr-   c                    t          j        |          }t          j        || j                  \  }}||\  }}nXt	          |          dk    r4t          t          j        t	          |          dz                      }d}nt	          |          }d}d}t          |          D ]x\  }}	| j        j	        dd|	f         
                                dk    rd}4|                    |||dz   |z
            }
t          | |	|
          }|
                    d           y|                    dd	
           |                                 |                    d           |S )a  
    Generate CCPR plots against a set of regressors, plot in a grid.

    Generates a grid of component and component-plus-residual (CCPR) plots.

    Parameters
    ----------
    results : result instance
        A results instance with exog and params.
    exog_idx : None or list of int
        The indices or column names of the exog used in the plot.
    grid : None or tuple of int (nrows, ncols)
        If grid is given, then it is used for the arrangement of the subplots.
        If grid is None, then ncol is one, if there are only 2 subplots, and
        the number of columns is two otherwise.
    fig : Figure, optional
        If given, this figure is simply returned.  Otherwise a new figure is
        created.

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

    See Also
    --------
    plot_ccpr : Creates CCPR plot for a single regressor.

    Notes
    -----
    Partial residual plots are formed as::

        Res + Betahat(i)*Xi versus Xi

    and CCPR adds::

        Betahat(i)*Xi versus Xi

    References
    ----------
    See http://www.itl.nist.gov/div898/software/dataplot/refman1/auxillar/ccpr.htm

    Examples
    --------
    Using the state crime dataset separately plot the effect of the each
    variable on the on the outcome, murder rate while accounting for the effect
    of all other variables in the model.

    >>> import statsmodels.api as sm
    >>> import matplotlib.pyplot as plt
    >>> import statsmodels.formula.api as smf

    >>> fig = plt.figure(figsize=(8, 8))
    >>> crime_data = sm.datasets.statecrime.load_pandas()
    >>> results = smf.ols('murder ~ hs_grad + urban + poverty + single',
    ...                   data=crime_data.data).fit()
    >>> sm.graphics.plot_ccpr_grid(results, fig=fig)
    >>> plt.show()

    .. plot:: plots/graphics_regression_ccpr_grid.py
    Nrg   r'   r   r   )rZ   r8   r   z&Component-Component Plus Residual Plotrk   rl   r   rw   )r	   ry   rM   rN   r   intrQ   ceilr   rP   varrz   r   rV   r   r   r   )r*   rZ   r   r]   r^   r   r   seen_constantr   r   r8   s              r+   r   r     sf   ~ 
s
#
#C1(GMJJIxuux==1Hb 01122EEEMMEEMH%%  3=aaaf%))++q00M__UE1Q3}+<==#"555
RLL9GLLLLC   Jr-   c                 8    ||                                 }nd}t          j        |          \  }}|r]|j        \   |P|j        j        dddf                                         |j        j        dddf                                         g}n) t          d          ||                                 }|d         z   z   |d         z   z   g}	|	                    |           ddl
m}
  G  fdd|
          } |||	fi |}|                    |           |j                            d|j                  |_        |j                            d	|j                  |_        |r|                    |           |r|                    |           |S )
a  
    Plot a line given an intercept and slope.

    Parameters
    ----------
    intercept : float
        The intercept of the line.
    slope : float
        The slope of the line.
    horiz : float or array_like
        Data for horizontal lines on the y-axis.
    vert : array_like
        Data for verterical lines on the x-axis.
    model_results : statsmodels results instance
        Any object that has a two-value `params` attribute. Assumed that it
        is (intercept, slope).
    ax : axes, optional
        Matplotlib axes instance.
    **kwargs
        Options passed to matplotlib.pyplot.plt.

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

    Examples
    --------
    >>> import numpy as np
    >>> import statsmodels.api as sm

    >>> np.random.seed(12345)
    >>> X = sm.add_constant(np.random.normal(0, 20, size=30))
    >>> y = np.dot(X, [25, 3.5]) + np.random.normal(0, 30, size=30)
    >>> mod = sm.OLS(y,X).fit()
    >>> fig = sm.graphics.abline_plot(model_results=mod)
    >>> ax = fig.axes[0]
    >>> ax.scatter(X[:,1], y)
    >>> ax.margins(.1)
    >>> import matplotlib.pyplot as plt
    >>> plt.show()

    .. plot:: plots/graphics_regression_abline.py
    Nr   z-specify slope and intercepty or model_resultsr   )Line2Dc                   6     e Zd Z fdZ fdZfdZ xZS )abline_plot.<locals>.ABLine2Dc                 V     t                      j        |i | d | _        d | _        d S N)super__init__id_xlim_callbackid_ylim_callback)selfargsr\   	__class__s      r+   r   z&abline_plot.<locals>.ABLine2D.__init__5  s5    EGGd-f---$(D!$(D!!!r-   c                     | j         }| j        r|j                            | j                   | j        r|j                            | j                   t                                                       d S r   )axesr   	callbacks
disconnectr   r   remove)r   r8   r   s     r+   r   z$abline_plot.<locals>.ABLine2D.remove:  sl    B$ ?''(=>>>$ ?''(=>>>GGNNr-   c                 P    |                     d           |                                } fd|D             }|d         }|                                }|d         z  z   |d         z  z   g}|                    ||           |j        j                                         d S )NFc                     g | ]}|u |	S  r   ).0childr   s     r+   
<listcomp>z@abline_plot.<locals>.ABLine2D.update_datalim.<locals>.<listcomp>E  s    DDDetmmummmr-   r   r   )set_autoscale_onget_childrenget_xlimset_datar7   canvasdraw)	r   r8   childrenablinesabliner   r_   	interceptslopes	   `      r+   update_datalimz,abline_plot.<locals>.ABLine2D.update_datalimB  s    &&&((HDDDD(DDDGQZFA1	)1Q4%<)+CDAOOAq!!!I!!#####r-   )__name__
__module____qualname__r   r   r   __classcell__)r   r   r   s   @r+   ABLine2Dr   4  sp        	) 	) 	) 	) 	)
	 	 	 	 		$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$r-   r   xlim_changedylim_changed)r   r	   rL   r   rN   rP   minmaxr   set_xlimmatplotlib.linesr   add_liner   connectr   r   r   hlinevline)r   r   horizvertmodel_resultsr8   r\   r   r]   data_yr   r   lines   ``           r+   r   r     s   \ 
~KKMM!"%%GC 	(/	59$)!!!Q$/3355$)!!!Q$/33557A %%*;LMMM9Ad5j"AaDJy$89FKKNNN ('''''$ $ $ $ $ $ $ $6 $ $ $2 8Av((((DKKL00ATUUDL00ATUUD 
 
Jr-   extra_params_doczresults: object
        Results for a fitted regression model.
    influence: instance
        The instance of Influence for model.皙?cooks0         ?c
           
         |}t          j        |          \  }}|                                                    d          r|j        d         }nY|                                                    d          r t          j        |j        d                   }nt          d|z            t          j	        |          }|dz  dz
  }||
                                z
  |z  |z  dz   }||j        }|	d}|r|j        }	n|j        }	nt          j        |	          }	d}dd	lm} |j                            d
|dz  z
  | j                  }t          j        |	          |k    }|t)          |           k    }t          j        ||          }|                    ||	||           | j        j        j        }|t5          t7          |	                    }t          j        t          j        |          d         |t=          ||	          t=          |dz  dz   |dz  dz            d|          }ddd} |j        |fi |  |j         di |  |j!        di | |S )Ncoor   dffzCriterion %s not understoodrg   @   zStudentized Residuals	Residuals)stats      ?)srH   rj   r      rn   )rm   rC   LeverageInfluence Plot)r  )r  )"r	   rL   lower
startswithcooks_distancerQ   absdffitsr   ptpr  hat_matrix_diagresid_studentized_externalresid_studentizedr   scipyr  tppfdf_residr,   
logical_orscatterrN   r   r   r   r   r   wherer   rX   rW   rV   )r*   	influenceexternalrH   	criterionr   
plot_alphar8   leveragero   r\   inflr]   psize	old_range	new_rangeylabelr  cutofflarge_residlarge_leveragelarge_pointslabelsfonts                           r+   _influence_plotr@  Y  sz    D!"%%GC##E** D#A&				%	%e	,	, Dt{1~&&6BCCC uIa$IUYY[[ I-i7$>E'}( 	+3EE*EE
5!!W[[E!GW%566F&--&(Kw 7 77N=n==LJJx%zJ::: ]*F~E

##		RXl33A6!(E22!E!Gb=.57R-@@)
! 
!B W--DBM&!!D!!!BM%%%%%BL**T***Jr-   z@results : Results
        Results for a fitted regression model.c           
      X    |                                  }t          | |f||||||d|}	|	S )N)r1  rH   r2  r   r3  r8   )get_influencer@  )
r*   r1  rH   r2  r   r3  r8   r\   r5  ress
             r+   r   r     sT       ""D
'4 B(%$-D%/BB B:@B BC Jr-   zqresults: object
    Results for a fitted regression model
influence: instance
    instance of Influence for modelc           
         ddl m}m} t          j        |          \  }}|}|j        }	 ||j                  }
 |j        |
dz  |	dfi | |                    d           |	                    d           |
                    d           |	t          |           k    }|                    d|dz  z
            }t          j        |
          |k    }| j        j        j        }|!t%          t'          | j                            }t          j        t          j        ||                    d         }t          j        ||t1          |
dz  |	          d	gt'          | j                  z  d
|dd          }|                    dd           |S )Nr   )normzscorerg   rh   zNormalized residuals**2r  z)Leverage vs. Normalized residuals squaredr  r   rk   r   r   )r8   r   r   g333333?)scipy.statsrE  rF  r	   rL   r&  ro   r6   rW   rX   rV   r,   r+  rQ   r#  rN   r   r   r   r   r)   r/  r-  r   r   margins)r*   r0  rH   r8   r\   rE  rF  r]   r5  r4  ro   r<  r:  r;  r>  rs   s                   r+   _plot_leverage_resid2rI    s    )(((((((!"%%GCD#HF4:EBGE1Hh..v...MM+,,,MM*LL<===w 7 77NXXbqj!!F&--&(K]*F~GL))**HR]>;??@@CE		UFD8,D,D$Xc',&7&77 "xH
> 
> 
>B JJtTJr-   z:results : object
    Results for a fitted regression modelc                 L    |                                  }t          | |f||d|S )N)rH   r8   )rB  rI  )r*   rH   r8   r\   r5  s        r+   r   r     s4    
   ""D $MeMMfMMMr-   c                    | j         }t          j        |          \  }}t          | ||||          \  }}	|                    |	|dd           |                    dd           t          |t                    r|}
n|j        |         }
|	                    |
d	           |
                    |j        d
z   d	           |S )N)
resid_typeuse_glm_weights
fit_kwargsrh   333333?rH   zAdded variable plotrk   rl      r   z
 residuals)rN   r	   rL   r    r6   rV   r   r   r   rW   rX   rS   )r*   
focus_exogrL  rM  rN  r8   rN   r]   endog_residfocus_exog_residxnames              r+   r#   r#     s     ME!"%%GC 'w
2<7F2<> > > "K! GGk3cG:::LL&L999*c"" - ,MM%bM!!!MM%#l2M<<<Jr-   c                    | j         }t          j        ||          \  }}t          | |          }| j         j        d d |f         }t          j        |          \  }}|                    ||dd           |                    dd           t          |t                    r|}n|j
        |         }|                    |d           |                    d	d           |S )
Nrh   rO  rP  zPartial residuals plotrk   rl   rQ  rR  Component plus residual)rN   r	   rM   r!   rP   rL   r6   rV   r   r   r   rW   rX   )	r*   rS  r8   rN   	focus_colprfocus_exog_valsr]   rV  s	            r+   r$   r$     s     ME!3JFFJ			,	,Bm(I6O!"%%GCGGORCG000LL)GL<<<*c"" - ,MM%bM!!!MM+"M555Jr-   zHresults : Results
        Results instance of a fitted regression model.Q?c                 v   | j         }t          j        ||          \  }}t          | |||          }|j        d d |f         }t          j        |          \  }	}|                    ||dd           |                    dd           |                    |d	           |	                    d
d	           |	S )N)r0   
cond_meansrh   rO  rP  zCERES residuals plotrk   rl   rQ  rR  rX  )
rN   r	   rM   r"   rP   rL   r6   rV   rW   rX   )
r*   rS  r0   r^  r8   rN   rY  presidr[  r]   s
             r+   r%   r%     s     ME!3JFFJ	':D%/1 1 1F jI.O!"%%GCGGOVSG444LL''L:::MM*2M&&&MM+"M555Jr-   c                 H   | j         }t          |t          t          t          f          st          d|j        j        z            t          j	        ||          \  }}t          t          | j                            }t          |          }|                    |           t          |          }||j        dd|f         }||                    d          z  }t"          j                            |d          \  }	}
}t#          j        |
dk              }|	dd|f         }|j        dd|f         }t#          j        t          |          |j        d         f          }t          |j        d                   D ]*}|dd|f         }t/          |||d          }||dd|f<   +t#          j        |j        dd|f         |fd          }|j        }|                                } ||j        |fi |}|                                }|j        |j        z
  }t          |t          t          f          r'||j        j                            |j                  z  }|j        d         |k    r1|t#          j         |dd|df         |j        |d                   z  }|S )	a  
    Calculate the CERES residuals (Conditional Expectation Partial
    Residuals) for a fitted model.

    Parameters
    ----------
    results : model results instance
        The fitted model for which the CERES residuals are calculated.
    focus_exog : int
        The column of results.model.exog used as the 'focus variable'.
    frac : float, optional
        Lowess smoothing parameter for estimating the conditional
        means.  Not used if `cond_means` is provided.
    cond_means : array_like, optional
        If provided, the columns of this array are the conditional
        means E[exog | focus exog], where exog ranges over some
        or all of the columns of exog other than focus exog.  If
        this is an empty nx0 array, the conditional means are
        treated as being zero.  If None, the conditional means are
        estimated.

    Returns
    -------
    An array containing the CERES residuals.

    Notes
    -----
    If `cond_means` is not provided, it is obtained by smoothing each
    column of exog (except the focus column) against the focus column.

    Currently only supports GLM, GEE, and OLS models.
    z$ceres residuals not available for %sNr   gư>r   F)r0   return_sorted)axis)!rN   r   r   r   r   r   r   r   r	   rM   ranger   r   r   r   rP   meanrQ   linalgsvdflatnonzeror   r}   r
   concatenate_get_init_kwdsrO   r   rT   familylinkderivdot)r*   rS  r0   r^  rN   rY  ix_nfnnfpexogur  vtiifcoljr;   cfnew_exogklassinit_kwargs	new_model
new_resultr_  s                          r+   r"   r"   *  s   D MEec3_-- 3?12 3 3 	3 "3JFFJ	 #gn%%&&EKKE	IIi
e**C 
 
111e8$A9==**1b^AH%%!!!R%z!!!Y,'Xs4yy%+a.9::
u{1~&& 	" 	"A qqq!tBDt5AAAB!Jqqq!t~uz!!!U(3Z@qIIIH OE&&((Kek8;;{;;IJ [:22F%#s$$ C%,#))**ABBB~a3"&!!!STT'*J,=cdd,CDDDMr-   c                    | j         }|j        |                                 z
  }t          |t          t
          f          r(||j        j                            | j	                  z  }nBt          |t          t          t          f          rnt          dt          |          z            t          |          t          u r|j                            |          }n|}| j        |         |j        dd|f         z  }||z   S )a:  
    Returns partial residuals for a fitted model with respect to a
    'focus predictor'.

    Parameters
    ----------
    results : results instance
        A fitted regression model.
    focus col : int
        The column index of model.exog with respect to which the
        partial residuals are calculated.

    Returns
    -------
    An array of partial residuals.

    References
    ----------
    RD Cook and R Croos-Dabrera (1998).  Partial residual plots in
    generalized linear models.  Journal of the American Statistical
    Association, 93:442.
    z+Partial residuals for '%s' not implemented.N)rN   rO   predictr   r   r   rj  rk  rl  rT   r   r   r   r   typer   r   rs   r   rP   )r*   rS  rN   ro   rY  	focus_vals         r+   r!   r!     s    8 MEK'//+++E%#s$$ ("(()=>>>	ECc?	+	+ (F;;' ( ( 	( J3$**:66			y)EJqqq)|,DDIur-   c                    | j         }t          |t          t          t          f          st          d|j        j        z            |j        }|j	        }t          j        ||          \  }}|dd|f         }	|!t          |t          t          f          rd}nd}t          |j        d                   }
t          |
          }
|
                    |           |dd|
f         }| j        |
         }|j        }|                                } |||fi |}d|i}||                    |            |j        di |}t)          |dd          st          d	          	 t)          ||          }n # t*          $ r t          d
|z            w xY wddlmc m} t          |t          t          f          re|rc|j                            | j                  }t9          |d          r
||j        z  }|                    |	||                                          }n(|                    |	|                                          }|j        }||fS )aO  
    Residualize the endog variable and a 'focus' exog variable in a
    regression model with respect to the other exog variables.

    Parameters
    ----------
    results : regression results instance
        A fitted model including the focus exog and all other
        predictors of interest.
    focus_exog : {int, str}
        The column of results.model.exog or a variable name that is
        to be residualized against the other predictors.
    resid_type : str
        The type of residuals to use for the dependent variable.  If
        None, uses `resid_deviance` for GLM/GEE and `resid` otherwise.
    use_glm_weights : bool
        Only used if the model is a GLM or GEE.  If True, the
        residuals for the focus predictor are computed using WLS, with
        the weights obtained from the IRLS calculations for fitting
        the GLM.  If False, unweighted regression is used.
    fit_kwargs : dict, optional
        Keyword arguments to be passed to fit when refitting the
        model.

    Returns
    -------
    endog_resid : array_like
        The residuals for the original exog
    focus_exog_resid : array_like
        The residuals for the focus predictor

    Notes
    -----
    The 'focus variable' residuals are always obtained using linear
    regression.

    Currently only GLM, GEE, and OLS models are supported.
    z8model type %s not supported for added variable residualsNresid_deviancero   r   start_params	convergedTz>fit did not converge when calculating added variable residualsz '%s' residual type not availabler   data_weightsr   ) rN   r   r   r   r   r   r   r   rP   rO   r	   rM   rc  r}   r   r   r   ri  r   r   getattrAttributeError#statsmodels.regression.linear_model
regressionlinear_modelrj  weightsrT   r   r  r   ro   )r*   rS  rL  rM  rN  rN   rP   rO   rY  r[  rs  reduced_exogr  rx  r\   rz  r   r{  rT  lmr  
lm_resultsrU  s                          r+   r    r      s   R MEec3_-- 3S12 3 3 	3 :DKE!3JFFJ	111i<(O ec3Z(( 	!)JJ J	tz!}		B	bBFF92;L>"%LOE!!##Fe\44V44IL)DJ&&&&J:{D11 [YZZZJj*55 J J J;jHIIIJ 544444444%#s$$ A A,&&w';<<5.)) 	3 22GVVO\7CCGGII

VVO\::>>@@
!'(((s    E1 1F)r   r.   )NNTr   )NNN)NNNNNNr   )Tr  r  r  r  NNN)Tr  r  r  r  N)r  N)NTNN)r\  NN)r\  N)NTN)8__doc__statsmodels.compat.pandasr   statsmodels.compat.pythonr   r   numpyrQ   r   r   patsyr   3statsmodels.genmod.generalized_estimating_equationsr   +statsmodels.genmod.generalized_linear_modelr   statsmodels.graphicsr	   *statsmodels.nonparametric.smoothers_lowessr
   r  r   r   r   &statsmodels.sandbox.regression.predstdr   r   r   _regressionplots_docr   r   r   r   r   __all__r,   r   r   r   r   r   r   r   r   r   formatr@  r   rI  r   r#   r$   r%   r"   r!   r    r   r-   r+   <module>r     s    / . . . . . 2 2 2 2 2 2 2 2               C C C C C C ; ; ; ; ; ; & & & & & & = = = = = = = = = = = = = = = = E E E E E E 8 8 8 8 8 8             = = =4 4 4
   8] ] ] ]@b b b bJ! ! !: 7;"$Bd d d dNc c c cLP P P Pf\ \ \ \~ >B'+h h h hV 

$

$ I I G(H I I J J
 >ACG)-; ; ;J J
;| 

$

$ K K I(J K K L L AH/3  L L 

*
#
* >,? @ @ A A
  A A
: 

*
#
* D,E F F G GN N NG GN 

" D&E E F F 9=BF  F F6 

% D)E E F F  F F2 

# !'" " # # EI   	# #.W W W Wr. . .` ;?;?]) ]) ]) ]) ]) ])r-   