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

时间:2018-08-09 17:43:49

标签: r ggplot2 glm predict

我想从glm模型绘制回归线(如下所示)。理想情况下,我想将其绘制在观察到的数据上,但是我无法适应在其他地方(例如predict.glmPlot 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)

返回观测值的散点图,但还会显示错误消息:

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概率标度?

非常感谢

1 个答案:

答案 0 :(得分:0)

以下是生成预测的方法:

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)) 

enter image description here

从图中可以看出,模型和图有些矛盾-这是因为您的模型被指定为预测概率(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)
相关问题