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

时间:2014-11-24 03:05:17

标签: r ggplot2 regression equation

前一段时间我从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));                 
}

这设法绘制&#34; a + bx&#34;或&#34; a-bx&#34;到图,但没有实际系数替换a和b。有谁知道如何解决这个问题?非常感谢!

Jayden的回答:

 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));                 
 }

1 个答案:

答案 0 :(得分:2)

您似乎错过了l中的substitute()。也就是说,使用substitute(yourFormula, l)。这是一个没有r^2的MWE,与您正在查看的那个(我认为是Adding Regression Line Equation and R2 on graph)相似。

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

Regression equation