3

I am trying to the for a mixed model with a binomial logit link function.

My issue is that I initially run the model with scaled continuous variables, which I then use within the ggpredict() function.

However, when I try to plot the marginal effects, the x-axis for the marginal effects uses the scaled variables and I would like to plot it with the original continuous unscaled data. Thereby making it more interpretable.

I'm unsure of how to do this. I have attached a minimum reproducible example.

    #data
    dat <- data.frame(age = seq(1,5, by = 1),
                      sex = as.factor(c("M", "F")),
                      cluster = runif(20, min=0, max=100),
                      household = runif(50, min=0, max=100),
                      temp = runif(100, min=0, max=100),
                      prec = runif(100, min=0, max=100),
                      hum = runif(100, min=0, max=100),
                      disease = c(1,0))

    #scale continuous variables
    pvars <- c("temp", "prec", "hum")
    datsc <- dat
    datsc[pvars] <- lapply(datsc[pvars],scale)

    #setting the control to run faster

    contr1 <- glmerControl(optimizer = "nloptwrap", calc.derivs = FALSE)

    #run glmer model


    model1 <- glmer(disease ~  hum + temp + prec +  (1|cluster/household), 
                               family = binomial("logit"), 
                               data = datsc, control = contr1) 

    modelsummary<- summary(model1)

    #calculate marginal effects

    humidity <- data.frame(ggpredict(model1, term = "hum [all]", type = "fe"))

    humidity_plot <- ggplot(data=humidity, aes(x=x, y=predicted)) + 
      geom_line(size = 1) +
      geom_ribbon(aes(ymin=conf.low, ymax=conf.high, fill = group), linetype=2, alpha=0.1) +
      scale_y_continuous(limits = c(0, 1), breaks = c(seq(0,1, by = 0.2))) + 
      xlab("Humidity") + 
      ylab("Probability of Disease") + theme_classic()

Any help would be much appreciated.

massisenergy
  • 1,764
  • 3
  • 14
  • 25
Hiral Shah
  • 31
  • 2

1 Answers1

0

After creating the predicted marginal effects dataframe via ggpredict(), add a new variable to the dataframe that is the unscaled version of the x values, then specify the unscaled variable as the x in the ggplot.

humidity <- data.frame(ggpredict(model1, term = "hum [all]", type = "fe"))

humidity$hum_unscaled <- humidity$x*sd(dat$hum) + mean(dat$hum)

humidity_plot <- ggplot(data=humidity, aes(x=hum_unscaled), y=predicted)) + 
  geom_line(size = 1) +
  geom_ribbon(aes(ymin=conf.low, ymax=conf.high, fill = group), linetype=2, alpha=0.1) +
  scale_y_continuous(limits = c(0, 1), breaks = c(seq(0,1, by = 0.2))) + 
  xlab("Humidity") + 
  ylab("Probability of Disease") + theme_classic()
Sean
  • 1