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

如何调整R代码为ggforestplot森林图添加左右侧表格信息

问题:调整ggforestplot森林图的显示内容

现有如下R数据框:

df <- data.frame(
  beta = c(0.45, -0.12, 0.33, -0.07, 0.21, 0.65, -0.18, 0.09),
  se = c(0.05, 0.03, 0.04, 0.02, 0.06, 0.07, 0.03, 0.05),
  prs_trait1 = c(
    "Rose Growth Index",
    "Tulip Petal Width",
    "Sunflower Height",
    "Daisy Bloom Count",
    "Orchid Stem Thickness",
    "Lily Leaf Area",
    "Carnation Bud Count",
    "Violet Flower Density"
  ),
  OR_CI_text = c(
    "1.57(1.46-1.70)",
    "0.89(0.84-0.94)",
    "1.39(1.28-1.52)",
    "0.93(0.90-0.96)",
    "1.23(1.15-1.32)",
    "1.92(1.72-2.15)",
    "0.83(0.79-0.87)",
    "1.10(1.02-1.18)"
  ),
  N = c(1200, 950, 1350, 890, 1020, 1600, 800, 1150) # Number of observations
)

原森林图绘制代码:

# Create the forest plot
 ggforestplot::forestplot(
  df = df,
  name = trait,
  estimate = beta,
  se = SE,
  xlab = "Odds ratio (95% CI)",
  title = NULL,
  grid = FALSE
)

需要调整代码,使森林图左侧显示prs_trait1(性状名称)与N(样本量),右侧显示OR_CI_text(OR值及95%CI文本),该如何修改?


解决方案

修改后的代码如下:

# 绘制调整后的森林图
ggforestplot::forestplot(
  df = df,
  name = prs_trait1,  # 指定左侧主列为性状名称
  estimate = beta,
  se = se,  # 修正参数名(数据框中为小写se)
  xlab = "Odds ratio (95% CI)",
  title = NULL,
  grid = FALSE,
  left_columns = c("N"),  # 左侧额外显示样本量列
  left_colnames = c("样本量"),  # 给左侧额外列添加标题(可按需修改)
  right_columns = c("OR_CI_text"),  # 右侧显示OR及CI文本列
  right_colnames = c("OR (95% CI)")  # 给右侧列添加标题(可按需修改)
)

关键改动说明:

  • 修正基础参数:将name = trait改为name = prs_trait1以匹配数据框中的性状名称列,同时把se = SE改为se = se(数据框中是小写的se列)。
  • 左侧添加样本量:通过left_columns参数指定额外显示的N列,并用left_colnames自定义列标题。
  • 右侧添加OR文本:通过right_columns参数指定显示OR_CI_text列,并用right_colnames自定义该列标题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 20:26:14