Add regression line equation and R^2 on graph

后端 未结 9 2217
梦如初夏
梦如初夏 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:42

    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

    Output

提交回复
热议问题