将回归线方程式和R平方添加到PLOTNINE中

问题描述 投票:1回答:1

使用stat_smooth(method="gls")可以很容易地获得platenine中数据的线性最佳拟合。但是,我无法弄清楚如何得出最适合线或R2值的系数。 R中的Ggplot具有执行此操作的stat_regline_equation()函数,但是我无法在plotnine中找到类似的工具。

当前,我正在使用statsmodels.formula.api.ols来获取这些值,但是必须在胶粘剂内部找到一种更好的方法。

PS:我是所有事物编码的新手。

python-3.x linear-regression plotnine
1个回答
0
投票

我最终使用了以下代码;不是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)
© www.soinside.com 2019 - 2024. All rights reserved.