I would like to plot the results of a multilevel model in R, specifically to illustrate an interaction effect, using plot_model from sjPlot. I would like to use a specific color scheme and I would also like to label the three levels of the legend (low, medium, high). However, when I try to do both of these things, the shading reverts to the default color scheme.
Here is a reproducible example of what I've tried, using a merTools dataset.
library(lme4)
library(sjPlot)
library(merTools)
colors<-c("red","darkred","pink")
m1 = lmer(mathach ~ ses + meanses + ses*meanses + (1|schid), data=hsb)
p1<-plot_model(m1, type="pred", terms= c("ses","meanses"),
colors= colors, legend.title = "Mean SES")+
labs(y="SES", x="Mean SES",
linetype = "meanses") +
scale_color_manual(labels = c("Low (-1 SD)", "Average", "High (+1 SD)"), values=colors)
p1
This gets me the message "Scale for colour is already present. Adding another scale for colour, which will replace the existing scale."
If I leave out the scale_color_manual code, I get the coloring that I wanted, but not the legend labels I wanted.
To add your labels and apply your colors for both the color
and the fill
aesthetic add aesthetics = c("color", "fill")
to scale_color_manual
.
Using a minimal reproducible example based on the default example from ?lme4::lmer
:
library(lme4)
#> Loading required package: Matrix
library(sjPlot)
library(ggplot2)
colors <- c("red", "darkred", "pink")
sleepstudy$foo <- rep(LETTERS[1:3], each = 60)
m1 <- lmer(Reaction ~ Days + Days * foo + (Days | Subject), sleepstudy)
p1 <- plot_model(m1,
type = "pred", terms = c("Days", "foo"),
colors = colors, legend.title = "Mean SES"
) +
labs(
y = "SES", x = "Mean SES",
linetype = "meanses"
) +
scale_color_manual(
labels = c("Low (-1 SD)", "Average", "High (+1 SD)"), values = colors,
aesthetics = c("color", "fill")
)
#> Scale for colour is already present.
#> Adding another scale for colour, which will replace the existing scale.
p1