My mixed effects model is very simple, one outcome, one covariate, one random intercept. Something similar to this.
# download data directly from URL
url <- "https://raw.githubusercontent.com/hauselin/rtutorialsite/master/data/simpsonsParadox.csv"
df1 <- fread(url)
# LMER model
m_intercept <- lmer(grades ~ iq + (1 | class), data = df1)
summary(m_intercept)
My question is how do I plot this using ggplot
function geom_smooth
?
Something similar to this
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(method = lm, se = FALSE)
Thanks.
Simply create a data frame of predictions and plot:
newdata <- expand.grid(iq = 90:130, class = letters[1:4])
newdata$grades <- predict(m_intercept, newdata)
ggplot(df1, aes(iq, grades, color = class)) +
geom_point() +
geom_line(data = newdata)
A nice demonstration of Simpson's paradox indeed. If your goal is to actually demonstrate Simpson's paradox, you might want to add some bells and whistles:
newdata <- data.frame(iq = c(90, 105, 95, 115, 105, 125, 110, 130),
class = rep(letters[1:4], each = 2))
newdata$grades <- predict(m_intercept, newdata)
ggplot(df1, aes(iq, grades, color = class)) +
geom_point(size = 3, alpha = 0.5) +
geom_line(data = newdata) +
geom_smooth(se = FALSE, aes(linetype = "Naive linear model"),
color = "gray50", method = "lm") +
scale_linetype_manual(NULL, values = 3) +
theme_minimal(base_size = 16) +
scale_color_brewer("Mixed effect model\nwith intercept\nper class",
palette = "Set1") +
ggtitle("Illustration of Simpson's Paradox")