Home > Enterprise >  R ggplot2 patchwork common axis labels
R ggplot2 patchwork common axis labels

Time:07-20

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?

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. I know I can use ggarrange but ggpubr is much slower than patchwork.

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

CodePudding user response:

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:

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

  • Related