How to plot predicted data of a GLMM from the package glmmTMB?

Viewed 1022

i have the following data and created a model with the package glmmTMB in R for plant diameters ~ plant density (number of plants) with a random plot effect:

d <- data.frame (diameter = c(17,16,15,13,11, 19,17,15,11,11, 19,15,14,11,8),
                      plant_density = c(1000,2000,3000,4000,5000, 1000,2000,3000,4000,5000, 1000,2000,3000,4000,5000),
                      plot = c(1,1,1,1,1, 2,2,2,2,2, 3,3,3,3,3))

glmm.model <- glmmTMB(diameter ~  plant_density + (1|plot),
                        data = d,
                        na.action = na.omit,
                        family="gaussian",
                        ziformula = ~ 0)

My intention was to create a plot with predicted diameter data for different plant densities with an included random plot effect. So i tried to predict the data:

new.dat <- data.frame(diameter= d$diameter,
                      plant_density = d$plant_density,
                      plot= d$plot) 

new.dat$prediction <- predict(glmm.model, new.data = new.dat, 
                              type = "response", re.form = NA)

Unfortunately I get an output for every plot but wanted a generalized prediction for the diameter ~ plant density.

My goal is to create a plot like here, but with a regression model from glmmTMB which consider the random effect.

Thanks for ur help!

1 Answers

The ggeffects package makes this type of thing very easy to implement and customize.

For example

library('ggplot2')
library('glmmTMB')
library('ggeffects')
d <- data.frame (diameter = c(17,16,15,13,11, 19,17,15,11,11, 19,15,14,11,8),
                 plant_density = c(1000,2000,3000,4000,5000, 1000,2000,3000,4000,5000, 1000,2000,3000,4000,5000),
                 plotx = as.factor( c(1,1,1,1,1, 2,2,2,2,2, 3,3,3,3,3)))

glmm.model <- glmmTMB(diameter ~  plant_density + (1|plotx),
                      data = d,
                      family="gaussian")

# basically what your looking for
plot(ggpredict(glmm.model, terms = "plant_density"))

# with additional a change of limits on the y-axis
plot(ggpredict(glmm.model, terms = "plant_density")) + 
scale_y_continuous(limits = c(0, 20))

You can really do whatever you'd like with it from there, changing colors, themes, scales, the package has some nice vignettes as well.

Related