Dekike
Dekike

Reputation: 1294

How to create a common title in X and Y axis in an arrange of plots using `ggdraw` and `plot_grid()` in R?

I have an arrange of plots for which I would like to create a common X-axe title and a common Y-axe title. As an example:

library(ggplot2)
library(cowplot)
library(ggpubr)z
theme_set(theme_cowplot())

df <- data.frame(x = 1:12, y = (1:12)^2)
df$grp = c('Some', 'Things', 'In a legend')

p <- ggplot(df, aes(x, y, color=grp)) + geom_point()
leg <- get_legend(p)
leg <- as_ggplot(leg)
p = p + theme(legend.position = "none")

plot_grid(
  p, p, leg, 
  p, p, leg,
  ncol = 3, rel_widths=c(2,2,1)
)

enter image description here

After some reading, I found as an option the use of ggdraw. However, I don't know how it works well, and I don't figure out how to get what I want (one Y in the y-axis and one X in the x-axis). Below is what I tried:

df <- data.frame(x = 1:12, y = (1:12)^2)
df$grp = c('Some', 'Things', 'In a legend')

p <- ggplot(df, aes(x, y, color=grp)) + geom_point()
leg <- get_legend(p)
leg <- as_ggplot(leg)
p = p + theme(legend.position = "none",axis.title.x =element_blank(),axis.title.y =element_blank()) # I remove x and y titles for the plots

P <-plot_grid(
  p, p, leg, 
  p, p, leg,
  ncol = 3, rel_widths=c(2,2,1)
)
P
P1 <- ggdraw(add_sub(P , "X", vpadding=grid::unit(0.8,"lines"), # With `0.8` I add some space in the X margin.
y=2, x=1, vjust=1, # With `y` and `x` I can indicate the coordinates for my desired text
angle=0) # With this I can change the orientation of the text
)
P1 

enter image description here

Does anyone know how to create a common x and y-axis using ggdraw or with another function?

Upvotes: 1

Views: 3692

Answers (2)

Yang Zhong
Yang Zhong

Reputation: 21

    Ylab<-ggplot()+
    geom_text(aes(x=0,y=0),label="Ylab",size=5,angle=90)+
    theme_void()

    legend<-get_legend(p)

    fig<-plot_grid(p,p,p,p,nrow=2)

    plot_grid(Ylab,fig,legend,nrow=1,rel_widths = c(0.02,1, 0.1))

You can plot the ylab separately as with geom_text.

Upvotes: 2

Allan Cameron
Allan Cameron

Reputation: 174468

I think you just need to play around with the margins before add_sub:

P <-plot_grid(
 p, p, leg, 
 p, p, leg,
 ncol = 3, rel_widths=c(2,2,1)
) + theme(plot.margin = margin(30, 30, -50, 50))

P <- add_sub(P, "x axis text", hjust = 1)
P <- add_sub(P, "y axis text", -0.05, 5, angle = 90)
ggdraw(P)

enter image description here

Upvotes: 4

Related Questions