简体   繁体   English

R ggplot2 拼凑通用轴标签

[英]R ggplot2 patchwork common axis labels

Based on the code and data below, is it possible to have common legend labels without having to remove xlab and ylab from the ggplot codes using patchwork ?根据下面的代码和数据,是否可以使用patchworkggplot代码中删除xlabylab而不必使用通用图例标签?

The reason why I ask this is because I have lots of ggplots and so I don't find it ideal to remove xlab and ylab from each of the ggplots and then use the method in the code.我问这个的原因是因为我有很多ggplots ,所以我觉得从每个ggplots中删除xlabylab然后在代码中使用该方法并不理想。 I know I can use ggarrange but ggpubr is much slower than patchwork .我知道我可以使用ggarrangeggpubrpatchwork慢得多。

Sample data and code:示例数据和代码:

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

One possible option to have a common axis title without having to remove xlab and ylab from the ggplot code would be to remove the axis labels via & labs(...) when creating the patch and adding a common axis title as a separate plot where I made use of cowplot::get_plot_component to create the axis title plot:无需从 ggplot 代码中删除xlabylab即可拥有公共轴标题的一种可能选择是在创建补丁时通过& labs(...)删除轴标签,并将公共轴标题添加为单独的图,其中我利用cowplot::get_plot_component创建轴标题图:

library(ggplot2)
library(patchwork)
library(cowplet)


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

You could also just make a blank plot with the label you need, then use plotlayout() with a high width ratio to combine.你也可以只用你需要的label做一个空白的plot,然后使用高宽比的plotlayout()来组合。

blanklabelplot<-ggplot()+labs(y="your title")+theme_classic()+ 
  guides(x = "none", y = "none")
  
blanklabelplot+plot+ plot_layout(widths=c(1,1000))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM