如何使用方法 = glmmTMB::glmmTMB 和点权重的 ggplot 可视化交互效果

How to visualise an interaction effect using ggplot with method = glmmTMB::glmmTMB and point weights

我正在 运行R 中分析树冠覆盖 (OverheadCover) 和放置在同一位置的尸体数量 (CarcassNumber) 对比例的影响被鸟类吃掉的腐肉 (ProportionBirdsScavenging)。交互作用 OverheadCover * CarcassNumber 很重要,我想使用 ggplot 将其可视化,如下所述:https://sebastiansauer.github.io/vis_interaction_effects/。我不会像示例中那样使用 method = "lm",而是 method = glmmTMB::glmmTMB。我添加了额外的参数 formula =method.args = 以确保 R 正确计算平滑度。

它应该是这样的,但我更喜欢用 ggplot 制作图表,因为这样我所有的图表都会采用相同的样式。

glmm_interaction <- glmmTMB(ProportionBirdsScavenging ~ OverheadCover * CarcassNumber + (1|Area), data = data_both, beta_family(link = "logit"), weights = pointWeight_scaled)
plot_model(glmm_interaction, type = "int", ci.lvl = 0.682) # conf. int. of 68.3% -> ± standard error

这是我正在尝试使用的代码 运行,但我无法让它工作。它一直给我错误,比如 object 'pointWeight_scaled' not found。有人知道我在这里做错了什么吗?

qplot(x = OverheadCover, y = ProportionBirdsScavenging, color = CarcassNumber, data = data_both) +
  geom_smooth(method = glmmTMB::glmmTMB,
              formula = ProportionBirdsScavenging ~ OverheadCover * CarcassNumber,
              method.args = list(data = data_both, beta_family(link = "logit"), weights = pointWeight_scaled))

我知道单独 运行 模型并将它们绘制在同一图表上可能更容易。我已经做到了,而且有效。然而,我计算的标准误差比 plot_model() 中的要大,所以我想看看如果 R 完成了所有工作,这些标准误差会是什么样子,因此我打算这样绘制它。

This is how it should look, but I prefer the graph to be made with ggplot

plot_model()返回的plot是一个ggplot-object,你可以随意修改。您也可以使用 ggeffects-package, which returns the underlying data that can be used to create the plot. There are many examples in the vignettes, both on how to create own plots or how to modify plots returned by plot(), e.g. here or here.

这是一个玩具示例:

library(ggplot2)
library(ggeffects)
library(lme4)
#> Loading required package: Matrix

set.seed(123)

dat <- data.frame(
  outcome = rbinom(n = 500, size = 1, prob = 0.25),
  var_binom = as.factor(rbinom(n = 500, size = 1, prob = 0.3)),
  var_cont = rnorm(n = 500, mean = 10, sd = 3),
  group = sample(letters[1:4], size =500, replace = TRUE)
)

model <- glmer(
  outcome ~ var_binom * poly(var_cont, 2) + (1 | group), 
  data = dat, 
  family = binomial(link = "logit")
)

predictions <- ggpredict(model, c("var_cont [all]", "var_binom"))

# plot-function from ggeffects
plot(predictions)

# self made ggplot
ggplot(
  predictions, 
  aes(x = x, y = predicted, ymin = conf.low, ymax = conf.high, colour = group, fill = group)
) +
  geom_line() +
  geom_ribbon(alpha = .1, colour = NA) +
  theme_minimal()

reprex package (v0.3.0)

于 2020-02-06 创建