如何绘制具有 2 列矩阵响应的 GLM 的预测概率?

How to plot predicted probabilities from a GLM with 2-column matrix response?

我想从 glm 模型(写在下面)中绘制回归线。理想情况下,我想将它绘制在观察到的数据上,但我无法调整我在其他地方找到的代码(例如 predict.glm, Plot predicted probabilities and confidence intervals in r)。

这是数据的一个子集:

     Pos   Tot   Age
    <int> <int> <int>
1     1    11     1
2     0     1     1
3     3     3     1
4     1     2     1
5     5     7     1
47   13    16     4
48    9     9     4
49    9    10     4
50   14    14     4    
158   1     3     2
159   3     5     2
160   0     7     2
161   9    12     2
162   0     2     2
209   0     1     3
210   1     2     3
211   1     1     3
212   2     2     3

每一行代表一个独特的位置。我删除了位置列以取消识别。

这是我的模型:

 model1 <- glm(cbind(Tot - Pos, Pos) ~ -1+Age,
            family = binomial(link = "log"), data = data.frame)

我的目标是绘制不同 glm 模型的预测概率以进行视觉比较...但现在我什至不知道如何绘制我最简单的模型。

编辑 因为响应是一个两列矩阵,所以我认为没有办法在 ggplot 中作图。有人可以确认吗?

我曾尝试在 ggplot 中绘图,但由于模型响应是一个两列矩阵,绘图和模型的美学不匹配:

ggplot(data.frame, aes(x = Age, y = Pos/Tot)) +
geom_jitter(width = 0.05, height = 0.05) +
geom_smooth(method = glm, formula = cbind(Tot-Pos, Pos) ~ -1+Age, se = FALSE)

其中 returns 观察值的散点图但也给我错误消息:

Warning message:
Computation failed in `stat_smooth()`:
object 'Tot' not found 

所以我现在正在尝试弄清楚如何使用 predict 函数进行绘图,这是我以前从未做过的。

这是我目前所拥有的,改编自 here:

 newdata<-data.frame(Age = 1:4)
 plot(1:4, predict(model1, newdata, type="link"))

如何添加 95% 置信区间并将数据转换回 y 轴上的概率范围 0-1?

非常感谢

生成预测的方法如下:

pd = data.frame(Age = 1:4)

# use type = "response" for probability-scale predictions    
preds = predict(model1, newdata = pd, type = "response", se.fit = TRUE)
pd$fit = preds$fit
pd$se = preds$se.fit

然后剧情:

ggplot(dd, aes(x = Age, y = Pos / Tot)) +
  geom_point(position = position_jitter(width = 0.05, height = 0.05)) +
  geom_ribbon(data = pd, aes(y = fit, ymin = fit - 1.96 * se, ymax = fit + 1.96 * se),
              fill = "blue", alpha = 0.3) +
  geom_line(data = pd, aes(y = fit)) 

从图中,我们可以看出模型和图有些矛盾 - 这是因为您的模型被指定为预测概率 (Tot - Pos) / Pos,但您的图显示的是补码 Pos / Tot ,我建议更换一个以匹配另一个。


使用此数据:

dd = read.table(header = TRUE, text = "Pos   Tot   Age
1     1    11     1
2     0     1     1
3     3     3     1
4     1     2     1
5     5     7     1
47   13    16     4
48    9     9     4
49    9    10     4
50   14    14     4    
158   1     3     2
159   3     5     2
160   0     7     2
161   9    12     2
162   0     2     2
209   0     1     3
210   1     2     3
211   1     1     3
212   2     2     3")

以及您问题中的模型:

model1 <- glm(cbind(Tot - Pos, Pos) ~ -1+Age,
        family = binomial(link = "log"), data = dd)