R/plotUMAP.R
9efd0344
 #' Plot UMAP results either on already run results or run first and then plot.
 #'
3fcae1c4
 #' @param inSCE Input \linkS4class{SingleCellExperiment} object with saved
 #' dimension reduction components. Required
9efd0344
 #' @param colorBy color by a condition(any column of the annotation data).
 #' @param shape add shapes to each condition.
3fcae1c4
 #' @param reducedDimName saved dimension reduction name in the
 #' \linkS4class{SingleCellExperiment} object. Required.
9efd0344
 #' @param runUMAP If the dimension reduction components are already available
 #' set this to FALSE, otherwise set to TRUE. Default is False.
 #' @param useAssay Indicate which assay to use. The default is "logcounts"
 #'
 #' @return a UMAP plot of the reduced dimensions.
 #' @export
 #'
 #' @examples
bc6984ea
 #' data(scExample, package = "singleCellTK")
c06bc73b
 #' sce <- subsetSCECols(sce, colData = "type != 'EmptyDroplet'")
c35af4eb
 #' sce <- runQuickUMAP(sce)
f0b0d74b
 #' plotUMAP(sce)
976db869
 plotUMAP <- function(inSCE, colorBy = NULL, shape = NULL,
9efd0344
                      reducedDimName = "UMAP", runUMAP = FALSE,
c35af4eb
                      useAssay = "counts"){
c07f40fe
   if(!(reducedDimName %in% names(SingleCellExperiment::reducedDims(inSCE)))){
9efd0344
     if (runUMAP){
c35af4eb
       inSCE <- runQuickUMAP(inSCE, useAssay = useAssay,
                             reducedDimName = reducedDimName)
9efd0344
     } else {
       stop(reducedDimName,
27e3c620
            " dimension not found. Run `runUMAP()` or set `runUMAP` to `TRUE`.")
9efd0344
     }
   }
   UMAPDf <- data.frame(SingleCellExperiment::reducedDim(inSCE,
                                                         reducedDimName))
   if (ncol(UMAPDf) > 2){
     warning("More than two UMAP dimensions. Using the first two.")
   }
c3583178
   colnames(UMAPDf)[1] <- "UMAP1"
   colnames(UMAPDf)[2] <- "UMAP2"
9efd0344
   xdim <- colnames(UMAPDf)[1]
   ydim <- colnames(UMAPDf)[2]
976db869
 
9efd0344
   if (!is.null(colorBy)){
     UMAPDf$color <- SingleCellExperiment::colData(inSCE)[, colorBy]
   }
   if (!is.null(shape)){
     UMAPDf$shape <- factor(SingleCellExperiment::colData(inSCE)[, shape])
   }
   UMAPDf$Sample <- colnames(inSCE)
   g <- ggplot2::ggplot(UMAPDf, ggplot2::aes_string(xdim, ydim,
                                                    label = "Sample")) +
     ggplot2::geom_point()
   if (!is.null(colorBy)){
     g <- g + ggplot2::aes_string(color = "color") +
       ggplot2::labs(color = colorBy)
   }
   if (!is.null(shape)){
     g <- g + ggplot2::aes_string(shape = "shape") +
       ggplot2::labs(shape = shape)
   }
   return(g)
 }