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

如何用ggplot的facet_nested移除子标题仅保留分组标题?

移除facet_nested图表中子标题,仅保留分组标题的方法

你使用facet_nested绘制的图表当前显示了分组标题“A”“B”和子标题“n”“y”,要只保留外层分组标题、移除内层子标题,同时保留不同selected_site对应的y轴刻度设置,可按以下方式修改代码:

修改后的完整代码

pdf <- data.frame(xx = as.factor(c(rep(0, 100), rep(1, 100))),
                  value = rnorm(200),
                  selected_site = c('y', rep('n', 98), 'y'),
                  name = as.factor(rep(1:5, each = 20)),
                  version = rep(c('A', 'B'), each = 100))


pdf %>%
  ggplot(aes(x = value, fill = xx)) +
  geom_histogram(alpha=0.6, position="identity") +
  facet_nested(version*selected_site ~ name, scale = 'free') +
  scale_fill_manual(name = '', values = c('red', 'blue')) +
  facetted_pos_scales(
    y = list(selected_site == TRUE ~ scale_y_continuous(limits = c(0,2), guide = "none"),
             selected_site == FALSE ~ scale_y_continuous(limits = c(0,15), guide = "none"))) +
  xlab('') + ylab('') +
  theme_bw() + 
  theme(
    legend.position = 'none',
    # 隐藏内层子标题文本
    strip.text.y.inner = element_blank(),
    # 可选:移除内层子标题的背景框,让布局更简洁
    strip.background.y.inner = element_blank()
  )

关键修改说明

  • 保留facet_nested(version*selected_site ~ name, ...)的结构:确保facetted_pos_scales能继续基于selected_site区分不同的y轴刻度设置
  • strip.text.y.inner = element_blank():隐藏嵌套facet内层(对应selected_site的“n”“y”)的文本标签
  • strip.background.y.inner = element_blank():可选操作,移除内层子标题的背景框,让图表布局更清爽

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 17:12:44