Reputation: 45
I am performing a multilevel (logistic) regression with two predictors, B and C. B and C have similar ranges so they can reasonably be shown using the same units in the x-axis. I want to do this because I want to highlight in my figure how they have different slopes.
When I try to do so using plot_model and the code below, one of the variables gets sent to the legend and I get this. However, I would rather have this.
Can this be done?
Thanks for the help!
df_test <- data.frame('subj' = c('Joe', 'Joe', 'Joe', 'Moe', 'Moe', 'Moe'), 'A' = c(1, 0, 1, 0, 1, 1), 'B' = c(3, 2, 1, 4, 3, 3), 'C' = c(3, 3, 2, 1, 3, 0))
m = glmer(A ~ B + C + (B + C| subj), data=df_test, family='binomial')
print(plot_model(m, terms = c('B', 'C'), type='pred'))
Upvotes: 1
Views: 1104
Reputation: 7832
You want to "overlay" two plots, one with predicted values for B, and one for C. Since sjPlot uses the ggeffects-package to compute marginal effects, I suggest you use ggeffects directly, and build your own ggplot-object.
Since B and C have different ranges, you could force the range to be the same for both (see second example below).
library(lme4)
library(ggeffects)
library(ggplot2)
df_test <-
data.frame(
'subj' = c('Joe', 'Joe', 'Joe', 'Moe', 'Moe', 'Moe'),
'A' = c(1, 0, 1, 0, 1, 1),
'B' = c(3, 2, 1, 4, 3, 3),
'C' = c(3, 3, 2, 1, 3, 0)
)
m <- glmer(A ~ B + C + (B + C | subj), data = df_test, family = 'binomial')
#> boundary (singular) fit: see ?isSingular
# get predictions for each predictor, combibe results
dat <- get_complete_df(ggpredict(m))
ggplot(dat, aes(x = x, y = predicted, colour = group, fill = group)) +
geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = .1, colour = NA) +
geom_line()
# get predictions for each predictor, combibe results
dat1 <- ggpredict(m, "B [0:4]")
dat1$group <- "B"
dat2 <- ggpredict(m, "C [0:4]")
dat2$group <- "C"
dat <- rbind(dat1, dat2)
ggplot(dat, aes(x = x, y = predicted, colour = group, fill = group)) +
geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = .1, colour = NA) +
geom_line()
Created on 2019-07-24 by the reprex package (v0.3.0)
Upvotes: 1