How to get the numerical fitting results when plotting a regression in seaborn?

前端 未结 3 1284
孤街浪徒
孤街浪徒 2020-12-02 17:09

If I use the seaborn library in Python to plot the result of a linear regression, is there a way to find out the numerical results of the regression? For example, I might wa

3条回答
  •  生来不讨喜
    2020-12-02 17:25

    Seaborn's creator has unfortunately stated that he won't add such a feature, so here's a workaround.

    def regplot(*args, **kwargs):
        # this is the class that `sns.regplot` uses
        plotter = sns.regression._RegressionPlotter(*args, **kwargs)
    
        # this is essentially the code from `sns.regplot`
        ax = kwargs.get("ax", None)
        if ax is None:
            ax = plt.gca()
    
        scatter_kws = {} if scatter_kws is None else copy.copy(scatter_kws)
        scatter_kws["marker"] = marker
        line_kws = {} if line_kws is None else copy.copy(line_kws)
    
        plotter.plot(ax, scatter_kws, line_kws)
    
        # unfortunately the regression results aren't stored, so we rerun
        grid, yhat, err_bands = plotter.fit_regression(plt.gca())
    
        # also unfortunately, this doesn't return the parameters, so we infer them
        slope = (yhat[-1] - yhat[0]) / (grid[-1] - grid[0])
        intercept = yhat[0] - slope * grid[0]
        return slope, intercept
    

    Note that this only works for linear regression because it simply infers the slope and intercept from the regression results. The nice thing is that it uses seaborn's own regression class and so the results are guaranteed to be consistent with what's shown. The downside is of course that we're using a private implementation detail in seaborn that can break at any point.

提交回复
热议问题