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

R ggplot2如何将分面标签置于Y轴标题左侧

R语言ggplot2分面箱线图调整Y轴标题与左侧分面标签顺序的解决方案

需求背景

使用R语言ggplot2绘制分面箱线图时,需要将左侧切换显示的分面标签放在最左侧,Y轴标题置于分面标签的右侧,保证和其余两张图拼接时布局统一。当前已可以设置合适的间距,但无法调换二者的排列顺序。

原有实现代码

library(ggplot2)
library(tibble)
tg <- ToothGrowth %>%
  as_tibble()

tg %>%
  ggplot(aes(supp, len)) +
  geom_boxplot(aes(fill = supp)) +
  theme(strip.placement = "outside",
        strip.switch.pad.grid = unit(1, "cm")) +
  facet_grid(dose ~ ., switch = "y")

初始效果

初始效果图

最优实现方案

通过调整Y轴标题的vjust参数即可实现布局调整,代码如下:

tg %>%
  ggplot(aes(supp, len)) +
  geom_boxplot(aes(fill = supp)) +
  facet_grid(dose ~ ., switch = "y") +
  theme(strip.placement = "outside",
        strip.switch.pad.grid = unit(1, "cm"),
        axis.title.y = element_text(vjust = -15))

最终效果

最终效果图

其他可选方案说明

  • 使用grid包的方案可以达到预期效果,但后续操作较为复杂
  • 使用假轴的方案会改变X轴刻度标签的间距,且label =参数不接受表达式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 03:06:04