簡體   English   中英

如何在 R ggplot2 中擬合具有交互作用的混合效應模型回歸?

[英]How to fit a mixed effects model regression with interaction in R ggplot2?

我正在使用的數據集有一個交互項。 我想用 x 軸上的交互項和 y 軸上的y.var來擬合模型。 我嘗試按照這個示例進行操作,但對於如何在 ggplot2 中復制它並沒有走得太遠(即繪圖樣式功能不再起作用..所以我不知道如何復制結果)。

temp <- rnorm(100, 2,1)set.seed(111)
temp <- rnorm(100, 3,1)
rainfall <- rnorm(100,5,1)
y.var <- rnorm(100, 2,1)
site <- rep(c("A","B","C","D"), each = 25)     

df <- data.frame(temp, rainfall, y.var, site)
df$site <- as.factor(as.character(df$site))

mod <- lmer(y.var ~ temp * rainfall + (1|site), data  = df)
summary(mod)

如果您想直接在 ggplot 中繪制模型而不是使用擴展包,則需要生成一個預測數據框來繪制。 這樣做的好處是您還可以在繪圖中包含原始數據點。

由於 y 軸上有y.var ,因此您只剩下一個軸來繪制兩個固定效應變量。 這意味着您需要為 x 軸選擇降雨量或溫度,並用另一種美學(例如顏色)來表示另一個變量。 在本例中,我將使用溫度作為 x 軸。 顯然,為了使情節具有可解釋性,我們需要限制我們預測的降雨“切片”的數量。 這里我將使用 5。

此處可以看到相互作用效應,因為隨着降雨量的增加,線的斜率會發生變化。

library(geomtextpath)
library(lme4)

mod <- lmer(y.var ~ temp * rainfall + (1|site), data  = df)

newdf <- expand.grid(temp = seq(min(df$temp), max(df$temp), length = 100),
                     rainfall = seq(min(df$rainfall), max(df$rainfall), 
                                    length = 5))

newdf$y.var <- predict(mod, newdata = newdf)

ggplot(newdf, aes(x = temp, y = y.var, group = rainfall)) +
  geom_point(data = df, aes(shape = site, color = rainfall)) +
  geom_textline(aes(color = rainfall, label = round(rainfall, 2)), 
                hjust = 0.95) +
  scale_color_gradient(low = 'navy', high = 'red4') +
  theme_light(base_size = 16)

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM