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

如何在R语言forestplot包中加宽X轴绘图区域且不丢失刻度值

原始森林图

你当前代码中设置的clip = c(0,5)远大于实际数据的最大上限(仅1.6),大量冗余空白挤占了有效绘图空间,导致红色框标注的低值区间被过度压缩。以下是两种不丢失刻度、放大目标区域的实现方法:

方案1:收紧X轴范围+自定义刻度(最简便)

直接删除X轴冗余空白,同时手动指定所有需要保留的刻度即可:

df %>%
  group_by(group) %>%
  forestplot(title= "test header",
             # 调整clip上限为略大于实际数据最大值即可,删除多余空白
             clip = c(0, 1.7),
             # 手动指定所有需要显示的X轴刻度,确保无遗漏
             xticks = c(0, 0.1, 0.2, 0.3, 0.5, 1, 1.5),
             lty.ci=c(2,3),
             lwd.ci = 1,
             shapes_gp = fpShapesGp(box = c("chocolate1", "aquamarine3") %>% lapply(function(x) gpar(fill = x, col = "#555555")),
                                    default = gpar(vertices = TRUE)),
             ci.vertices = TRUE,
             ci.vertices.height = 0.05,
             boxsize = .1,
             ticks = gpar(fontfamily = "", cex = 5),
             xlab = "mean (95% CI)",
             grid=structure(c(1), gp=gpar(lty=2, lwd=1)))

方案2:分段缩放X轴(适配更高放大需求)

如果方案1的放大效果仍不符合要求,可以自定义分段变换规则,将低值区域按需求放大,高值区域保持正常比例:

# 自定义分段变换:0-0.3区间放大3倍,0.3以上保持线性
trans_func <- function(x) {
  ifelse(x < 0.3, x * 3, 0.9 + (x - 0.3))
}
# 配套逆变换函数,用于匹配原始刻度显示
inv_trans_func <- function(x) {
  ifelse(x < 0.9, x / 3, 0.3 + (x - 0.9))
}

df %>%
  group_by(group) %>%
  forestplot(title= "test header",
             clip = c(0, 1.7),
             xticks = c(0, 0.1, 0.2, 0.3, 0.5, 1, 1.5),
             # 应用自定义变换
             axis.transform = trans_func,
             axis.invtransform = inv_trans_func,
             lty.ci=c(2,3),
             lwd.ci = 1,
             shapes_gp = fpShapesGp(box = c("chocolate1", "aquamarine3") %>% lapply(function(x) gpar(fill = x, col = "#555555")),
                                    default = gpar(vertices = TRUE)),
             ci.vertices = TRUE,
             ci.vertices.height = 0.05,
             boxsize = .1,
             ticks = gpar(fontfamily = "", cex = 5),
             xlab = "mean (95% CI)",
             grid=structure(c(1), gp=gpar(lty=2, lwd=1)))

可通过修改x * 3的系数调整低值区域的放大比例。

内容的提问来源于stack exchange,提问作者Prajwal Mani Pradhan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:36:03