在PLOTNINE中添加回归线方程和R-Square

4
在plotnine中很容易通过使用stat_smooth(method="gls")获取数据的线性最佳拟合。然而,我不知道如何得到最佳拟合线的系数或R2值。在R中的ggplot有一个stat_regline_equation()函数可以做到这一点,但是我在plotnine中找不到类似的工具。
目前,我正在使用statsmodels.formula.api.ols来获取这些值,但在plotnine内部肯定有更好的方法。
注:我对编程还一窍不通。

stat_regline_equation() 不是 ggplot 的函数,而是来自于 ggpubr 扩展包,因此我不认为它会成为 plotnine 的一部分。如果你有一个使用 statsmodels.formula.api.ols 的可行替代方案,你可以在这里发布它以指导其他用户,也许然后有人能够为你改进它。 - krassowski
1个回答

3
我最终使用了以下代码,不是PlotNine,但非常容易实现。
import plotnine as p9
from scipy import stats
from plotnine.data import mtcars as df

#calculate best fit line
slope, intercept, r_value, p_value, std_err = stats.linregress(df['wt'],df['mpg'])
df['fit']=df.wt*slope+intercept
#format text 
txt= 'y = {:4.2e} x + {:4.2E};   R^2= {:2.2f}'.format(slope, intercept, r_value*r_value)
#create plot. The 'factor' is a nice trick to force a discrete color scale
plot=(p9.ggplot(data=df, mapping= p9.aes('wt','mpg', color = 'factor(gear)'))
    + p9.geom_point(p9.aes())
    + p9.xlab('Wt')+ p9.ylab(r'MPG')
    + p9.geom_line(p9.aes(x='wt', y='fit'), color='black')
    + p9.annotate('text', x= 3, y = 35, label = txt))
#for some reason, I have to print my plot 
print(plot)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接