JohnSal
JohnSal

Reputation: 378

Arrange multiple ggplots using grid.arrange with labels and common.legend

How can I plot two graphs with marking (A and B) and common legend ? I used the ggarrange {ggpubr} and it does not seem to support gridExtra plots.

library(data.table)
library(ggplot2)
library(grid)
library(gridExtra) 
library(ggpubr)

P1 <- ggplot(iris,aes(x=Sepal.Length,y=Petal.Length)) + geom_point(size = 2, aes(color=Species))   
P2 <- ggplot(iris,aes(x=Petal.Width,y=Petal.Length)) + geom_point(size = 2, aes(color=Species))   

#PCA  
iris.pca <- prcomp(iris[,1:4], scale. = TRUE)
dataIris.pca  <- data.frame(summary(iris.pca)$importance) 
dat <- data.table(PC1=iris.pca$x[,1],PC2=iris.pca$x[,2],Species=  iris[,5])
dat <- dat[order(dat$Species),]

#PCA plot
mainPlot <- ggplot(dat,aes(x=PC1,y=PC2)) + geom_point(size = 2, aes(color=Species))   
mainPlot

#Prop variance table
Prop <- as.data.frame(summary(iris.pca)[[6]])
PropTable <- round(Prop[2,],3)

#Prop variance plot
propPlot <- tableGrob(PropTable,theme = ttheme_default(base_size = 8))

P3 <- grid.arrange(propPlot, mainPlot, nrow = 2, as.table = TRUE, heights = c(1, 3))
ggarrange(P1, P2, P3, labels = c("A", "B", "C"),  ncol=3, nrow=1, common.legend = TRUE, legend="bottom")

Upvotes: 0

Views: 4014

Answers (2)

tjebo
tjebo

Reputation: 23747

Another option is the patchwork package

It's a tiny bit hacky because of this table. I combined it directly with patchwork, and that's why it gets its own label.

library(patchwork)
library(ggplot2)
P1 <- 
  ggplot(iris,aes(x=Sepal.Length,y=Petal.Length)) + 
  geom_point(size = 2, aes(color=Species)) 

P2 <- 
  ggplot(iris,aes(x=Petal.Width,y=Petal.Length)) + 
  geom_point(size = 2, aes(color=Species)) 

#PCA  
iris.pca <- prcomp(iris[,1:4], scale. = TRUE)
dataIris.pca  <- data.frame(summary(iris.pca)$importance) 
dat <- data.frame(PC1=iris.pca$x[,1],PC2=iris.pca$x[,2],Species=  iris[,5])
dat <- dat[order(dat$Species),]

#PCA plot
mainPlot <- 
  ggplot(dat,aes(x=PC1,y=PC2)) + 
  geom_point(size = 2, aes(color=Species)) 

#Prop variance table
Prop <- as.data.frame(summary(iris.pca)[[6]])
PropTable <- round(Prop[2,],3)
#Prop variance plot
propPlot <- gridExtra::tableGrob(PropTable, theme = gridExtra::ttheme_default(base_size = 8))


P1 + P2 +  plot_spacer()+ wrap_elements(propPlot)/ mainPlot + plot_spacer()+
  plot_layout(guides = "collect", nrow = 1) +
  plot_annotation(tag_levels = 'A') &
  theme(legend.position = "bottom")

Created on 2020-07-30 by the reprex package (v0.3.0)

Upvotes: 1

Allan Cameron
Allan Cameron

Reputation: 173813

You can use arrangeGrob from gridExtra to draw the final plot.

ggarrange(P1, P2, P3, labels = c("A", "B", "C"),  
          ncol=3, nrow=1, common.legend = TRUE, legend="bottom")
grid.draw(arrangeGrob(P3,layout_matrix = matrix(c(3, 2, 1), nrow = 1)))

enter image description here

Upvotes: 2

Related Questions