使用 ggplot2 绘制泊松混合模型

Plot poisson mixed models with ggplot2

我尝试使用 ggplot2 为标准目的绘制零膨胀模型和零膨胀混合模型,但没有成功。为此,我尝试:

#Packages
library(pscl)
library(glmmTMB)
library(ggplot2)
library(gridExtra)


# Artificial data set
set.seed(007)
n <- 100 # number of subjects
K <- 8 # number of measurements per subject
t_max <- 5 # maximum follow-up time
DF <- data.frame(id = rep(seq_len(n), each = K),
                 time = c(replicate(n, c(0, sort(runif(K - 1, 0, t_max))))),
                 sex = rep(gl(2, n/2, labels = c("male", "female")), each = K))
DF$y <- rnbinom(n * K, size = 2, mu = exp(1.552966))
str(DF)

使用带有 pscl 包的零膨胀泊松模型

time2<-(DF$time)^2
mZIP <- zeroinfl(y~time+time2+sex|time+sex, data=DF)
summary(mZIP)

如果我认为所有系数都是显着的

# Y estimated
pred.data1 = data.frame(
time<-DF$time,
time2<-(DF$time)^2,
sex<-DF$sex) 
pred.data1$y = predict(mZIP, newdata=pred.data1, type="response")

现在使用带有 glmmTMB 包的零膨胀泊松混合模型

mZIPmix<- glmmTMB(y~time+time2+sex+(1|id),
data=DF, ziformula=~1,family=poisson)
summary(mZIPmix)
#

# new Y estimated
pred.data2 = data.frame(
time<-DF$time,
time2<-(DF$time)^2,
sex<-DF$sex,
id<-DF$id) 
pred.data2$y = predict(mZIPmix, newdata=pred.data2, type="response")

绘制零膨胀泊松模型和混合泊松模型

par(mfrow=c(1,2))
plot1<-ggplot(DF, aes(time, y, colour=sex)) +
  labs(title="Zero inflated model") +
  geom_point() +
  geom_line(data=pred.data1) +
  stat_smooth(method="glm", family=poisson(link="log"), formula = y~poly(x,2),fullrange=TRUE)

plot2<-ggplot(DF, aes(time, y, colour=sex)) +
  labs(title="Zero inflated mixed model") +
  geom_point() +
  geom_line(data=pred.data2) +
  stat_smooth(method="glm", family=poisson(link="log"), formula = y~poly(x,2),fullrange=TRUE)## here a don't find any method to mixed glm
grid.arrange(plot1, plot2, ncol=2)
#-

当然行不通。可以使用 ggplot2 来实现吗? 提前致谢

我不确定,但在我看来,您正在寻找边际效应。您可以使用 ggeffects-package 执行此操作。这里有两个例子,使用你的模拟数据,创建一个 ggplot-object,一个有一个 w/o 原始数据。

library(glmmTMB)
library(ggeffects)

mZIPmix<- glmmTMB(y~poly(time,2)+sex+(1|id), data=DF, ziformula=~1,family=poisson)

# compute marginal effects and create a plot.
# the tag "[all]" is useful for polynomial terms, to produce smoother plots
ggpredict(mZIPmix, c("time [all]", "sex")) %>% plot(rawdata = TRUE, jitter = .01)

ggpredict(mZIPmix, c("time [all]", "sex")) %>% plot(rawdata = FALSE)

reprex package (v0.2.1)

创建于 2019-05-16

请注意 sex 仅具有 "additive" 效果。也许您想模拟时间和性别之间的交互?

mZIPmix<- glmmTMB(y~poly(time,2)*sex+(1|id), data=DF, ziformula=~1,family=poisson)

ggpredict(mZIPmix, c("time [all]", "sex")) %>% plot(rawdata = TRUE, jitter = .01)

ggpredict(mZIPmix, c("time [all]", "sex")) %>% plot()

reprex package (v0.2.1)

创建于 2019-05-16