I have a PCA plot and the Proportion of Variance table. When I plot the mentioned table (using tableGrob) above the plot there is a lot of space between them. How can I attached them "closer" and align the table to the upper right side of the PCA plot?
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)
The only changes you need to make to your code are in the grid.arrange()
function.
ncol = 1
with nrow = 2
as.table = TRUE
was addedheights = c(1, 3)
was added (the relative heights of the rows)grid.arrange(propPlot, mainPlot, nrow = 2, as.table = TRUE, heights = c(1, 3))
This is what you will get:
I couldn't have found the solution without this blog post: https://magesblog.com/post/2015-04-14-plotting-tables-alsongside-charts-in-r/