0

I have created a plot with many elements using ggplot and plot_layout. I want to add common x and y axes. I would like to use textGrob to keep a common look with other plots I created this way.

MWE

library(patchwork)   
library(ggplot2)
library(grid)
library(gridExtra)

p1 <- ggplot(mtcars) + 
  geom_point(aes(mpg, disp, color = mpg)) + 
  ggtitle('Plot 1')

p2 <- ggplot(mtcars) + 
  geom_boxplot(aes(gear, disp, group = gear)) + 
  ggtitle('Plot 2')

p3 <- ggplot(mtcars) + 
  geom_point(aes(hp, wt, colour = mpg)) + 
  ggtitle('Plot 3')

design <- "
1111
223#
"

myplt <- (p1 + p2 + p3 +  plot_layout(design=design, guides = "collect")  &
  theme(legend.position = 'right',
        legend.direction = 'vertical'))

y.grob <- textGrob("My Y label", 
                   gp=gpar(fontface="bold", fontsize=15), rot=90)

x.grob <- textGrob("My X label", 
                   gp=gpar(fontface="bold",  fontsize=15))

grid.arrange(arrangeGrob(myplt, left = y.grob, bottom = x.grob)) 

The above worked well for plots I arranged using plot_grid (i.e. adding the common labels). However, with the above I get either a blank plot with the correct labels, or with the MWE above the correct labels but only with Plot 3.

I also tried adding on

myplt
grid::grid.draw(grid::textGrob(y.grob))
grid::grid.draw(grid::textGrob(x.grob))

because of this answer, but that just put text[GRID text 26826] in the middle of my plot.

I did manage to get their other idea working, but the spacing was horrible and I couldn't get the font details to match what I have for other plots, so would prefer to find a solution using the textGrobs already created.

EDIT: The design had an extra row that was blank that I removed

Esme_
  • 1,360
  • 3
  • 18
  • 30
  • 1
    Maybe **{cowplot}** can help. It has helper functions (https://wilkelab.org/cowplot/reference/index.html#section-get-methods) to get and reuse plot elements, i.a. `get_x_axis()`. –  May 25 '22 at 06:13
  • Try `grid.arrange(arrangeGrob(patchworkGrob(myplt), left = y.grob, bottom = x.grob))`. – stefan May 25 '22 at 06:29
  • @stefan that works, if you post as an answer I will accept. – Esme_ May 25 '22 at 06:34

1 Answers1

1

To make grid.arrange work with a patch you have to convert it to a grob first using patchwork::patchworkGrob. Additionally there is no need for grid.arrange(arrangeGrob(...)). Just use grid.arrange:

grid.arrange(patchworkGrob(myplt), left = y.grob, bottom = x.grob)

stefan
  • 90,330
  • 6
  • 25
  • 51