R/ArchR_ClustRes.R

Defines functions ArchR_ClustRes

Documented in ArchR_ClustRes

#' ArchR function: Plot multiple cluster resolutions
#'
#' This function plots UMAPs for a series of nine cluster resolutions, alongside a clustree which reveals the relationship between clusters at different resolutions
#'
#' @param ArchR ArchR object
#' @param by value by which resolution is incremented
#' @param starting_res lowest resolution to cluster cells by
#' @return plot generated by grid extra
#' @export
ArchR_ClustRes <- function(ArchR, by = 0.1, starting_res = 0){
  plots <- list()
  resolutions <- c(seq(starting_res, starting_res+9*by, by=by))
  cluster_df <- data.frame(ArchR$cellNames)
  
  if(length(ArchR@reducedDims) == 0){stop("Carry out dimensionality reduction before clustering")}
  
  for(res in resolutions[2:length(resolutions)]){
    ArchR_clustered <- addClusters(input = ArchR, name = "clusters", force = TRUE, resolution = res)
    plots[[paste(res)]] <- plotEmbedding(ArchR_clustered, name = "clusters") +
      ggtitle(paste("resolution = ", res))
    title <- paste0("clustering_res_", res)
    cluster_df <- cluster_df %>% mutate(!!title := ArchR_clustered@cellColData$clusters)
  }
  
  plots[["clustree"]] <- clustree(cluster_df, prefix = "clustering_res_")
  lay <- rbind(c(1,1,1,2,3,4),
               c(1,1,1,5,6,7),
               c(1,1,1,8,9,10))
  lay <- rbind(c(10,10,10,1,2,3),
               c(10,10,10,4,5,6),
               c(10,10,10,7,8,9))
  plots2 <- gridExtra::arrangeGrob(grobs = plots, layout_matrix = lay)
  return(gridExtra::grid.arrange(plots2))
}
alexthiery/scHelper documentation built on Aug. 26, 2023, 3:42 p.m.