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

ggplot2添加顶部边距文本且不破坏coord_flip()翻转坐标系的方法

在ggplot2 coord_flip()图的顶部边距添加文本的解决方案

要在使用coord_flip()的森林图顶部边距添加文本且不破坏坐标系,最稳定的方法是用annotation_custom()配合grid包的文本对象,完全不受坐标系翻转影响。

完整代码

library(ggplot2)
library(grid)

var1 <- c("ab", "cd")
HR1 <- c(0.51, 0.65)
lower1 <- c(0.4, 0.5)
upper1 <- c(0.6, 0.9)
forest1 <- data.frame(var1, HR1, lower1, upper1)

ggplot(data=forest1, aes(x=var1, y=HR1, ymin=lower1, ymax=upper1)) +
  geom_pointrange() +
  geom_hline(yintercept=1, lty=2) + 
  geom_hline(yintercept=0.4, lty=2) +  
  coord_flip() +  
  labs(x="", y="HR") + 
  ylim(0.3, 1.1) +
  theme_bw() +
  theme(plot.margin = unit(c(4, 1, 1, 1), "lines")) +
  # 添加顶部文本
  annotation_custom(
    grob = textGrob("自定义顶部文本内容", gp = gpar(fontsize=12)),
    xmin = -Inf, xmax = Inf,
    ymin = 1.3, ymax = 1.3
  )

关键说明

  • annotation_custom()直接将文本对象放置在绘图区域外的边距,完全不受coord_flip()的坐标系转换影响。
  • 调整ymin/ymax的数值可以控制文本的上下位置:数值越大,文本越靠上;保持xmin=-Inf和xmax=Inf可让文本横向居中对齐整个图表。
  • 如需多行文本,可用textGrob(paste("第一行", "第二行", sep="\n"))实现换行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 00:27:18