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

如何高效计算多个ggpredict对象的均值并使用ggplot绘图?

解决多重插补后ggpredict结果的均值计算与绘图问题

问题原因

直接使用Reduce(+, list_ggpred)/length(list_ggpred)报错,是因为ggpredict返回的结果中包含age、hyp这类因子型分组变量,因子不支持加法运算,导致出现Ops.factor(left, right) : + not meaningful for factors警告。


a) 按分组计算预测值与置信区间的均值

步骤代码

# 加载所需包
library(mice)
library(ggpredict)
library(tidyverse)

# 假设list_ggpred是你得到的10个ggpredict对象组成的列表
# 1. 合并所有插补的预测结果
combined_preds <- bind_rows(list_ggpred, .id = "imputation_id")

# 2. 按age和hyp分组,计算预测值、置信区间的均值
mean_preds <- combined_preds %>%
  group_by(age, hyp) %>%
  summarise(
    predicted_mean = mean(predicted),
    conf_low_mean = mean(conf.low),
    conf_high_mean = mean(conf.high),
    .groups = "drop"  # 取消分组状态
  )

代码说明

  • bind_rows()将所有ggpredict结果合并为一个数据框,保留插补编号便于溯源(可选)。
  • group_by(age, hyp)指定分组变量,确保按年龄和高血压状态分别计算均值。
  • summarise()对每个分组内的predicted(预测值)、conf.low(置信区间下限)、conf.high(置信区间上限)求均值,得到合并后的汇总结果。

b) 用ggplot绘制均值结果

绘图代码

ggplot(mean_preds, aes(x = age, y = predicted_mean, color = hyp, group = hyp)) +
  # 绘制均值点
  geom_point(position = position_dodge(width = 0.2), size = 2) +
  # 绘制置信区间误差棒
  geom_errorbar(aes(ymin = conf_low_mean, ymax = conf_high_mean), 
                width = 0.2, position = position_dodge(width = 0.2), linewidth = 0.8) +
  # 自定义标签与主题
  labs(
    x = "年龄",
    y = "BMI预测均值",
    color = "高血压状态",
    title = "多重插补后BMI预测值及95%置信区间均值"
  ) +
  theme_minimal()

绘图说明

  • position_dodge(width = 0.2)让不同hyp组的点和误差棒错开,避免重叠。
  • geom_errorbar()展示95%置信区间的均值范围,直观呈现结果的不确定性。
  • 可根据需求调整size、linewidth、主题等参数优化可视化效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 03:17:17