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

如何在ggplot2的facet_wrap中设置子图y轴标签分置左右

实现facet_wrap子图左右y轴标签分置的方法

可以实现这个需求,以下是两种实用的解决方案:

方案1:使用ggh4x包的facet_wrap2

ggh4x是ggplot2的扩展包,提供了更灵活的分面控制功能,其中facet_wrap2支持为每个分面子图单独设置轴位置:

library(tidyverse)
# 若未安装ggh4x,先执行安装命令
# install.packages("ggh4x")
library(ggh4x)

mtcars %>% 
  mutate(let = rep(LETTERS[1:2], times = nrow(mtcars)/2),
         make = rownames(mtcars)) %>% 
  ggplot(aes(y = make, x = mpg)) + 
  geom_point() +
  # 替换facet_wrap为facet_wrap2,指定y轴位置按分面顺序为左、右
  facet_wrap2(~ let, scales = "free", 
              axis.position = list(y = c("left", "right")))

关键参数是axis.position = list(y = c("left", "right")),它会按照分面的顺序(A在前,B在后)分别设置两个子图的y轴标签位置。

方案2:拆分数据后用patchwork拼接

如果不想额外安装扩展包,可以将数据拆分为两组,分别绘制子图后用patchwork拼接,单独配置每个子图的y轴标签位置:

library(tidyverse)
library(patchwork)

# 预处理数据
df <- mtcars %>% 
  mutate(let = rep(LETTERS[1:2], times = nrow(mtcars)/2),
         make = rownames(mtcars))

# 左侧子图:y轴标签默认在左侧
p1 <- df %>% 
  filter(let == "A") %>% 
  ggplot(aes(y = make, x = mpg)) + 
  geom_point() +
  facet_wrap(~ let, scales = "free")

# 右侧子图:设置y轴标签在右侧,可选隐藏y轴刻度标签避免重复
p2 <- df %>% 
  filter(let == "B") %>% 
  ggplot(aes(y = make, x = mpg)) + 
  geom_point() +
  facet_wrap(~ let, scales = "free") +
  theme(axis.title.y.position = "right",
        axis.text.y = element_blank())

# 横向拼接两个子图
p1 + p2 + plot_layout(ncol = 2)

这里通过theme(axis.title.y.position = "right")直接修改右侧子图的y轴标签位置,隐藏右侧的y轴刻度标签可以让整体布局更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 11:05:12