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 want to know the fitting coefficients or the R2 of the fit.
I could re-run the same fit using the underlying statsmodels interface, but that would seem to be unnecessary duplicate effort, and anyway I'd want to be able to compare the resulting coefficients to be sure the numerical results are the same as what I'm seeing in the plot.
There's no way to do this.
In my opinion, asking a visualization library to give you statistical modeling results is backwards.
statsmodels
, a modeling library, lets you fit a model and then draw a plot that corresponds exactly to the model you fit. If you want that exact correspondence, this order of operations makes more sense to me.You might say "but the plots in
statsmodels
don't have as many aesthetic options asseaborn
". But I think that makes sense —statsmodels
is a modeling library that sometimes uses visualization in the service of modeling.seaborn
is a visualization library that sometimes uses modeling in the service of visualization. It is good to specialize, and bad to try to do everything.Fortunately, both
seaborn
andstatsmodels
use tidy data. That means that you really need very little effort duplication to get both plots and models through the appropriate tools.Looking thru the currently available doc, the closest I've been able to determine if this functionality can now be met is if one uses the scipy.stats.pearsonr module.
In attempting to make it work directly within a Pandas dataframe, there's an error kicked out from violating the basic scipy input requirements:
I managed to locate another Pandas Seaborn user who evidently solved it: https://github.com/scipy/scipy/blob/v0.14.0/scipy/stats/stats.py#L2392
But, unfortunately I haven't managed to get that to work as it appears the author created his own custom 'corr_func' or either there's an undocumented Seaborn arguement passing method that's available using a more manual method:
Hope this helps to advance this original request along toward an interim solution as there's much needed utility to add the regression fitness stats to the Seaborn package as a replacement to what one can easily get from MS-Excel or a stock Matplotlib lineplot.
Seaborn's creator has unfortunately stated that he won't add such a feature, so here's a workaround.
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 inseaborn
that can break at any point.