一个ggplot2图中的PCA图和方差比例table - R

PCA plot and Proportion of Variance table in one ggplot2 plot - R

我有 PCA 图和方差比例 table。当我在图上方绘制提到的 table(使用 tableGrob)时,它们之间有很多 space。我怎样才能将它们“靠近”并将 table 对齐到 PCA 图的右上角?

library(data.table)
library(MASS)
library(ggplot2)
library(reshape2)
library(grid)
library(gridExtra) 
   
#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))
 
grid.arrange(propPlot, mainPlot, ncol=1)

您需要对代码进行的唯一更改是在 grid.arrange() 函数中。

  • 我用nrow = 2
  • 替换了ncol = 1 添加了
  • as.table = TRUE
  • 添加了
  • heights = c(1, 3)(行的相对高度)
grid.arrange(propPlot, mainPlot, nrow = 2, as.table = TRUE, heights = c(1, 3))

这就是你将得到的:

没有这个博客我找不到解决方案 post:https://magesblog.com/post/2015-04-14-plotting-tables-alsongside-charts-in-r/