R/PlotClustersByTrt.R

Defines functions PlotClustersByTrt

Documented in PlotClustersByTrt

#' Given a Seurat object and treatment variable, compare
#' clusters between levels of the treatment
#'
#' @param cluster_freqs dataframe of cluster frequencies (produced by ComputeClustersByTrt function)
#'
#' @importFrom magrittr '%>%'
#' @examples
#' pbmc_small$trt <- sample(c('drug', 'control'), ncol(pbmc_small), replace=TRUE)
#' pbmc_small$genotype <- sample(c('1', '2', '3'), ncol(pbmc_small), replace=TRUE)
#' freq <- ComputeClustersByTrt(pbmc_small, trt, genotype)
#' PlotClustersByTrt(freq)
#'
#' @export
PlotClustersByTrt <- function(cluster_freqs, seed = 1,
                              jitter.width = 0.4, dodge.width = 0.55,
                              pt.size = 0.5, base_size = 16) {

    # Get some summary stats about cluster freqs
    cfrac <- cluster_freqs %>%
        dplyr::group_by(ident) %>%
        dplyr::summarize(max_per_1k = max(cells_per_thousand)) %>%
        dplyr::arrange(dplyr::desc(max_per_1k))

    # Make the plot
    set.seed(seed)
    dodge <- ggplot2::position_jitterdodge(jitter.width = jitter.width, dodge.width = dodge.width)
    cluster_freqs$popF <- factor(cluster_freqs$ident, cfrac$ident)
    g2 <- ggplot2::ggplot(cluster_freqs, ggplot2::aes(x = trt_var,
        y = cells_per_thousand, color = trt_var, fill = trt_var)) +
        ggplot2::geom_linerange(ggplot2::aes(ymin = lower_per_thousand, ymax = upper_per_thousand),
        position = dodge, alpha = 0.4, color = "darkgray") +
        ggplot2::geom_point(shape = 16, size = pt.size,
        position = dodge) + ggplot2::facet_wrap(~popF, scales = "free_y") + ggplot2::ylab("Cells per thousand") +
        ggplot2::guides(fill = 'none', color = 'none') + ggplot2::theme_bw(base_size = base_size) +
        ggplot2::theme(panel.grid.minor = ggplot2::element_blank()) +
        ggplot2::xlab('')
    g2
}
daskelly/earlycross documentation built on Feb. 20, 2023, 3:56 p.m.