You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot的stat_poly_eq()中添加随机效应?

在ggplot中为stat_poly_eq添加随机效应的解决方案

你遇到的问题根源有两个:

  1. stat_poly_eq() 原生只支持lm()这类固定效应线性模型,不兼容lmer()混合效应模型
  2. 你的公式写法错误:随机效应分组变量只需写列名(如wt)而非mtcars$wt,而且连续变量wt作为随机截距的分组逻辑完全不合理——随机效应是用来处理分类分组(比如气缸数cyl、变速箱类型am)的,连续变量做分组会让每个唯一的wt值对应一个随机截距,模型既无统计意义又会报错。

下面是具体的解决步骤,分两种场景:


场景1:确实需要加入分类变量的随机效应

如果你的真实需求是给某个分类变量(比如cyl)加随机截距,用lme4::lmer()拟合模型,再通过ggpmisc的stat_fit_glance自定义标注方程:

步骤1:加载依赖包

library(ggplot2)
library(ggpmisc)
library(lme4)
library(broom.mixed)

步骤2:写一个提取混合效应模型信息的函数

这个函数会提取固定效应的斜率、截距,以及边际R²(衡量固定效应的解释力):

extract_mixed_eq <- function(model) {
  # 提取固定效应参数
  fixed_params <- tidy(model, effects = "fixed")
  intercept <- round(fixed_params$estimate[fixed_params$term == "(Intercept)"], 2)
  slope <- round(fixed_params$estimate[fixed_params$term == "x"], 2)
  # 计算边际R²
  marginal_r2 <- round(r.squaredGLMM(model)[["R2m"]], 2)
  
  # 拼接成方程文本
  paste0("y = ", slope, "x + ", intercept, "\nMarginal R² = ", marginal_r2)
}

步骤3:绘制带随机效应的可视化

这里以mpg为因变量,disp为自变量,cyl为随机截距分组,保留分面:

ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point(color = "darkgray") +
  # 拟合混合效应回归线
  stat_smooth(method = "lmer", formula = y ~ x + (1 | cyl), 
              se = TRUE, color = "#2c3e50") +
  # 添加自定义方程标注
  stat_fit_glance(method = "lmer", formula = y ~ x + (1 | cyl),
                  geom = "text", aes(label = extract_mixed_eq(.model)),
                  position = position_nudge(x = 60, y = 4), size = 3.5) +
  facet_wrap(~am) +
  theme_minimal()

场景2:误将连续变量设为随机效应

如果你的真实需求是把wt作为固定效应加入模型,而非随机效应,直接修正公式即可,此时可以继续用stat_poly_eq():

my.formula <- y ~ x + wt

ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point() +
  stat_smooth(method = "lm", formula = my.formula, se = TRUE) +
  stat_poly_eq(formula = my.formula, aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
               parse = TRUE) +
  facet_wrap(~am)

重要提醒

  • 随机效应的分组变量必须是分类变量,连续变量做分组会导致模型逻辑混乱,甚至无法拟合
  • 混合效应模型的R²有两种:边际R²(仅固定效应)和条件R²(固定+随机效应),根据你的需求选择
  • stat_poly_eq() 没有适配混合效应的原生支持,必须通过自定义函数配合stat_fit_glance实现方程标注

内容的提问来源于stack exchange,提问作者JamesR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 11:52:52