首页 > 解决方案 > 使用带有标签和 common.legend 的 grid.arrange 排列多个 ggplots

问题描述

如何绘制带有标记(A 和 B)和常见图例的两个图形?我使用了 ggarrange {ggpubr},它似乎不支持 gridExtra 图。

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")

标签: rggplot2

解决方案


您可以使用arrangeGrobfromgridExtra绘制最终图。

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)))

在此处输入图像描述


推荐阅读