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

如何调整R语言forestplot行间距,统一不同行数森林图高度?

解决forestplot行高不生效及统一多图高度问题

核心问题修正

你之前设置lineheight未生效,是因为参数位置错误——lineheight是forestplot()函数的原生参数,需直接写在该函数内,而非后续样式调整函数中。以下是修改后的完整代码,同时加入了进一步压缩行高、统一多图高度的设置:

library(forestplot)

base_data <- tibble::tibble(mean  = c(0.578, 0.165),
                            lower = c(0.372, 0.018),
                            upper = c(0.898, 1.517),
                            study = c("Auckland", "Block"),
                            deaths_steroid = c("36", "1"),
                            deaths_placebo = c("60", "5"),
                            OR = c("0.58", "0.16"))

base_data |>
  forestplot(labeltext = c(study, deaths_steroid, deaths_placebo, OR),
             clip = c(0.1, 2.5),
             xlog = TRUE,
             # 核心:将行高参数放在forestplot()内生效
             lineheight = unit(8.6, "mm"),
             # 可选:缩小字体进一步压缩行高,保证可读性的前提下优化紧凑度
             txt_gp = fpTxtGp(label = gpar(fontsize = 9))) |>
  fp_set_style(box = "royalblue",
               line = "darkblue",
               summary = "royalblue") |>
  fp_add_header(study = c("", "Study"),
                deaths_steroid = c("Deaths", "(steroid)"),
                deaths_placebo = c("Deaths", "(placebo)"),
                OR = c("", "OR"),
                # 控制表头高度,避免表头占用过多垂直空间
                header_height = unit(10, "mm")) |>
  fp_append_row(mean  = 0.531,
                lower = 0.386,
                upper = 0.731,
                study = "Summary",
                OR = "0.53",
                is.summary = TRUE) |>
  fp_set_zebra_style("#EFEFEF")

统一不同行数森林图的高度

若要让行数不同的森林图输出高度完全一致,可在导出时手动指定图形总高度:

  1. 先确定固定的表头高度(比如上述代码的10mm)和每行高度(8.6mm)
  2. 按公式计算总高度:总高度 = 表头高度 + 行数 × 行高
  3. 在导出函数(如png()/pdf())中指定height参数

示例:

# 导出3行(2研究+1汇总)的图,总高度=10 + 3×8.6=35.8mm
png("forestplot_3rows.png", width = 200, height = 36, units = "mm", res = 300)
# 插入你的森林图代码
dev.off()

# 导出5行的图,总高度=10 + 5×8.6=53mm
png("forestplot_5rows.png", width = 200, height = 53, units = "mm", res = 300)
# 插入对应5行数据的森林图代码
dev.off()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 21:42:46