Add regression line equation and R^2 on graph

后端 未结 9 2229
梦如初夏
梦如初夏 2020-11-21 07:24

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         


        
9条回答
  •  走了就别回头了
    2020-11-21 07:49

    I've modified Ramnath's post to a) make more generic so it accepts a linear model as a parameter rather than the data frame and b) displays negatives more appropriately.

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

    Usage would change to:

    p1 = p + geom_text(aes(x = 25, y = 300, label = lm_eqn(lm(y ~ x, df))), parse = TRUE)
    

提交回复
热议问题