在图上添加回归线方程和 R^2 [英] Add regression line equation and R^2 on graph

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

问题描述

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

库(ggplot2)df <- data.frame(x = c(1:100))df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)p <- ggplot(数据 = df, aes(x = x, y = y)) +geom_smooth(method = "lm", se=FALSE, color="black", 公式 = y ~ x) +几何点()p

我们将不胜感激.

解决方案

这里有一个解决方案

# 将方程和 R 平方作为字符串# 来源:https://groups.google.com/forum/#!topic/ggplot2/1TgH-kG5XMAlm_eqn <- 函数(df){m <- lm(y ~ x, df);eq <- 替换(斜体(y)== a + b %.% 斜体(x)*",~~斜体(r)^2~"="~r2,列表(a = 格式(unname(coef(m)[1]),数字 = 2),b = 格式(无名(coef(m)[2]),数字 = 2),r2 = 格式(汇总(m)$r.squared,数字 = 3)))as.character(as.expression(eq));}p1 <- p + geom_text(x = 25, y = 300, label = lm_eqn(df), parse = TRUE)

编辑.我找出了我选择此代码的来源.这是 链接到 ggplot2 google 群组中的原始帖子p>

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: https://groups.google.com/forum/#!topic/ggplot2/1TgH-kG5XMA

lm_eqn <- function(df){
    m <- lm(y ~ x, df);
    eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2, 
         list(a = format(unname(coef(m)[1]), digits = 2),
              b = format(unname(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)

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

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

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