Adding a regression line on a ggplot

前端 未结 5 1409
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 18:54

I\'m trying hard to add a regression line on a ggplot. I first tried with abline but I didn\'t manage to make it work. Then I tried this...

data = data.frame         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 19:11

    I found this function on a blog

     ggplotRegression <- function (fit) {
    
        `require(ggplot2)
    
        ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) + 
          geom_point() +
          stat_smooth(method = "lm", col = "red") +
          labs(title = paste("Adj R2 = ",signif(summary(fit)$adj.r.squared, 5),
                             "Intercept =",signif(fit$coef[[1]],5 ),
                             " Slope =",signif(fit$coef[[2]], 5),
                             " P =",signif(summary(fit)$coef[2,4], 5)))
        }`
    

    once you loaded the function you could simply

    ggplotRegression(fit)
    

    you can also go for ggplotregression( y ~ x + z + Q, data)

    Hope this helps.

提交回复
热议问题