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

如何用dwplot()绘制多个R回归模型的lsmeans结果?

绘制多个模型的LS均值:解决dwplot报错问题

问题背景

需要绘制多个回归模型的LS均值(通过lsmeans包计算),但直接将lsmeans对象传入dwplot()会报错。最小复现代码如下:

# 生成数据
df <- data.frame(
  y1 = runif(100),
  y2 = runif(100),
  x = c(rep("A",times=50), rep("B",times=50))
)

# 拟合模型
m0 <- lm(y1 ~ factor(x), data = df)
m1 <- lm(y2 ~ factor(x), data = df)

# 计算LS均值
library(lsmeans)
lsm0 <- lsmeans(m0, ~ factor(x), data = df)
lsm1 <- lsmeans(m1, ~ factor(x), data = df)

# 直接调用dwplot报错
dwplot(list(lsm0, lsm1), show_intercept=T) + theme_bw()

解决方案

dwplot()默认仅支持标准模型对象(如lm),无法直接解析lsmeans生成的特殊类对象,需先将LS均值结果转换为标准数据框格式,再传入绘图函数。

方法1:用broom提取结果后调用dwplot

借助broom.mixed包提取LS均值的统计量,整理成统一数据框后传入dwplot():

library(broom.mixed)
library(dotwhisker)
library(ggplot2)
library(dplyr)

# 提取每个模型的LS均值结果并添加模型标识
tidy_lsm0 <- tidy(lsm0) %>% mutate(model = "y1 ~ x")
tidy_lsm1 <- tidy(lsm1) %>% mutate(model = "y2 ~ x")

# 合并数据
combined_lsm <- bind_rows(tidy_lsm0, tidy_lsm1)

# 调用dwplot绘制
dwplot(combined_lsm, 
       x = "estimate", 
       y = "term", 
       ymin = "conf.low", 
       ymax = "conf.high",
       color = "model") + 
  theme_bw() +
  labs(x = "LS均值", y = "分组")

方法2:用ggplot2手动绘制(更灵活)

如果需要自定义绘图细节,直接用ggplot2基于整理好的数据框绘制:

ggplot(combined_lsm, aes(x = estimate, y = term, color = model)) +
  geom_vline(xintercept = 0, linetype = "dashed", alpha = 0.5) + # 添加参考线
  geom_point(position = position_dodge(width = 0.5)) + # 绘制均值点
  geom_errorbarh(aes(xmin = conf.low, xmax = conf.high), 
                 height = 0.2, position = position_dodge(width = 0.5)) + # 绘制置信区间
  theme_bw() +
  labs(x = "LS均值", y = "分组")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 15:14:52