I am learning how to apply a multilevel modelling to traditional ANOVA research designs. I would like to plot fitted regression lines for each treatment using ggplot2. I would like to plot regression lines based on models I fitted, not let ggplot2 to plot since I would like to see how estimations differ based on changing models. I am aware that I can calculate coefficients and slopes by myself, but because the model is relatively complicated, I am looking for ways to plot more easily.
This is the sample code for the type of research design I am dealing with. I found that the sjPlot package (http://www.strengejacke.de/sjPlot/sjp.lm/) provides very nice plots, which shows the regression lines for each treatment over each test timing and actual observations on a scatter plot. This is exactly what I would like to make with ggplot.
require(tidyverse)
require(sjPlot)
set.seed (100)
dat <- data_frame(
participant_id = c(c(1:15), c(1:15)),
treatment = c(sample (letters [1:3], 15, replace = T), sample (letters [1:3], 15, replace = T)),
test_timing = c(sample(letters [1:3], 15, replace = T),sample(letters [1:3], 15, replace = T)),
learning_gain = (runif(30, min = 1, max = 20))
)
fit <- lm (learning_gain ~ treatment * test_timing -1, data = dat)
sjp.lm(fit, type = "pred",
vars = c("test_timing", "treatment"),facet.grid = F)
Or, something like this:
sjp.lm(fit, type = "pred",
vars = c("test_timing", "treatment"),facet.grid = T)
I would really appreciate it if you could teach me how I can make a plot similar to this image using the ggplot2 package. Thank you!
Indeed, sjPlot just calls a function from ggeffects. ggeffects again just returns a data frame with the marginal effects / predicted values. So you can use this data frame to build your own ggplot-objects, or simply use the
plot()
-function to create a plot (a ggplot-object).There is a package vignette that describes how to build own plots using ggplot: https://cran.r-project.org/web/packages/ggeffects/vignettes/marginaleffects.html
Furthermore, the help-files (see https://cran.r-project.org/web/packages/ggeffects/ggeffects.pdf) are full of examples on how to to create plots using ggplot. Maybe this helps you?
Here is an example for your specific case, but note that you will not see straight lines, because your variables are categorical:
Line plot
Dot plot
Dot plots with error bars
Facets
plot()-function from the ggeffects package
Raw Observations
ggpredict()
returns the raw data as attribute to the return value, so you can also plot the original observations as well:Or, also the simple way:
See also
?plot.ggeffects
for the different plot options, for instance, usejitter = FALSE
to remove the jittering for the raw data points etc...The
emmeans
package is pretty useful: