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

R与ggplot2:分面网格(facet grid)的Y轴定制及次坐标轴设置

解决分面图的两个定制需求

1. 单独设置每个分面的Y轴范围

原生ggplot的scales="free_y"只能自动适配数据范围,要手动指定每个子图的Y轴区间,推荐用ggh4x包的facetted_pos_scales函数——它支持给每个分面单独配置坐标轴参数。

2. 给Speed子图添加次Y轴(Split)

同样借助ggh4x的分面轴配置功能,针对speed分面单独添加次Y轴,利用速度与500米用时的转换关系(split = 500 / speed)构建次轴刻度。


完整代码示例:

library(tidyr)
library(ggplot2)
library(ggh4x) # 需先安装:install.packages("ggh4x")

# 数据构建(和原代码一致)
s <- function(d) ifelse(d < 500, "down", "up")
dist <- seq(1,1000)
cadence <- floor(25 + 7 * sin(dist/250))
speed <- 4+sin(dist/250)*2
stream <- s(dist)
df <- data.frame(dist,cadence,speed,stream)
g <- gather(df, variable, value, speed, cadence)

# 绘图并定制分面轴
p <- ggplot(g, aes(dist, value)) +
  geom_line(aes(color=stream, group=1)) + 
  scale_x_continuous(name = "distance [m]") +
  facet_grid(variable ~ ., scales = "free_y") +
  # 单独配置每个分面的Y轴
  facetted_pos_scales(
    y = list(
      # 给cadence分面设置Y轴范围和标签
      variable == "cadence" ~ scale_y_continuous(limits = c(20, 35), name = "cadence [spm]"),
      # 给speed分面设置主Y轴+次Y轴
      variable == "speed" ~ scale_y_continuous(
        limits = c(3.0, 5.5),
        name = "speed [m/s]",
        sec.axis = sec_axis(
          ~ 500/.,
          name = "split [s/500m]",
          breaks = c(90,95,100,105,110,115,120,125,130,140,150)
        )
      )
    )
  )

print(p)

代码说明

  • facetted_pos_scales的y参数接收列表,每个元素通过分面变量条件(如variable == "cadence")匹配对应子图,单独定义轴属性。
  • Speed分面的次Y轴通过sec_axis实现,~500/.对应split = 500 / speed的转换逻辑,同时指定了次轴的标签和刻度断点。
  • 保留facet_grid(..., scales = "free_y")既保证X轴对齐,又允许Y轴独立定制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 23:22:15