在geom_smooth中使用二项式公式的语法

5

我在R中计算了二项式回归:

Call:
glm(formula = cbind(success, failure) ~ x * f, family = "binomial", 
    data = tb1)

Deviance Residuals: 
    Min       1Q   Median       3Q      Max  
-3.6195  -0.9399  -0.0493   0.5698   2.0677  

Coefficients:
              Estimate Std. Error z value Pr(>|z|)    
(Intercept) -2.3170182  0.0622600 -37.215  < 2e-16 ***
x            0.0138201  0.0009892  13.972  < 2e-16 ***
fTRUE        0.6466238  0.1976115   3.272  0.00107 ** 
x:fTRUE     -0.0035741  0.0032587  -1.097  0.27273    
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 479.88  on 147  degrees of freedom
Residual deviance: 201.53  on 144  degrees of freedom
  (7 observations deleted due to missingness)
AIC: 870.72

Number of Fisher Scoring iterations: 4    

我希望能够将其可视化,即绘制数据和回归曲线。我可以轻松地使用线性平滑器:

ggplot(tb1, aes(x, success/(success+failure), colour=f)) +
  geom_point() +
  geom_smooth(method="lm")

线性回归

但我真正想要的是通过数据绘制一个逻辑曲线。当我尝试时:

ggplot(tb1, aes(x, success/(success+failure), colour=f)) +
  geom_point() +
  geom_smooth(
    method="glm",
    method.args=list(family="binomial"),
  )

我得到了这张图表:

可疑二项回归

看起来不太对。标准误差不应该那么大。我认为我需要在geom_smooth中明确指定公式,但是我无法正确地使用语法。当我尝试时:

ggplot(tb1, aes(x, success/(success+failure), colour=f)) +
  geom_point() +
  geom_smooth(
    method="glm",
    method.args=list(
      family="binomial",
      formula = cbind(success, failure) ~ x
    )
  )

我收到了以下信息:

警告信息:
stat_smooth() 中计算失败:
找不到对象“success”

我该如何正确指定公式?


1
似乎这个公式只知道 x 和 y,这些变量可能是从美学中推断出来的? - NelsonGon
1
@NelsonGon:谢谢,你似乎是对的。然而,现在我收到了警告:“在eval(family $ initialize)中的二项式glm中非整数#successes!” - Igor F.
1
这个应该是统计相关的。看一下这个问题 - NelsonGon
1个回答

9

像二项式回归一样,在geom_smooth中的公式需要将成功和失败的矩阵作为响应。相应的变量需要在美学上定义:

ggplot(tb1, aes(x, y=success/(success+failure), colour=f, succ=success, fail=failure)) +
  geom_point() +
  geom_smooth(
    method="glm",
    method.args=list(family="binomial"),
    formula = cbind(succ, fail) ~ x
  )

现在它可以工作了:

二项平滑处理正确

感谢NelsonGon指出这一点。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接