如何在 r 中使用 ggplot 为空模型在 lm 线上绘制预测值

how to plot predicted values on lm line for a null model using ggplot in r

正在尝试使用产生的 ggplot 重现以下基本代码 结果不正确

基本代码

model1 <- lm(wgt ~ 1, data = bdims)
model1_null <- augment(model1)
plot(bdims$hgt, bdims$wgt)
abline(model1, lwd = 2, col = "blue")
pre_null <- predict(model1)
segments(bdims$hgt, bdims$wgt, bdims$hgt, pre_null, col = "red")

ggplot代码

bdims %>% 
  ggplot(aes(hgt, wgt)) +
  geom_point() +
  geom_smooth(method = "lm", formula = bdims$hgt ~ 1) +
  segments(bdims$hgt, bdims$wgt, bdims$hgt, pre_null, col = "red")

这是一个使用 built-in mtcars 数据的示例:

ggplot(mtcars, aes(wt, mpg)) +
    geom_point() +
    geom_smooth(method = "lm", formula = y ~ 1) + 
    geom_segment(aes(xend = wt, yend = mean(mpg)), col = "firebrick2")

formula 引用的是美学维度,而不是变量名称。而且您需要使用 geom_segment 而不是基本图形 segments。在更复杂的情况下,您会 pre-compute 模型的分段预测值,但对于空模型,只需使用 mean 内联就足够了。