← 返回教程列表

🌲 森林图绘制

使用forestploter绘制发表级森林图

📖 概述

森林图(Forest Plot)是MR分析结果展示的核心图形,直观展示各SNP的效应值和置信区间。

📊 数据准备

library(data.table)

# 读取MR结果数据(示例格式)
dt <- fread("OR_results.csv", header = TRUE)

# 查看数据结构
# 需要的列:SNP名称、OR值、置信区间上下限、p值
head(dt)

# 选择需要的列(根据实际列名调整)
dt <- dt[, c("SNP", "or", "or_lci95", "or_uci95", "pval")]
dt <- na.omit(dt)

💻 完整绘制代码

步骤1:安装并加载包

# 安装forestploter包
install.packages('forestploter')

# 加载必要的包
library(grid)
library(forestploter)

步骤2:数据预处理

library(data.table)
library(dplyr)

# 读取数据
dt <- fread("OR_results.csv", header = TRUE)

# 选择需要的列
dt <- dt[, c("SNP", "or", "or_lci95", "or_uci95", "pval")]

# 添加空白列(用于森林图布局)
dt$` ` <- paste(rep(" ", 30), collapse = " ")

# 格式化OR和置信区间
dt$'OR(95%CI)' <- ifelse(
  is.na(dt$or),
  "",
  sprintf('%.2f(%.2f to %.2f)', 
      dt$or, dt$or_lci95, dt$or_uci95)
)

# 处理缺失值
dt[is.na(dt)] <- " "

步骤3:设置主题

# 创建森林图主题
tm <- forest_theme(
  base_size = 10,       # 基础字体大小
  
  # 可信区间设置
  ci_pch = 20,        # 可信区间点的形状
  ci_col = "#4575b4",     # 可信区间颜色
  ci_lty = 1,        # 可信区间线型
  ci_lwd = 2.3,       # 可信区间线宽
  ci_Theight = 0.2,     # 可信区间两端短竖线
  
  # 参考线设置
  refline_lwd = 1.5,     # 参考线宽度
  refline_lty = "dashed",  # 参考线线型
  refline_col = "red",    # 参考线颜色(OR=1)
  
  # 汇总菱形设置
  summary_fill = "#4575b4", # 汇总菱形填充色
  summary_col = "#4575b4",  # 汇总菱形边框色
  
  # 脚注设置
  footnote_cex = 1.1,    # 脚注字体大小
  footnote_fontface = "italic", # 脚注字体
  footnote_col = "blue"   # 脚注颜色
)

步骤4:绘制森林图

# 绘制森林图
p <- forest(
  dt[, c(1:4, 11:12, 8:10)], # 选择显示的列
  
  # 设置效应值
  est = dt$or,         # OR值
  lower = dt$or_lci95,    # 置信区间下限
  upper = dt$or_uci95,    # 置信区间上限
  
  # 图形参数
  sizes = 0.6,        # 点估计框大小
  ci_column = 5,       # 置信区间显示列
  ref_line = 1,       # 参考线位置(OR=1)
  xlim = c(0, 4),      # x轴范围
  ticks_at = c(0, 1, 2, 3, 4), # x轴刻度
  
  # 轴标签
  arrow_lab = c('Protective', 'Risk'),
  
  # 脚注
  footnote = 'P<0.05 was considered statistically significant',
  
  # 应用主题
  theme = tm
)

# 显示图形
print(p)

步骤5:保存图片

# 保存为PNG格式
png(filename = 'forest_plot.png', 
  width = 8000, 
  height = 2800, 
  res = 350)

print(p)

dev.off()

# 保存为TIFF格式(期刊推荐)
tiff(filename = 'forest_plot.tif', 
   width = 8000, 
   height = 2800, 
   res = 350)

print(p)

dev.off()

⚠️ 常见问题

📚 相关教程