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

如何用forestplot包为森林图列标题添加下划线?

为forestplot森林图的列标题添加下划线

因为gpar()本身没有下划线参数,不过可以通过两种方式实现列标题下划线的需求:

方法1:绘制森林图后手动添加下划线

先完成森林图的绘制,再用grid包的grid.lines()在标题下方绘制横线,精准控制位置:

library(forestplot)
library(grid)

# 绘制基础森林图并保存对象
fp_plot <- base_data |>
  forestplot(labeltext = c(text, results),
             zero = 1,
             col = fpColors(zero = "black"),
             txt_gp = fpTxtGp(label = gpar(fontfamily = "Arial"),
                              ticks = gpar(cex = 1),
                              xlab = gpar(cex = 1),
                              summary = gpar(fontface = "plain")))

# 获取当前绘图视口,用于定位标题位置
current_vp <- current.viewport()

# 示例:为三列标题分别添加下划线
# 可通过grid.locator()点击标题左右边缘获取精准x坐标,这里是示例值
grid.lines(x = c(0.18, 0.28), y = current_vp$yscale[2] - 0.06, gp = gpar(lwd = 1))
grid.lines(x = c(0.48, 0.58), y = current_vp$yscale[2] - 0.06, gp = gpar(lwd = 1))
grid.lines(x = c(0.78, 0.88), y = current_vp$yscale[2] - 0.06, gp = gpar(lwd = 1))

方法2:将标题替换为带下划线的textGrob

直接把列标题行替换为grid::textGrob()对象,利用其underline参数实现下划线:

library(forestplot)
library(grid)

# 为每个列标题创建带下划线的textGrob
title_grobs <- lapply(text[1, ], function(title_txt) {
  textGrob(title_txt, 
           gp = gpar(fontfamily = "Arial", fontface = "plain"),
           underline = TRUE)
})

# 绘制森林图,将标题行替换为自定义grob
base_data |>
  forestplot(labeltext = c(list(title_grobs), results),
             zero = 1,
             col = fpColors(zero = "black"),
             txt_gp = fpTxtGp(label = gpar(fontfamily = "Arial"),
                              ticks = gpar(cex = 1),
                              xlab = gpar(cex = 1),
                              summary = gpar(fontface = "plain")))

注意事项

  • 方法2中需要确保text[1,]是你的列标题行,并且将其包装为列表传入labeltext;
  • 方法1的坐标如果不准确,可以运行grid.locator()后点击绘图区域的对应位置获取精准的x/y值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 02:52:39