首页 > 解决方案 > 尝试使用 ggplot 绘制具有一个分类变量的简单线性回归,并在绘图上获得回归线

问题描述

我正在尝试使用 ggplot 绘制 3 个线性模型:

model = lm(dep_delay ~ season, data = data)
model2 = lm(dep_delay ~ carrier, data = data)
model3 = lm(dep_delay ~ origin, data = data)

我的数据结构如下:

season origin carrier dep_delay
1 winter    EWR      UA         2
2 winter    LGA      UA         4
3 winter    JFK      AA         2
4 winter    JFK      B6        -1
5 winter    LGA      DL        -6
6 winter    EWR      UA        -4

我正在尝试使用这行代码:

ggplot(data, aes(x = season, y = dep_delay)) + geom_boxplot() + labs(x="season") + geom_smooth(method = "lm",se=FALSE, col = "blue")

它给了我想要的情节,但没有在情节上画一条线,我如何让这条线出现?

标签: rggplot2lm

解决方案


geom_smooth() 无法适应给定 x 不是数字的行。您可以将季节重新编码为数字并在指定 aes 时使用 as.numeric(season)。


推荐阅读