在分面外的 ggplot 中注释森林图

Annotating a forest plot in ggplot outside of the facets

提问人:krtbris 提问时间:11/17/2023 更新时间:11/17/2023 访问量:17

问:

我正在使用 R 中的 ggplot2 生成一个森林图,并希望在图的顶部添加一个标签以指示风险比的影响方向。但是,当我这样做时,它会将标签添加到每个方面,而不仅仅是绘图的顶部。我也尝试过使用,但这需要坐标而不是我不想要的 x 轴值,因为我正在生成此图的数十个版本,并且无论图上的内容如何,每次都需要标签保持一致。draw_plot_label

library(ggplot2)

# Sample data
final_cox_dat <- data.frame(
  comparator = rep(c("Group A", "Group B", "Group C"), each = 2),
  estimate = c(1.2, 1.5, 0.8, 0.9, 1.4, 1.7),
  conf.low = c(1.0, 1.3, 0.7, 0.8, 1.3, 1.5),
  conf.high = c(1.5, 1.7, 0.9, 1.0, 1.6, 1.9),
  model = rep(c("Weighted", "Unweighted"), times = 3)
)

# Create a forest plot using ggplot2 
forest_plot <-
  ggplot(
    final_cox_dat,
    aes(
      x = estimate, y = comparator,
      xmin = conf.low, xmax = conf.high, 
      color = model
    )
  ) +
  geom_pointrange(position = position_dodge(width = 0.8)) +
  geom_vline(xintercept = 1, linetype = "dashed") +
  facet_wrap(~comparator, ncol = 1, scales = "free_y") +
  labs(
    title = NULL,
    x = "Hazard Ratio (95% CI)",
    y = NULL
  ) +
  theme_minimal() +
  theme(
    strip.text = element_blank(), # Hide both x and y-axis labels in facet
    legend.title = element_blank(),
    legend.position = "bottom",
    axis.title.y = element_blank(),
    axis.ticks.y = element_blank()
  ) +
  scale_color_manual(
    values = c("Unweighted" = "red", "Weighted" = "blue")
  ) +
  geom_text(
    aes(
      x = max(conf.high) + 0.05,
      group = model,
      label = sprintf(
        "%0.2f (%0.2f, %0.2f)",
        estimate, conf.low, conf.high
      )
    ),
    hjust = 0, vjust = 0.5, size = 4.5, color = "black",
    position = position_dodge(width = 0.8)
  ) +
  scale_x_continuous(breaks = seq(0, max(final_cox_dat$conf.high + 0.2), by = 0.2), expand = expansion(mult = 0.1)) +
  theme(text = element_text(size = 18))  +
  guides(color = guide_legend(reverse=TRUE))

# Annotate plot with direction of hazard ratio 

forest_plot <-  forest_plot + annotate("text", x = 1, y = Inf, label = "Favours Drug", vjust = 1, hjust = 1.5, color = "black", size = 6) +
  annotate("text", x = 1, y = Inf, label = "Favours comparator", vjust = 1, hjust = -0.5, color = "black", size = 6) 

enter image description here

r ggplot2

评论


答:

1赞 stefan 11/17/2023 #1

问题是注释不知道你的方面。相反,你可以使用 which 通过参数允许指定要添加注释的 facet:geom_textdata=

library(ggplot2)

forest_plot +
  geom_text(
    data = data.frame(
      x = c(.9, 1.1), y = Inf, comparator = "Group A",
      label = c("Favours Drug", "Favours comparator"),
      hjust = c(1, 0)
    ),
    aes(x = x, y = y, label = label, hjust = hjust),
    vjust = 1, color = "black", size = 6,
    inherit.aes = FALSE
  )

enter image description here

评论

0赞 krtbris 11/17/2023
谢谢@stefan。这需要显式调用“A 组”——有没有办法在不显式调用比较器名称的情况下做到这一点?我正在完全不同的比较器范围内迭代此代码。
0赞 stefan 11/17/2023
尝试使用 .这应该选择比较器列的“第一”组。comparator = sort(unique(final_cox_dat$comparator))[[1]]
0赞 krtbris 11/17/2023
大喊大叫,谢谢