首页 > 解决方案 > 使用 ggplot 将 geom_abline 添加到来自 glm 的残差与拟合数据

问题描述

我的数据如下所示:

y = c(12, 14, 33, 50, 67, 74, 123, 141, 165, 204, 253, 246, 240)
t = 1:13
aids.pois <- glm(y~t, data=data, family="poisson")
cc <- data.frame(aids.pois$residuals, aids.pois$fitted.values)

我想将 geom_abline 添加到下面的图中,但无法显示 abline:

ggplot(cc, aes(x = aids.pois.fitted.values, y = aids.pois.residuals)) + 
  geom_point() +
  geom_abline()

我期待这样的事情(但使用ggplot)

plot(aids.pois, which = 1, main = "base R: Residual Vs fitted plot")

在此处输入图像描述

标签: rggplot2regression

解决方案


如果你想要类似于基地plot()正在做的事情,你可以这样做

cc <- data.frame(resid=resid(aids.pois), fitted=fitted(aids.pois))

ggplot(cc, aes(x = fitted, y = resid)) + 
  geom_smooth(method="loess", color="red", se=FALSE) + 
  geom_hline(yintercept = 0, linetype=2, color="darkgrey") +
  geom_point()

在此处输入图像描述

来自的红线plot()只是绘制点的黄土平滑。您可以添加参考线geom_hlinegeom_abline这里根本不需要。


推荐阅读