R 用ggplot2绘制泊松混合模型

R 用ggplot2绘制泊松混合模型,r,ggplot2,glm,mixed-models,poisson,R,Ggplot2,Glm,Mixed Models,Poisson,我尝试使用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 <

我尝试使用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)
图书馆(glmmTMB)
图书馆(GG2)
图书馆(gridExtra)
#人工数据集
种子集(007)

我不确定,但在我看来,你在寻找边际效应。你可以用这个。下面是两个使用模拟数据创建ggplot对象的示例,一个包含原始数据,另一个不包含原始数据

库(glmmTMB)
图书馆(ggeffects)
mZIPmix%图(rawdata=TRUE,抖动=0.01)

ggpredict(mZIPmix,c(“时间[全部],“性别”))%>%绘图(rawdata=FALSE)

由(v0.2.1)于2019年5月16日创建

请注意,
sex
仅具有“相加”效应。也许你想在时间和性之间建立一个互动模型

mZIPmix%图(rawdata=TRUE,jitter=0.01)

ggpredict(mZIPmix,c(“时间[全部],“性别”))%>%plot()


由(v0.2.1)于2019-05-16创建的

两个图中都有问题还是只有一个?对于GLMM,您需要的是总体预测,而不是每个
id
的预测。您可以通过将预测数据集中的
id
设置为
NA
(根据
predict.glmmTMB
的文档)来实现这一点。问题只存在于GLMM模型的绘图中。我想要一个图,看看调整过的模型之间的差异。
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")
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)
#-