Add additional head and row titles within a ggplot figure (plot_grid)

50 views Asked by At

I have data such as:

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

df1 <- data.frame(x = 1:12, y = (1:12)^2)
df1$grp = c('A', 'B', 'C')

df2 <- data.frame(x = 1:12, y = (1:12)^2)
df2$grp = c('D', 'E')

df3 <- data.frame(x = 1:12, y = (1:12)^2)
df3$grp = c('F', 'G', 'H','I')

df4 <- data.frame(x = 1:12, y = (1:12)^2)
df4$grp = c('J', 'K')

p1 <- ggplot(df1, aes(x, y, color=grp)) + geom_point()
leg1 <- get_legend(p1)
leg1 <- as_ggplot(leg1)
p1 = p1 + theme(legend.position = "none",axis.title.x =element_blank(),axis.title.y =element_blank())

p2 <- ggplot(df2, aes(x, y, color=grp)) + geom_point()
leg2 <- get_legend(p2)
leg2 <- as_ggplot(leg2)
p2 = p2 + theme(legend.position = "none",axis.title.x =element_blank(),axis.title.y =element_blank())

p3 <- ggplot(df3, aes(x, y, color=grp)) + geom_point()
leg3 <- get_legend(p3)
leg3 <- as_ggplot(leg3)
p3 = p3 + theme(legend.position = "none",axis.title.x =element_blank(),axis.title.y =element_blank())

p4 <- ggplot(df4, aes(x, y, color=grp)) + geom_point()
leg4 <- get_legend(p4)
leg4 <- as_ggplot(leg4)
p4 = p4 + theme(legend.position = "none",axis.title.x =element_blank(),axis.title.y =element_blank())

plot_grid(
  p1, p1, p1, leg1, 
  p2, p2, p2, leg2,
  p3, p3, p3, leg3,
  p4, p4, p4, leg4,
  ncol = 4, rel_widths=c(2,2,2,0.5),align = "hv"
)

which gives the following plot:

enter image description here

My question is does someone know how can I add supplemental head titles and row titles within the plot_grid function for example or if it not possible with other ways?

I should for example get something like:
enter image description here

1

There are 1 answers

0
Antreas Stefopoulos On

Not exactly what you need but useable,

replace plot_grid contents with the following,

plot_grid(
  p1, p1, p1, leg1, 
  p2, p2, p2, leg2,
  p3, p3, p3, leg3,
  p4, p4, p4, leg4,
  ncol = 4, rel_widths=c(2,2,2,0.5), align = "hv", 
  labels = c("A1", "A2", "A3","","B1", "B2", "B3","","C1", "C2", "C3","","D1", "D2", "D3",""),
  label_x = 0.2
)