Add regression line equation and R^2 on graph

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

    Here's the most simplest code for everyone

    Note: Showing Pearson's Rho and not R^2.

    library(ggplot2)
    library(ggpubr)
    
    df <- data.frame(x = c(1:100)
    df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
    p <- ggplot(data = df, aes(x = x, y = y)) +
            geom_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) +
            geom_point()+
            stat_cor(label.y = 35)+ #this means at 35th unit in the y axis, the r squared and p value will be shown
            stat_regline_equation(label.y = 30) #this means at 30th unit regresion line equation will be shown
    
    p
    

提交回复
热议问题