繁体   English   中英

R中的ggplot:在绘图中添加回归方程

[英]ggplot in R: add regression equation in a plot

不久前,我从杰登(Jayden)看到了关于将回归方程添加到绘图中的答案,我发现它非常有用。 但是我不想显示R ^ 2,因此我将代码更改为:

lm_eqn = function(m) {
l <- list(a = format(coef(m)[1], digits = 2),
  b = format(abs(coef(m)[2]), digits = 2));
if (coef(m)[2] >= 0)  {
eq <- substitute(italic(y) == a + b %.% italic(x))
} else {
eq <- substitute(italic(y) == a - b %.% italic(x))    
}
as.character(as.expression(eq));                 
}

这设法将“ a + bx”或“ a-bx”绘制到该图上,但没有实际系数替换a和b。 有人知道如何解决该问题吗? 非常感谢!

杰登的答案:

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

看来您缺少了l substitute()l 也就是说,使用substitute(yourFormula, l) 这是一个不带r^2的MWE,它与您正在查看的MWE相似(我认为这是在图上添加回归线方程和R2 )。

library(ggplot2)

# Function to generate correlated data.
GenCorrData = function(mu, Sig, n = 1000) {
  U            <- chol(Sig)
  Z            <- matrix(rnorm(n*length(mu)), nrow = length(mu))
  Y            <- crossprod(U,Z) + mu
  Y            <- as.data.frame(t(Y))
  names(Y)     <- c("x", "y")
  return(Y)
}

# Function to add text
LinEqn = function(m) {
  l <- list(a = format(coef(m)[1], digits = 2),
            b = format(abs(coef(m)[2]), digits = 2));
  if (coef(m)[2] >= 0) {
    eq <- substitute(italic(y) == a + b %.% italic(x),l)
  } else {
    eq <- substitute(italic(y) == a - b %.% italic(x),l)    
  }
  as.character(as.expression(eq));                 
}

# Example
set.seed(700)
n1             <- 1000
mu1            <- c(4, 5)
Sig1           <- matrix(c(1, .8, .8, 1), nrow = length(mu1))
df1            <- GenCorrData(mu1, Sig1, n1)
scatter1       <- ggplot(data = df1, aes(x, y)) +
                    geom_point(shape = 21, color = "blue", size = 3.5) +
                    scale_x_continuous(expand = c(0, 0), limits = c(0, 8)) +
                    scale_y_continuous(expand = c(0, 0), limits = c(0, 8))
scatter.line1  <- scatter1 + 
                    geom_smooth(method = "lm", formula = y ~ x, se = FALSE, 
                                color="black", size = 1) +
                    annotate("text", x = 2, y = 7, color = "black", size = 5,
                             label = LinEqn(lm(y ~ x, df1)), parse = TRUE)
scatter.line1

回归方程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM