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

如何用R语言forestplot/ggplot2绘制带均值±标准差的森林图

用ggplot2绘制展示均值±标准差的分组森林图

核心问题解决:单个研究多均值点

你遇到的单个研究出现多个均值点的问题,本质是数据格式未整理为长格式——宽格式下多个均值列会被ggplot2重复映射,导致同个研究出现多个点。先把数据转成长格式,再绘图就能解决。

步骤1:整理数据为长格式

假设你的原始数据是宽格式(如下模拟样本),用tidyr::pivot_longer转换为长格式,让每个研究的对照组/患者组各占一行:

# 模拟你的原始宽格式数据
df_wide <- data.frame(
  Study = c("Study A", "Study B", "Study C"),
  n_control = c(30, 45, 28),
  mean_control = c(12.3, 11.8, 13.1),
  sd_control = c(2.1, 1.9, 2.3),
  n_patient = c(32, 42, 30),
  mean_patient = c(15.6, 14.9, 16.2),
  sd_patient = c(2.5, 2.2, 2.4)
)

# 转换为长格式
library(tidyr)
df_long <- df_wide %>%
  pivot_longer(
    cols = -Study,
    names_to = c(".value", "Group"),
    names_pattern = "(n|mean|sd)_(.*)"
  )

转换后的长格式数据结构示例:

StudyGroupnmeansd
Study Acontrol3012.32.1
Study Apatient3215.62.5
Study Bcontrol4511.81.9

步骤2:用ggplot2绘制森林图

用长格式数据绘图,通过position_dodge让两组的点和误差线错开,避免重叠:

library(ggplot2)

ggplot(df_long, aes(x = mean, y = Study, color = Group)) +
  # 绘制标准差误差线(均值±SD)
  geom_errorbarh(aes(xmin = mean - sd, xmax = mean + sd), 
                 height = 0.2, 
                 position = position_dodge(width = 0.5)) +
  # 绘制均值点
  geom_point(size = 3, 
             position = position_dodge(width = 0.5)) +
  # 添加样本量标签(可选)
  geom_text(aes(label = paste0("n=", n)), 
            position = position_dodge(width = 0.5), 
            hjust = -0.2, 
            size = 3.5) +
  # 自定义标签和主题
  labs(x = "均值 ± 标准差", y = "研究", color = "分组") +
  theme_bw() +
  theme(
    panel.grid.major.y = element_blank(), # 去掉Y轴方向的网格线
    legend.position = "top" # 把图例放在顶部
  )

可选调整

  • 添加参考线(比如总体均值):用geom_vline(xintercept = 总体均值, linetype = "dashed")
  • 调整误差线颜色、点的形状:修改geom_errorbarh和geom_point的color、shape参数
  • 限制X轴范围:用xlim(c(最小值, 最大值))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 22:18:33