Add regression line equation and R^2 on graph

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

    I changed a few lines of the source of stat_smooth and related functions to make a new function that adds the fit equation and R squared value. This will work on facet plots too!

    library(devtools)
    source_gist("524eade46135f6348140")
    df = data.frame(x = c(1:100))
    df$y = 2 + 5 * df$x + rnorm(100, sd = 40)
    df$class = rep(1:2,50)
    ggplot(data = df, aes(x = x, y = y, label=y)) +
      stat_smooth_func(geom="text",method="lm",hjust=0,parse=TRUE) +
      geom_smooth(method="lm",se=FALSE) +
      geom_point() + facet_wrap(~class)
    

    enter image description here

    I used the code in @Ramnath's answer to format the equation. The stat_smooth_func function isn't very robust, but it shouldn't be hard to play around with it.

    https://gist.github.com/kdauria/524eade46135f6348140. Try updating ggplot2 if you get an error.

提交回复
热议问题