Notification texts go here Contact Us Buy Now!

Drawing a regression line with interaction in ggplot2

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)

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.