如何用ggplot2复现带分组比值比的森林图及侧边统计表格?
复现带侧边统计表格的分组森林图
这种图是森林图+分组统计表格的组合,我们可以用ggplot2绘制森林图主体,再结合patchwork(或gridExtra)将统计表格与图拼接,也可以直接在ggplot图层中添加文本实现表格效果。以下是完整的复现步骤:
1. 准备模拟数据
先构造符合场景的数据集,包含结局变量、分组的效应估计值、置信区间、P值等信息:
library(tidyverse) library(patchwork) # 模拟数据:结局变量、分组(干预/对照)的均值/率、OR值及CI、P值 df_plot <- tibble( outcome = factor(c("结局1", "结局2", "结局3", "结局4", "结局5"), levels = c("结局5", "结局4", "结局3", "结局2", "结局1")), # 反转顺序对应y轴 group1_est = c("2.3 (1.1-3.5)", "45.2%", "12.8", "0.76", "89.1"), # 分组1的估计值 group2_est = c("1.8 (0.9-2.7)", "32.1%", "9.6", "0.52", "76.3"), # 分组2的估计值 or = c(1.32, 1.78, 1.33, 1.46, 1.68), ci_low = c(0.91, 1.22, 0.87, 1.01, 1.15), ci_high = c(1.92, 2.59, 2.02, 2.11, 2.47), p_value = c("0.14", "<0.01", "0.18", "0.04", "<0.01") )
2. 绘制森林图主体
用ggplot2绘制核心的森林图,包含点估计和置信区间:
p_forest <- ggplot(df_plot, aes(x = or, y = outcome)) + # 添加置信区间 geom_errorbarh(aes(xmin = ci_low, xmax = ci_high), height = 0.2, color = "#636363") + # 添加点估计 geom_point(size = 3, color = "#2c3e50") + # 添加OR=1的参考线 geom_vline(xintercept = 1, linetype = "dashed", color = "#e74c3c") + # 设置x轴范围和标签 scale_x_continuous(limits = c(0.5, 3), breaks = seq(0.5, 3, 0.5)) + labs(x = "比值比 (OR)", y = "") + # 调整主题,去除多余元素 theme_minimal() + theme( panel.grid.major.y = element_blank(), panel.grid.minor = element_blank(), axis.text.y = element_text(size = 10), axis.title.x = element_text(size = 11, face = "bold") )
3. 制作侧边统计表格
我们用ggplot2生成表格样式的图,方便和森林图拼接:
p_table <- ggplot(df_plot, aes(y = outcome)) + # 添加分组1的估计值文本 geom_text(aes(x = 1, label = group1_est), hjust = 0.5, size = 3.5) + # 添加分组2的估计值文本 geom_text(aes(x = 2, label = group2_est), hjust = 0.5, size = 3.5) + # 添加P值文本 geom_text(aes(x = 3, label = p_value), hjust = 0.5, size = 3.5) + # 添加表格标题 annotate("text", x = 1, y = length(df_plot$outcome)+1, label = "干预组", size = 4, fontface = "bold") + annotate("text", x = 2, y = length(df_plot$outcome)+1, label = "对照组", size = 4, fontface = "bold") + annotate("text", x = 3, y = length(df_plot$outcome)+1, label = "P值", size = 4, fontface = "bold") + # 设置坐标轴和主题 scale_x_continuous(limits = c(0.5, 3.5), breaks = NULL) + scale_y_discrete(limits = rev(levels(df_plot$outcome))) + # 和森林图y轴顺序一致 labs(x = "", y = "") + theme_minimal() + theme( panel.grid = element_blank(), axis.text = element_blank(), plot.margin = margin(5, 10, 5, 5) )
4. 拼接森林图和表格
用patchwork将两个图组合,调整宽度比例:
# 拼接表格和森林图,表格宽度占比小,森林图占比大 p_table + p_forest + plot_layout(widths = c(1, 2))
关键调整说明
- 如果需要更贴合示例图的样式,可以修改颜色、字体大小、文本对齐方式
- 若你的数据是其他效应量(如RR、均值差),只需替换
or列和x轴标签即可 - 如果要在森林图右侧添加表格,只需调整拼接顺序和布局
内容的提问来源于stack exchange,提问作者Nao
相关产品推荐
相关产品推荐

