英文:
How to use lmer within geom_smooth
问题
# 混合效应模型
m_intercept <- lmer(grades ~ iq + (1 | class), data = df1)
summary(m_intercept)
# 使用 ggplot 的 geom_smooth 函数绘制图表
ggplot(df1, aes(x = iq, y = grades, color = class)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE)
英文:
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.
答案1
得分: 2
只需创建一个预测数据框并绘图:
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)
Simpson悖论的一个很好的演示。如果你的目标是真正演示Simpson悖论,你可能想添加一些花里胡哨的东西:
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")
英文:
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论