以拼凑的方式合并两个 y-axes 标题

Merging two y-axes titles in patchwork

关于如何将两个相同的 y-axes 标题“合并”为一个,然后将这个 y-axis 标题放在情节中间的任何想法?我已经通过使用 plot_layout(guides = "collect") 成功地合并了图例,但我似乎找不到任何类似的轴。在这种情况下,我会将名为 disp_disp_disp 的两个轴标题合并为一个。

mtcars

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars) + 
  geom_point(aes(mpg, disp)) + 
  labs(x = "mpg", y = "disp_disp_disp_disp_disp")

p2 <- ggplot(mtcars) + 
  geom_boxplot(aes(gear, disp, group = gear)) + 
  labs(x = "gear", y = "disp_disp_disp_disp_disp")

p3 <- ggplot(mtcars) + 
  geom_point(aes(hp, wt, colour = mpg)) + 
  ggtitle('Plot 3')

p1 / (p2 | p3)

我能想到的唯一方法是在 gtable 级别破解它,但我也很高兴学习更方便的方法。这是 gtable 方法:

library(ggplot2)
library(patchwork)
library(grid)

p1 <- ggplot(mtcars) + 
  geom_point(aes(mpg, disp)) + 
  labs(x = "mpg", y = "disp_disp_disp_disp_disp")

p2 <- ggplot(mtcars) + 
  geom_boxplot(aes(gear, disp, group = gear)) + 
  labs(x = "gear", y = "disp_disp_disp_disp_disp")

p3 <- ggplot(mtcars) + 
  geom_point(aes(hp, wt, colour = mpg)) + 
  ggtitle('Plot 3')

p123 <- p1 / (p2 | p3)

# Convert to gtable
gt <- patchworkGrob(p123)

# Stretching one y-axis title
is_yaxis_title <- which(gt$layout$name == "ylab-l")
# Find new bottom position based on gtable::gtable_show_layout(gt)
gt$layout$b[is_yaxis_title] <- gt$layout$b[is_yaxis_title] + 18

# Deleting other y-axis title in sub-patchwork
is_patchwork <- which(gt$layout$name == "patchwork-table")
pw <- gt$grobs[[is_patchwork]]
pw <- gtable::gtable_filter(pw, "ylab-l", invert = TRUE)

# Set background to transparent
pw$grobs[[which(pw$layout$name == "background")[1]]]$gp$fill <- NA

# Putting sub-patchwork back into main patchwork
gt$grobs[[is_patchwork]] <- pw

# Render
grid.newpage(); grid.draw(gt)

reprex package (v0.3.0)

于 2020-12-14 创建

我想在绘图之前去掉 y 轴标题会稍微容易一些,然后在绘图后重新绘制它:

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars) + 
  geom_point(aes(mpg, disp)) + 
  labs(x = "mpg", y = "disp_disp_disp_disp_disp")

p2 <- ggplot(mtcars) + 
  geom_boxplot(aes(gear, disp, group = gear)) + 
  labs(x = "gear", y = "disp_disp_disp_disp_disp")

p3 <- ggplot(mtcars) + 
  geom_point(aes(hp, wt, colour = mpg)) + 
  ggtitle('Plot 3')

ylab <- p1$labels$y
p1$labels$y <- p2$labels$y <- " "

p1 / (p2 | p3)
grid::grid.draw(grid::textGrob(ylab, x = 0.02, rot = 90))

如果你想完全避免让 grobs 弄脏你的手,另一个选择是指定一个 text-only ggplot 并将其添加为你的轴文本:

p4 <- ggplot(data.frame(l = p1$labels$y, x = 1, y = 1)) +
      geom_text(aes(x, y, label = l), angle = 90) + 
      theme_void() +
      coord_cartesian(clip = "off")

p1$labels$y <- p2$labels$y <- " "

p4 + (p1 / (p2 | p3)) + plot_layout(widths = c(1, 25))

这在调整大小时表现得也更好。