R ggplot2拼凑公共轴标签

Ed_*_*avy 5 r ggplot2 patchwork

根据下面的代码和数据,是否可以拥有通用的图例标签,而不必使用来从代码中删除xlab和?ylabggplotpatchwork

我之所以问这个问题,是因为我有很多,所以我觉得从每个中删除和然后在代码中使用该方法ggplots并不理想。我知道我可以使用但比 慢得多。xlabylabggplotsggarrangeggpubrpatchwork

示例数据和代码:

library(tidyverse)
library(patchwork)
library(gridextra)

gg1 = ggplot(mtcars) +
  aes(x = cyl, y = disp) +
  geom_point() +
  xlab("Disp") +
  ylab("Hp // Cyl") +
  theme(axis.title = element_blank())

gg2 = gg1 %+% aes(x = hp) +
  xlab("Disp") +
  ylab("Hp // Cyl")

# This method still keeps the individual axis labels.
p = gg1 + gg2
gt = patchwork::patchworkGrob(p)
gridExtra::grid.arrange(gt, left = "Disp", bottom = "Hp // Cyl")
Run Code Online (Sandbox Code Playgroud)

ste*_*fan 6

更新

现在patchwork >= 1.2.0可以使用 的新axis_title=参数来收集轴标题plot_layout(),即类似于guides="collect"现在可以设置axis_title="collect"添加共享轴标题。

library(ggplot2)
library(patchwork)

packageVersion("patchwork")
#> [1] '1.2.0'

gg1 <- ggplot(mtcars) +
  aes(x = cyl, y = disp) +
  geom_point() +
  xlab("Disp") +
  ylab("Hp // Cyl")

gg2 <- gg1 %+% aes(x = hp) +
  xlab("Disp") +
  ylab("Hp // Cyl")

gg1 + gg2 +
  plot_layout(axis_titles = "collect")
Run Code Online (Sandbox Code Playgroud)

原答案

无需从 ggplot 代码中删除即可拥有公共轴标题的一种可能选择xlabylab& labs(...)创建补丁时删除轴标签,并添加公共轴标题作为单独的图,我用它cowplot::get_plot_component来创建轴标题阴谋:

library(ggplot2)
library(patchwork)
library(cowplot)


gg1 <- ggplot(mtcars) +
  aes(x = cyl, y = disp) +
  geom_point() +
  xlab("Disp") +
  ylab("Hp // Cyl") +
  theme(axis.title = element_blank())

gg2 <- gg1 %+% aes(x = hp) +
  xlab("Disp") +
  ylab("Hp // Cyl")

gg_axis <- cowplot::get_plot_component(ggplot() +
  labs(x = "Hp // Cyl"), "xlab-b")

(gg1 + gg2 & labs(x = NULL, y = NULL)) / gg_axis + plot_layout(heights = c(40, 1))
Run Code Online (Sandbox Code Playgroud)

更新要添加 y 轴,它基本上是相同的。要获得左侧 y 轴标题,我们必须使用ylab-l. 此外,我们必须在补丁中添加一个垫片。恕我直言,在这种情况下,最好的方法是将所有组件放入列表中,并使用 参数designplot_layout它们放入补丁中。

p <- ggplot() + labs(x = "Hp // Cyl", y = "Disp")
x_axis <- cowplot::get_plot_component(p, "xlab-b")
y_axis <- cowplot::get_plot_component(p, "ylab-l")

design = "
DAB
#CC
"

list(
  gg1 + labs(x = NULL, y = NULL), # A
  gg2 + labs(x = NULL, y = NULL), # B
  x_axis,# C
  y_axis # D
) |> 
  wrap_plots() + 
  plot_layout(heights = c(40, 1), widths = c(1, 50, 50), design = design)
Run Code Online (Sandbox Code Playgroud)