将SEPARATE LINES图上的回归线方程式和R2相加 [英] Adding Regression Line Equation and R2 on SEPARATE LINES graph

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

问题描述

几年前,一位发帖人在下面的链接中问如何在ggplot图上添加回归线方程和R2.

A few years ago, a poster asked how to add regression line equation and R2 on ggplot graphs at the link below.

在图形上添加回归线方程和R2

最佳解决方案是:

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)

我正在使用此代码,效果很好.但是,我想知道是否有可能使此代码在单独的行上具有R2值和回归线方程,而不是用逗号分隔.

I am using this code and it works great. However, I was wondering if it is at all possible to make this code have the R2 value and regression line equation on separate lines, instead of being separated by a comma.

而不是像这样

类似这样的东西

提前感谢您的帮助!

推荐答案

除了插入方程式之外,我还修复了截距值的符号.通过将RNG设置为set.seed(2L)将给出正截距.下面的示例产生负拦截.

In addition to inserting the equation, I have fixed the sign of the intercept value. By setting the RNG to set.seed(2L) will give positive intercept. The below example produces negative intercept.

我还修复了geom_text

set.seed(3L)
library(ggplot2)
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)

lm_eqn <- function(df){
  # browser()
  m <- lm(y ~ x, df)
  a <- coef(m)[1]
  a <- ifelse(sign(a) >= 0, 
              paste0(" + ", format(a, digits = 4)), 
              paste0(" - ", format(-a, digits = 4))  )
  eq1 <- substitute( paste( italic(y) == b, italic(x), a ), 
                     list(a = a, 
                          b = format(coef(m)[2], digits = 4)))
  eq2 <- substitute( paste( italic(R)^2 == r2 ), 
                     list(r2 = format(summary(m)$r.squared, digits = 3)))
  c( as.character(as.expression(eq1)), as.character(as.expression(eq2)))
}

labels <- lm_eqn(df)


p <- ggplot(data = df, aes(x = x, y = y)) +
  geom_smooth(method = "lm", se=FALSE, color="red", formula = y ~ x) +
  geom_point() +
  geom_text(x = 75, y = 90, label = labels[1], parse = TRUE,  check_overlap = TRUE ) +
  geom_text(x = 75, y = 70, label = labels[2], parse = TRUE, check_overlap = TRUE )

print(p)

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

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