如何用ggplot绘制回归线?
How to plot regression line with ggplot?
我正在尝试将两条回归线放入同一个图中。我可以使用下面的代码来完成,但线条颜色相同:
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") 生成回归线。不过好像不是我建的模型
有人能解释一下吗?
非常感谢。
只需添加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)))
结果:
您可以直接在 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)
我正在尝试将两条回归线放入同一个图中。我可以使用下面的代码来完成,但线条颜色相同:
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") 生成回归线。不过好像不是我建的模型
有人能解释一下吗?
非常感谢。
只需添加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)))
结果:
您可以直接在 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)