根据下面的代码和数据,是否可以使用通用的图例标签而不必使用xlab从ggplot代码中删除patchwork和patchwork
我问这个问题的原因是因为我有很多ggplots,所以我不认为从每个ggplots中删除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")发布于 2022-07-19 20:40:24
有一个可能的选择是在创建补丁时通过xlab和ylab通过& 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。此外,我们还必须在补丁中添加一个间隔。在这种情况下,最好的方法是将所有组件放在一个列表中,并使用plot_layout的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)https://stackoverflow.com/questions/73042802
复制相似问题