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

使用ggplot2复刻学术期刊图:截断轴、短副轴及跨分面垂直线

用ggplot2复刻学术期刊图的解决方案

1. 实现0//截断式轴刻度

guide_axis_truncated() 可直接实现该效果,核心通过 trunc_label 指定截断标记,配合 trunc_lower/trunc_upper 限定截断范围。示例代码:

library(ggplot2)

# 构造示例数据
set.seed(123)
data <- data.frame(
  x = c(0, 20, 40, 60, 80),
  y = rnorm(5),
  group = rep(c("A", "B"), each = 5)[1:5]
)

ggplot(data, aes(x, y)) +
  geom_point() +
  scale_x_continuous(
    breaks = c(0, 20, 40, 60, 80),
    guide = guide_axis_truncated(
      trunc_lower = 0,  # 从0位置开始截断
      trunc_label = "0//"  # 替换0刻度的标记
    )
  )

该代码会将x轴最左侧的0刻度替换为0//,其余刻度保持原样,满足截断式显示要求。

2. 分面右侧部分延伸的副轴

可结合 sec_axis() 和 guide_axis_truncated() 实现分面右侧的局部副轴,需为副轴设置截断范围,使其仅显示指定区间,同时配合分面的刻度自由设置:

ggplot(data, aes(x, y)) +
  geom_point() +
  facet_wrap(~group, scales = "free_x") +
  scale_x_continuous(
    breaks = c(0, 20, 40, 60, 80),
    guide = guide_axis_truncated(trunc_lower = 0, trunc_label = "0//"),
    # 定义副轴,仅显示20-60区间
    sec.axis = sec_axis(
      ~.,
      breaks = c(20, 40, 60),
      guide = guide_axis_truncated(trunc_lower = 20, trunc_upper = 60)
    )
  )

若不同分面的副轴截断范围不同,可通过自定义函数或分面数据预处理适配每个分面的刻度区间。

3. 对齐轴与跨分面垂直虚线

推荐使用 ggh4x 包的增强分面功能实现轴对齐,同时通过 geom_vline() 配合全局参数添加跨分面的垂直虚线:

library(ggh4x)

ggplot(data, aes(x, y)) +
  geom_point() +
  # 用facet_wrap2实现全部分面轴对齐
  facet_wrap2(~group, align = "all", axes = "all") +
  # 添加跨分面的垂直虚线,inherit.aes=FALSE避免继承分组映射
  geom_vline(xintercept = 40, linetype = "dashed", color = "gray50", inherit.aes = FALSE) +
  scale_x_continuous(
    breaks = c(0, 20, 40, 60, 80),
    guide = guide_axis_truncated(trunc_lower = 0, trunc_label = "0//")
  )

facet_wrap2() 的 align = "all" 参数确保所有分面的轴完全对齐,geom_vline() 配合 inherit.aes=FALSE 可让虚线跨越所有分面显示,无需依赖过时的ggplotGrob拼接方法。

内容的提问来源于stack exchange,提问作者a.hesse

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 15:31:58