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
CodePudding user response:
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)