How to overlay a line for an lm object on a ggplot2 scatterplot

前端 未结 2 1484
情歌与酒
情歌与酒 2020-12-29 11:58

I have some data,

calvarbyruno.1<-structure(list(Nominal = c(1, 3, 6, 10, 30, 50, 150, 250), Run = structure(c(1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label =         


        
2条回答
  •  甜味超标
    2020-12-29 12:37

    The easiest option is to use geom_smooth() and let ggplot2 fit the model for you.

    ggplot(calvarbyruno.1, aes(y = PAR, x = Nominal, weight=Nominal^calweight)) + 
        geom_smooth(method = "lm") + 
        geom_smooth(method = "lm", formula = y ~ poly(x, 2), colour = "red") + 
        geom_point() + 
        coord_flip()
    

    Illustration using geom_smooth

    Or you can create a new dataset with the predicted values.

    newdata <- data.frame(Nominal = pretty(calvarbyruno.1$Nominal, 100))
    newdata$Linear <- predict(callin.1, newdata = newdata)
    newdata$Quadratic <- predict(calquad.1, newdata = newdata)
    require(reshape2)
    newdata <- melt(newdata, id.vars = "Nominal", variable.name = "Model")
    ggplot(calvarbyruno.1, aes(x = PAR, y = Nominal, weight=Nominal^calweight)) + 
        geom_line(data = newdata, aes(x = value, colour = Model)) + 
        geom_point()
    

提交回复
热议问题