0

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

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
chippycentra
  • 3,396
  • 1
  • 6
  • 24
  • I'm not sure if this would apply to your real data, but an alternative approach could be to combine all the dfs into one and then use ggplot's `facet_grid` instead of `plot-grid`; the variables you facet by would be labelled, see https://ggplot2.tidyverse.org/reference/facet_grid.html – Ottie Sep 07 '22 at 12:22

1 Answers1

0

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
)