R ggplot2 patchwork常见轴标签

3
基于以下代码和数据,使用patchwork是否可以有公共图例标签而不必从ggplot代码中删除xlab和ylab?
我之所以问这个问题是因为我有很多ggplots,所以我不认为从每个ggplot中删除xlab和ylab然后使用代码中的方法是理想的。我知道我可以使用ggarrange,但ggpubr比patchwork慢得多。
样本数据和代码:
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")

1
你是指在引用 p1 的地方应该使用 gg1 吗? - Jon Spring
@JonSpring,是的,已修正,谢谢您指出。 - Ed_Gravy
2个回答

5

为了在不移除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))

更新 要添加 y 轴基本上是一样的。为了获取左边 Y 轴标题,我们必须使用 ylab-l。此外,我们还需要在 patch 中添加一个 spacer。在我看来,这种情况下最好的方法是将所有组件放在列表中,并使用 plot_layoutdesign 参数来将它们放置在 patch 中。

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)

好的,那么对于 y-axis 标签,我应该添加 labs(x = "Hp // Cyl"), "xlab-b", y = "Disp", "ylab-b" 吗? - Ed_Gravy
1
比那要多做一点。:) 请看我的更新。 - stefan
你好 Stefan,我的代码似乎不能按照预期工作,该代码和数据与此问题中的相同。我应该编辑我的问题并将代码和数据添加在这里吗? - Ed_Gravy

3
您可以创建一个带有所需标签的空白图,然后使用高宽比的plotlayout()进行组合。
blanklabelplot<-ggplot()+labs(y="your title")+theme_classic()+ 
  guides(x = "none", y = "none")
  
blanklabelplot+plot+ plot_layout(widths=c(1,1000))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接