绘制具有数值变量交互作用的二项式 glm

Plotting binomial glm with interactions in numeric variables

我想知道是否可以绘制具有数值变量交互作用的二项式 glm。就我而言:

##Data set artificial
set.seed(20)
d <- data.frame(
    mating=sample(0:1, 200, replace=T),
    behv = scale(rpois(200,10)),
    condition = scale(rnorm(200,5))
) 

#Binomial GLM ajusted
model<-glm(mating ~ behv + condition, data=d, family=binomial)
summary(model)

在行为和条件在模型中很重要的情况下

#Plotting first for behv
x<-d$behv ###Take behv values
x2<-rep(mean(d$condition),length(d_p[,1])) ##Fixed mean condition

# Points
plot(d$mating~d$behv)

#Curve
curve(exp(model$coefficients[1]+model$coefficients[2]*x+model$coefficients[3]*x2)
/(1+exp(model$coefficients[1]+model$coefficients[2]*x+model$coefficients[3]*x2)))

但是不起作用!!还有其他正确的做法吗?

谢谢

您想要的输出似乎是条件均值图(或 best-fit 线)。您可以通过使用 predict 函数计算预测值来做到这一点。

我将稍微更改一下您的示例,以获得更好看的结果。

d$mating <- ifelse(d$behv > 0, rbinom(200, 1, .8), rbinom(200, 1, .2))
model <- glm(mating ~ behv + condition, data = d, family = binomial)
summary(model)

现在,我们用您想要的值制作一个 newdata 数据框:

newdata <- d
newdata$condition <- mean(newdata$condition)
newdata$yhat <- predict(model, newdata, type = "response")

最后,我们按 x-axis 变量对 newdata 进行排序(如果不是,我们将在整个绘图中得到 zig-zag 的行),然后绘制:

newdata <- newdata[order(newdata$behv), ]
plot(newdata$mating ~ newdata$behv)
lines(x = newdata$behv, y = newdata$yhat)

输出: