strengejacke / sjPlot

sjPlot - Data Visualization for Statistics in Social Science
https://strengejacke.github.io/sjPlot
606 stars 91 forks source link

plot 3-way interaction with data points #585

Open mpapoutsi opened 4 years ago

mpapoutsi commented 4 years ago

Hi I want to plot a 3-way interaction between continuous variables and show the data.

I get three panels side by side and the marginal means for each group factor (tiv_base). However, the data points are not split by the factor "tiv_base". Each panel shows all data points. Is there a way to fix this and split the data points the panel?

Here is the code and the resulting plots. mixed_model <- lmer(cs ~ dtimer(tiv_basedbs_base) + (dtimer | sbj), data = zdata2a)

plot_model(mixed_model, type = "emm", terms = c("dtimer [all]", "dbs_base", "tiv_base"), mdrt.values = "quart", show.legend = T, line.size = 2, show.data =T)

TIV_by_DBS_by_time

I tried adding the data points manually using geom_point and facet_grid/facet_wrap. However, when I do that the lines plotting the marginal means seem to be double plotting. The code and figure is below (ps. I also added different grouping for this one, because I wanted the data to have discrete color)

p + geom_point(data = zdata2a, mapping = aes(x = dtimer, y = cs, group = dbs_group, colour = dbs_group), inherit.aes = F) + scale_fill_manual(values = c("red", "blue", "black")) + scale_color_manual(values = c("red", "blue", "black")) + facet_wrap(~tiv_group)

TIV_by_DBS_by_time_ZigZag

Many thanks for the help, Marina

strengejacke commented 4 years ago

Do you have a reproducible example?

mpapoutsi commented 4 years ago

Hi,

This should work.

library(lmertest) library(sjPlot) library(ggplot2)

tiv <- rnorm(100) dbs <- rnorm(100) cs <- rnorm(100) dt <- rep(c(0:3), 25) sbj <- rep(c(1:25), each=4) tmp <- data.frame(tiv, dbs, cs, dt, sbj)

tmp$dbs_group <- cut(tmp$dbs, c(-2.5, -0.84, 0.83, 2.5), labels = c(-1.01, -0.03, 0.95)) tmp$tiv_group <- cut(tmp$tiv, c(-2.7, -0.74, 0.68, 2.4), labels = c(-1.11, 0.01, 1.13))

mmod <- lmer(cs ~ dt tiv dbs + (dt | sbj), data = tmp, control=lmerControl(optimizer="bobyqa"))

p <- plot_model(mmod, type = "emm", terms = c("dt [all]", "dbs", "tiv"), mdrt.values = "quart", show.legend = T, line.size = 2, show.data =T)

For the second part, when adding the datapoints manually, set show.data = F and add:

p + geom_point(data = tmp, mapping = aes(x = dt, y = cs, group = dbs_group, colour = dbs_group), inherit.aes = F) + scale_fill_manual(values = c("red", "blue", "black")) + scale_color_manual(values = c("red", "blue", "black"))+ facet_grid(~tiv_group)

Many thanks! M