R ggplot2拼凑公共轴标签

2024-02-02

根据下面的代码和数据,是否可以拥有通用的图例标签而无需删除xlab and ylab来自ggplot代码使用patchwork?

我之所以问这个问题是因为我有很多ggplots所以我觉得删除它并不理想xlab and ylab从每个ggplots然后使用代码中的方法。我知道我可以使用ggarrange but ggpubrpatchwork.

示例数据和代码:

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")

一种可能的选择是拥有公共轴标题而无需删除xlab and ylab从 ggplot 代码将通过删除轴标签& 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))

UPDATE添加 y 轴基本上是相同的。为了获得左 y 轴标题,我们必须使用ylab-l。此外,我们必须在补丁中添加一个垫片。恕我直言,在这种情况下最好的方法是将所有组件放在列表中并使用design的论证plot_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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

R ggplot2拼凑公共轴标签 的相关文章

随机推荐