R/plotPCA.R
a7648e0a
 #' Plot PCA run data from its components.
f4d70b88
 #' @param colorBy The variable to color clusters by
 #' @param shape Shape of the points
 #' @param pcX User choice for the first principal component
8d72aa93
 #' @param pcY User choice for the second principal component
 #' @param runPCA Run PCA if the reducedDimName does not exist. the Default is
7827e2ef
 #' FALSE.
3fcae1c4
 #' @param inSCE Input \linkS4class{SingleCellExperiment} object.
a7648e0a
 #' @param useAssay Indicate which assay to use. The default is "logcounts".
 #' @param reducedDimName a name to store the results of the dimension reduction
 #' coordinates obtained from this method. This is stored in the SingleCellExperiment
 #' object in the reducedDims slot. Required.
7eb21ec0
 #'
a7648e0a
 #' @return A PCA plot
0be6f650
 #'
40c2c313
 #' @export
443bc2c7
 #' @examples
c32ed94f
 #' data("mouseBrainSubsetSCE")
 #' plotPCA(mouseBrainSubsetSCE, colorBy = "level1class",
443bc2c7
 #'         reducedDimName = "PCA_counts")
976db869
 plotPCA <- function(inSCE, colorBy=NULL, shape=NULL, pcX="PC1",
7827e2ef
                     pcY="PC2", reducedDimName="PCA", runPCA=FALSE,
c32ed94f
                     useAssay="logcounts"){
c07f40fe
   if(!(reducedDimName %in% names(SingleCellExperiment::reducedDims(inSCE)))){
7827e2ef
     if (runPCA){
e41fdba4
       inSCE <- scaterPCA(inSCE, useAssay = useAssay,
0be6f650
                       reducedDimName = reducedDimName)
7827e2ef
     } else {
c32ed94f
       stop(reducedDimName,
e41fdba4
            " dimension not found. Run scaterPCA() or set runPCA to TRUE.")
7827e2ef
     }
f4d70b88
   }
0be6f650
   pcaDf <- data.frame(SingleCellExperiment::reducedDim(inSCE,
c32ed94f
                                                        reducedDimName))
   if (!(pcX %in% colnames(pcaDf))){
ac2ad89f
     stop("pcX dimension ", pcX, " is not in the reducedDim data")
   }
c32ed94f
   if (!(pcY %in% colnames(pcaDf))){
ac2ad89f
     stop("pcY dimension ", pcY, " is not in the reducedDim data")
   }
40c2c313
 
976db869
 
3fcae1c4
   # Need to add back in variances in the plot axis labels
   pcXlab <- pcX
   pcYlab <- pcY
ac2ad89f
 
40a61489
   if (!is.null(colorBy)){
0be6f650
     pcaDf$color <- SingleCellExperiment::colData(inSCE)[, colorBy]
f4d70b88
   }
40a61489
   if (!is.null(shape)){
0be6f650
     pcaDf$shape <- factor(SingleCellExperiment::colData(inSCE)[, shape])
f4d70b88
   }
0be6f650
   pcaDf$Sample <- colnames(inSCE)
c32ed94f
   g <- ggplot2::ggplot(pcaDf, ggplot2::aes_string(pcX, pcY, label = "Sample")) +
dc61b914
     ggplot2::geom_point() +
ac2ad89f
     ggplot2::labs(x = pcXlab, y = pcYlab)
40a61489
   if (!is.null(colorBy)){
dc61b914
     g <- g + ggplot2::aes_string(color = "color") +
       ggplot2::labs(color = colorBy)
f4d70b88
   }
40a61489
   if (!is.null(shape)){
dc61b914
     g <- g + ggplot2::aes_string(shape = "shape") +
       ggplot2::labs(shape = shape)
f4d70b88
   }
   return(g)
 }