Search code examples
rpca

Proportion of Variance plot inside a PCA ggplot2


How can I create a Proportion of Variance plot using ggplot2 using the information in dataIris.pca and add it inside the right upper corner of the main ggplot (mainPlot)

library(data.table)
library(MASS)
library(ggplot2)
  
 
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),]

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

Solution

  • You can try this (You have to play with the position):

    library(data.table)
    library(MASS)
    library(ggplot2)
    library(reshape2)
    library(grid)
    
    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),]
    
    mainPlot <- ggplot(dat,aes(x=PC1,y=PC2)) + geom_point(size = 2, aes(color=Species))+
      scale_y_continuous(limits=c(NA,6))
    mainPlot
    
    #Prop variance
    Prop <- as.data.frame(summary(iris.pca)[[6]])
    Propf <- round(Prop[2,],3)
    #Melt
    dfmelt <- melt(Propf)
    #New plot
    plota <- ggplot(dfmelt,aes(x=variable,y=value,label=paste0(100*value,'%')))+
      geom_bar(stat='identity',color='black',fill='orange')+
      geom_text(position=position_dodge(width=0.9), vjust=-0.25,size=2)+
      xlab('PC')+ylab('Var')
    
    mainPlot + annotation_custom(ggplotGrob(plota), xmin = 1.5, xmax = 3.65, ymin = 2.75, ymax = 6)
    

    enter image description here