【问题标题】:Add Regression Line Equation and R-Square to a PLOTNINE将回归线方程和 R 方添加到 PLOTNINE
【发布时间】:2020-04-09 22:30:16
【问题描述】:

使用stat_smooth(method="gls") 在 plotnine 中很容易获得数据的线性最佳拟合。但是,我不知道如何将系数导出到最佳拟合线或 R2 值。 R中的ggplot有一个stat_regline_equation()函数可以做到这一点,但我在plotnine中找不到类似的工具。

目前,我正在使用statsmodels.formula.api.ols 来获取这些值,但在 plotnine 中必须有更好的方法。

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

【问题讨论】:

  • stat_regline_equation() 不是 ggplot 函数,而是来自 ggpubr 扩展,所以我不希望它成为 plotnine 的一部分。如果您有使用 statsmodels.formula.api.ols 的工作替代品,您可能希望在此处发布它以指导其他用户,也许有人会为您改进它。

标签: python-3.x linear-regression plotnine


【解决方案1】:

我最终使用了以下代码;不是 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)

【讨论】:

    猜你喜欢
    • 2011-11-24
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    • 2021-01-21
    • 2018-08-31
    • 1970-01-01
    相关资源
    最近更新 更多