With the ggeffects
package, drawing a regression line with interaction in ggplot2
can be achieved using the ggpredict()
function.
library(tidyverse)
library(ggeffects)
#Generate an example dataset for reproduciblity:
set.seed(42)
example_data =
data.frame(treatment = as.factor(c(rep("t1", 50), rep("t2", 50))),
time = rep(1:50, 2),
error = rnorm(100, 0, 1)) %>%
mutate( slope = ifelse(treatment == "t1", -0.2, -0.3)) %>%
mutate( measurement = 2.5 + time * slope + error)
#Linear model that I want to display in my plot:
model = lm(measurement ~ time:treatment, data = example_data)
summary(model)
g <- ggpredict(model, terms=c("time", "treatment"))
plot(g)
The ggpredict()
function produces a modified tibble, on which you can call plot()
to generate a plot with superposed lines.
Since the result of plot(g)
is a ggplot
object, you can modify it in the expected ways (e.g., adding a facet):
plot(g) + facet_wrap(~group)