在图上添加回归直线方程和R2 [英] Adding Regression Line Equation and R2 on graph

查看:165
本文介绍了在图上添加回归直线方程和R2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在 ggplot 上添加回归直线方程和R ^ 2。我的代码是

I wonder how to add regression line equation and R^2 on the ggplot. My code is

library(ggplot2)
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
p <- ggplot(data = df, aes(x = x, y = y)) +
            geom_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) +
            geom_point()
p

任何帮助都将得到高度评价。

Any help will be highly appreciated.

推荐答案

以下是一个解决方案

Here is one solution

# GET EQUATION AND R-SQUARED AS STRING
# SOURCE: http://goo.gl/K4yh

lm_eqn <- function(df){
    m <- lm(y ~ x, df);
    eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2, 
         list(a = format(coef(m)[1], digits = 2), 
              b = format(coef(m)[2], digits = 2), 
             r2 = format(summary(m)$r.squared, digits = 3)))
    as.character(as.expression(eq));                 
}

p1 <- p + geom_text(x = 25, y = 300, label = lm_eqn(df), parse = TRUE)

编辑。我想出了我选择这个代码的来源。以下是链接到ggplot2 google群组中的原始帖子。

EDIT. I figured out the source from where I picked this code. Here is the link to the original post in the ggplot2 google groups

这篇关于在图上添加回归直线方程和R2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆