首页 文章

如何用ggplot绘制回归线?

提问于
浏览
4

我试图将两条回归线放入同一个图中 . 我可以使用下面的代码,但使用相同颜色的行:

model1 <- glm(species~logarea, family=poisson, data=fish)
model2 <- glm.nb(species~logarea, data=fish)

plot(species~logarea,data=fish)
lines(fitted(model1)[order(logarea)]~sort(logarea),data=fish)
lines(fitted(model2)[order(logarea)]~sort(logarea),data=fish)

我想用ggplot复制上面的图,这样我就可以用不同的颜色显示不同的线 . 但我无法弄清楚如何做到这一点 .

我只完成了绘制散点图的第一步,但不知道如何在其上添加线条 .

ggplot(fish,aes(fish$logarea,fish$SPECIES))+geom_point()

我做了一些搜索,我明白我可以使用geom_smooth(method =“glm”)来生成回归线 . 但它似乎不是基于我 Build 的模型 .

谁能对此有所了解?

非常感谢 .

2 回答

  • 2

    只需添加 geom_line(aes(y=fitted_datas)) ,例如:

    data("mtcars")
    library(ggplot2)
    model <- glm(mpg~hp, family=poisson, data=mtcars)
    ggplot(mtcars,aes(hp,mpg))+geom_point()+geom_line(aes(y=fitted(model)))
    

    结果:

    enter image description here

  • 4

    您可以直接在 geom_smooth 中拟合模型 . 在这种情况下,您需要使用 method.args 参数为拟合方法提供额外的参数,以定义 glm 的族 .

    这是一个示例,为每个模型类型添加不同的颜色 . 我使用 se = FALSE 删除置信区间 .

    ggplot(fish,aes(logarea, SPECIES)) + 
        geom_point() +
        geom_smooth(method = "glm", method.args = list(family = poisson), aes(color = "poisson"), se = FALSE) +
        geom_smooth(method = MASS::glm.nb, aes(color = "NB"), se = FALSE)
    

相关问题