Add regression line equation and R^2 on graph

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

    Using ggpubr:

    library(ggpubr)
    
    # reproducible data
    set.seed(1)
    df <- data.frame(x = c(1:100))
    df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
    
    # By default showing Pearson R
    ggscatter(df, x = "x", y = "y", add = "reg.line") +
      stat_cor(label.y = 300) +
      stat_regline_equation(label.y = 280)
    

    # Use R2 instead of R
    ggscatter(df, x = "x", y = "y", add = "reg.line") +
      stat_cor(label.y = 300, 
               aes(label = paste(..rr.label.., ..p.label.., sep = "~`,`~"))) +
      stat_regline_equation(label.y = 280)
    
    ## compare R2 with accepted answer
    # m <- lm(y ~ x, df)
    # round(summary(m)$r.squared, 2)
    # [1] 0.85
    

提交回复
热议问题