Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put row and column titles using grid.arrange in R

The data for the ggplots:

set.seed(0)

library(ggplot2)
library(gridExtra)

c <- list()

for (k in 1:9) c[[k]] <- ggplot(data.frame(x=1:10,y=rnorm(10)),aes(x=x,y=y))+geom_line()

grid.arrange (c[[1]],c[[2]],c[[3]],c[[4]],c[[5]]
,c[[6]],c[[7]],c[[8]],c[[9]],ncol=3, nrow=3, widths = c(4,4,4) ,heights = c(4,4,4))

I want titles for each row and each column.

The shape of the output would be something like this:

          CTitle 1 CTitle 2 CTitle 3
RTitle1   plot1     plot2   plot3
RTitle2   plot4     plot5   plot6
RTitle3   plot7     plot8   plot9
like image 368
Leonhardt Guass Avatar asked Nov 03 '25 04:11

Leonhardt Guass


1 Answers

You can use nested arrangeGrob calls for each column/row, setting the top and left argument. Something like this:

grid.arrange (arrangeGrob(c[[1]], top="CTitle1", left="RTitle1"),arrangeGrob(c[[2]],top="CTitle2"),arrangeGro‌​b(c[[3]],top="CTittl‌​e3"),arrangeGrob(c[[‌​4]], left="RTitle2"),c[[5]],c[[6]],arrangeGrob(c[[7]],left="RTitl‌​e3"),c[[8]],c[[9]],n‌​col=3, nrow=3, widths = c(4,4,4) ,heights = c(4,4,4))

Below is a code to streamline the process thanks to @eipi10

# Create list of plots
set.seed(0)
pl = lapply(1:9, function(i) {
  p = ggplot(data.frame(x=1:10,y=rnorm(10)),aes(x, y)) + 
              geom_line()
})

# Create row and column titles
col.titles = paste("C_Title", 1:3)
row.titles = paste("R_Title", 4:6)

# Add row titles
pl[1:3] = lapply(1:3, function(i) arrangeGrob(pl[[i]], left=row.titles[i]))

# Add column titles and lay out plots
grid.arrange(grobs=lapply(c(1,4,7), function(i) {
  arrangeGrob(grobs=pl[i:(i+2)], top=col.titles[i/3 + 1], ncol=1)
}), ncol=3)
like image 61
S Rivero Avatar answered Nov 04 '25 20:11

S Rivero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!