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

ggplot嵌套分面(facet_wrap2-ggh4x):自由y轴下移除内层y轴标签

解决嵌套分面中仅保留指定分组y轴标签的问题

问题背景

我有一个带嵌套结构的数据集:包含3个试验,每个试验下分2组,组内对应相同项目(部分项目会随试验调整,但组间一致)。使用ggplot2结合ggh4x的facet_wrap2制作嵌套分面图展示通过率时,设置scales="free_y"后,remove_labels="all"无法按预期仅保留外层边缘的y轴标签。我希望只保留group A的y轴标签,移除group B的冗余标签。

数据集代码

set.seed(32123)
test <- tibble(
  trial  = rep(c("Trial_A", "Trial_B", "Trial_C"), each = 3, times = 8),
  group  = rep(c("A", "B"), each = 36),
  result = rep(c("Fail", "Pass"), times = 36),
  item   = rep(c("item 1", "item 2", "item 3", "item 4"), each = 6, times = 3),
  tries  = round(runif(n = 72, min = 0, max = 20))) %>%
  mutate(item = case_when(item == "item 4" & group == "B" & trial == "Trial_C" ~ "item 3",
                          item == "item 3" & group == "B" & trial == "Trial_C" ~ "item 2",
                          item == "item 3" & group == "B" & trial == "Trial_A" ~ "item 2",
                          item == "item 2" & group == "B" & trial == "Trial_A" ~ "item 1",
                          TRUE ~ item))

原始绘图代码

test %>% 
  ggplot(aes(x = item, y = tries, fill = result)) +
  geom_bar(position = "fill", stat = "identity") +
  ggh4x::facet_wrap2(dplyr::vars(trial, group),
                     strip = strip_nested(bleed = FALSE),
                     scales = "free_y", nrow = 3, axes = "margins",
                     remove_labels = "all") +
  coord_flip() +
  theme(axis.title.x = element_blank())

解决方案

使用ggh4x的panel_match()函数在主题中条件控制轴元素的可见性,仅让group == "A"的面板保留y轴标签:

test %>% 
  ggplot(aes(x = item, y = tries, fill = result)) +
  geom_bar(position = "fill", stat = "identity") +
  ggh4x::facet_wrap2(dplyr::vars(trial, group),
                     strip = strip_nested(bleed = FALSE),
                     scales = "free_y", nrow = 3, axes = "margins") +
  coord_flip() +
  theme(
    axis.title.x = element_blank(),
    # 仅group为A的面板显示y轴标签
    axis.text.y = element_text(condition = ggh4x::panel_match(group == "A")),
    # 可选:同步移除group为B的面板的y轴刻度线
    axis.ticks.y = element_line(condition = ggh4x::panel_match(group == "A"))
  )

原理说明

panel_match()函数可以基于分面变量的条件来控制主题元素的显示状态,在scales="free_y"的场景下,它能精准识别指定分组的面板,绕过remove_labels参数的限制,实现仅保留目标分组y轴标签的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 00:06:18