From 3bfbc3f9190f4c09df8d08647cb9d92e7820c003 Mon Sep 17 00:00:00 2001 From: erliuu Date: Tue, 1 Dec 2026 23:15:41 -0800 Subject: [PATCH] feat([r] plotting): Add data value legend label mode for doublet plotting. --- NEWS.md | 1 + R/doublet.R | 2 +- R/plotting.R | 88 +++++++++++++++++++++++--------- man/plot_doublet_scores.Rd | 10 ++++ man/plot_embedding.Rd | 6 +++ man/score_doublets.Rd | 2 +- tests/testthat/test-plotting.R | 92 ++++++++++++++++++++++++++++++++++ 7 files changed, 174 insertions(+), 27 deletions(-) diff --git a/NEWS.md b/NEWS.md index 329f050..39656c2 100644 --- a/NEWS.md +++ b/NEWS.md @@ -13,6 +13,7 @@ * `load_project()` errors when data referenced by a checkpoint no longer matches what was saved. * `add_tile_matrix()` errors on arguments it does not use instead of ignoring them. * The hematopoiesis and multiome tutorials keep the project under `cache_dir` instead of R's temporary directory. +* `plot_embedding()` and `plot_doublet_scores()` gain `legend_labels = "value"`, which labels the continuous color bar in data units instead of quantiles. # MarchR 0.3.0 diff --git a/R/doublet.R b/R/doublet.R index e3b22f9..60a5d80 100644 --- a/R/doublet.R +++ b/R/doublet.R @@ -742,7 +742,7 @@ project_doublets.default <- function( #' #' @return A list with one row per real cell: #' \describe{ -#' \item{doublet_score}{log10(doublet_enrichment + 1) - primary scalar score} +#' \item{doublet_score}{-log10(Bonferroni-adjusted binomial p-value)} #' \item{doublet_enrichment}{observed / expected doublet neighbor fraction} #' } #' @export diff --git a/R/plotting.R b/R/plotting.R index a2e8e50..baf5493 100644 --- a/R/plotting.R +++ b/R/plotting.R @@ -163,33 +163,47 @@ palette_discrete <- function(set = "stallion", n = NULL, reverse = FALSE) { label } -# Prepare color data: detect discrete/continuous, clip, rescale +# Prepare color data: detect discrete/continuous, clip to quant_cut, and return the color +# scale's limits/breaks/labels. "quantile" rescales to [0, 1] and labels the clip ends by +# quantile; "value" keeps data units and leaves breaks and labels to ggplot. # @noRd -.prepare_color_data <- function(values, quant_cut = c(0.01, 0.99)) { +.prepare_color_data <- function(values, quant_cut = c(0.01, 0.99), legend_labels = "quantile") { is_discrete <- is.character(values) || is.factor(values) || is.logical(values) if (is_discrete) { lvls <- .natural_sort(unique(as.character(values))) return(list( values = factor(as.character(values), levels = lvls), - cutoffs = NULL, is_discrete = TRUE, scale_labels = NULL + cutoffs = NULL, is_discrete = TRUE )) } if (!is.null(quant_cut)) { cutoffs <- quantile(values, quant_cut, na.rm = TRUE, names = FALSE) - clipped <- pmax(pmin(values, cutoffs[2]), cutoffs[1]) - denom <- cutoffs[2] - cutoffs[1] - rescaled <- if (denom > 0) (clipped - cutoffs[1]) / denom else rep(0, length(clipped)) - scale_labels <- sprintf("p%g", 100 * quant_cut) + # Mostly-zero data: an upper cutoff of 0 would clip away every nonzero value + if (cutoffs[2] == 0) { + cutoffs[2] <- max(values, na.rm = TRUE) + quant_cut[2] <- 1 + } + values <- pmax(pmin(values, cutoffs[2]), cutoffs[1]) + labels <- sprintf("p%g", 100 * quant_cut) } else { cutoffs <- range(values, na.rm = TRUE) - denom <- cutoffs[2] - cutoffs[1] - rescaled <- if (denom > 0) (values - cutoffs[1]) / denom else rep(0, length(values)) - scale_labels <- round(cutoffs, 2) + labels <- round(cutoffs, 2) } - list(values = rescaled, cutoffs = cutoffs, is_discrete = FALSE, scale_labels = scale_labels) + if (legend_labels == "value") { + return(list( + values = values, cutoffs = cutoffs, is_discrete = FALSE, + limits = cutoffs, breaks = ggplot2::waiver(), labels = ggplot2::waiver() + )) + } + denom <- cutoffs[2] - cutoffs[1] + rescaled <- if (denom > 0) (values - cutoffs[1]) / denom else rep(0, length(values)) + list( + values = rescaled, cutoffs = cutoffs, is_discrete = FALSE, + limits = c(0, 1), breaks = c(0, 1), labels = labels + ) } # Build point geom: geom_point or scattermore @@ -393,6 +407,9 @@ palette_continuous <- function(set = "solarExtra", n = 256L) { #' @param legend_position (character) Legend position. Default \code{"bottom"}. #' @param legend_text_size (numeric) Legend text size. Default 5. #' @param legend_title (character) Legend title. NULL for auto. +#' @param legend_labels (character) Continuous color bar labels: \code{"quantile"} marks the +#' \code{quant_cut} ends (e.g. "p1", "p99"); \code{"value"} shows data units. +#' Default \code{"quantile"}. #' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param ... Additional arguments (unused). #' @return A ggplot object, or named list of ggplot objects for multiple features. @@ -445,12 +462,14 @@ plot_embedding.default <- function( legend_position = "bottom", legend_text_size = 5, legend_title = NULL, + legend_labels = c("quantile", "value"), verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() assert_for(verbose, "logical") assert_that(is.matrix(embedding), ncol(embedding) == 2) + legend_labels <- match.arg(legend_labels) is_mat <- is.matrix(x) || inherits(x, "IterableMatrix") if (is_mat) { assert_that(!is.null(features), msg = "features required when x is a matrix") @@ -516,7 +535,7 @@ plot_embedding.default <- function( title = feat, xlabel = xlabel, ylabel = ylabel, extend = extend, legend_position = legend_position, legend_text_size = legend_text_size, legend_title = legend_title, - verbose = FALSE, ... + legend_labels = legend_labels, verbose = FALSE, ... ) }) names(plots) <- features @@ -526,7 +545,7 @@ plot_embedding.default <- function( } # Single vector source - color_data <- .prepare_color_data(x, quant_cut = quant_cut) + color_data <- .prepare_color_data(x, quant_cut = quant_cut, legend_labels = legend_labels) is_discrete <- color_data$is_discrete # Highlight: grey out non-highlighted cells, reorder so highlighted draw on top @@ -642,8 +661,8 @@ plot_embedding.default <- function( .point_geom(size = size, alpha = alpha, rastr = rastr, raster_px = raster_px) + ggplot2::scale_color_gradientn( - colors = colors_continuous, limits = c(0, 1), - breaks = c(0, 1), labels = color_data$scale_labels, + colors = colors_continuous, limits = color_data$limits, + breaks = color_data$breaks, labels = color_data$labels, na.value = "lightgrey", name = legend_title ) } @@ -715,6 +734,7 @@ plot_embedding.MarchRProject <- function( legend_position = "bottom", legend_text_size = 5, legend_title = NULL, + legend_labels = c("quantile", "value"), verbose = getOption("MarchR.verbose", FALSE), ... ) { @@ -776,7 +796,7 @@ plot_embedding.MarchRProject <- function( title = title, xlabel = xlabel, ylabel = ylabel, extend = extend, legend_position = legend_position, legend_text_size = legend_text_size, legend_title = legend_title, - verbose = verbose, ... + legend_labels = legend_labels, verbose = verbose, ... ) if (verbose) .log_finish(run, .log_plural(n_plots, "plot")) plots @@ -913,10 +933,12 @@ plot_gene_scores.MarchRProject <- function( res <- if (length(plots) == 1) { plots[[1]] } else if (patchwork) { + legend_labels <- match.arg(dot_args$legend_labels %||% "quantile", c("quantile", "value")) .combine_gene_score_plots( plots, colors_continuous = dot_args$colors_continuous, - legend_title = dot_args$legend_title + legend_title = dot_args$legend_title, + shared_scale = legend_labels == "quantile" ) } else { plots @@ -925,11 +947,14 @@ plot_gene_scores.MarchRProject <- function( res } -#' Assemble per-gene score plots into one shared-legend figure +#' Assemble per-gene score plots into one figure +#' +#' With \code{shared_scale = TRUE} every panel gets the same \code{c(0, 1)} fill scale, so +#' \code{guides = "collect"} renders a single legend; otherwise each panel keeps its own. #' #' @keywords internal #' @noRd -.combine_gene_score_plots <- function(plots, colors_continuous, legend_title) { +.combine_gene_score_plots <- function(plots, colors_continuous, legend_title, shared_scale = TRUE) { if (!requireNamespace("patchwork", quietly = TRUE)) { rlang::abort(c( 'Package "patchwork" is required for patchwork = TRUE.', @@ -937,6 +962,9 @@ plot_gene_scores.MarchRProject <- function( i = 'Or use patchwork = FALSE (default) to get a list of plots.' )) } + if (!shared_scale) { + return(patchwork::wrap_plots(plots) & ggplot2::theme(legend.position = "bottom")) + } suppressMessages( patchwork::wrap_plots(plots) + patchwork::plot_layout(guides = "collect") & @@ -1341,9 +1369,15 @@ plot_enrichment_heatmap <- function(enrichment, n = 10L, cutoff = 20, ...) { #' @param dataset_name (character) For MarchRProject only. #' @param plot (character) One or more of \code{"enrichment"}, \code{"score"}, #' \code{"density"}. Default plots all. +#' @param legend_labels (character) \code{"quantile"} or \code{"value"}. \code{"value"} labels the +#' color bar in the units of the \code{filter_doublets()} cutoffs. Default \code{"quantile"}. #' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param ... Passed to \code{\link{plot_embedding}} for enrichment/score panels. #' @return ggplot object or patchwork composition. +#' @details +#' **ArchR correspondence**: the doublet summary plots of \code{addDoubletScores()}, which clip +#' enrichment and score at the 95th percentile and label the color bar in data units +#' (\code{legend_labels = "value"}). #' @export plot_doublet_scores <- function(x, ...) { UseMethod("plot_doublet_scores") @@ -1354,12 +1388,14 @@ plot_doublet_scores <- function(x, ...) { plot_doublet_scores.MarchRDataset <- function( x, plot = c("enrichment", "score", "density"), + legend_labels = c("quantile", "value"), verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() assert_for(verbose, "logical") plot <- match.arg(plot, several.ok = TRUE) + legend_labels <- match.arg(legend_labels) if (is.null(x$doublet_data) || is.null(x$doublet_data$scores)) { rlang::abort("Doublet data not found. Run add_doublet_scores() first.") @@ -1381,15 +1417,15 @@ plot_doublet_scores.MarchRDataset <- function( colors_continuous = palette_continuous("greyMagma"), plot_as = "points" ) - for (nm in names(defaults)) { - if (is.null(dot_args[[nm]])) dot_args[[nm]] <- defaults[[nm]] - } + dot_args <- c(dot_args, defaults[setdiff(names(defaults), names(dot_args))]) + title_suffix <- if (legend_labels == "quantile") " (Quantile)" else "" panels <- list() if ("enrichment" %in% plot) { panels$enrichment <- do.call(plot_embedding.default, c( list(x = scores$doublet_enrichment, embedding = umap_cells, - title = "Simulated Doublet Enrichment", legend_title = "Enrichment (Quantile)", + title = "Simulated Doublet Enrichment", + legend_title = paste0("Enrichment", title_suffix), legend_labels = legend_labels, verbose = FALSE), dot_args )) @@ -1397,7 +1433,8 @@ plot_doublet_scores.MarchRDataset <- function( if ("score" %in% plot) { panels$score <- do.call(plot_embedding.default, c( list(x = scores$doublet_score, embedding = umap_cells, - title = "Doublet Score [-log10(P-adj)]", legend_title = "Score (Quantile)", + title = "Doublet Score [-log10(P-adj)]", + legend_title = paste0("Score", title_suffix), legend_labels = legend_labels, verbose = FALSE), dot_args )) @@ -1465,6 +1502,7 @@ plot_doublet_scores.MarchRProject <- function( x, dataset_name = character(0), plot = c("enrichment", "score", "density"), + legend_labels = c("quantile", "value"), verbose = getOption("MarchR.verbose", FALSE), ... ) { @@ -1474,7 +1512,7 @@ plot_doublet_scores.MarchRProject <- function( if (verbose) run <- .log_start("Doublet score plots", sprintf("'%s'", dataset_name)) p <- plot_doublet_scores( x$datasets[[dataset_name]], - plot = plot, verbose = FALSE, ... + plot = plot, legend_labels = legend_labels, verbose = FALSE, ... ) if (verbose) { n_plots <- if (inherits(p, "ggplot") && !inherits(p, "patchwork")) 1L else length(p) diff --git a/man/plot_doublet_scores.Rd b/man/plot_doublet_scores.Rd index 7dbd4e4..42e0762 100644 --- a/man/plot_doublet_scores.Rd +++ b/man/plot_doublet_scores.Rd @@ -11,6 +11,7 @@ plot_doublet_scores(x, ...) \method{plot_doublet_scores}{MarchRDataset}( x, plot = c("enrichment", "score", "density"), + legend_labels = c("quantile", "value"), verbose = getOption("MarchR.verbose", FALSE), ... ) @@ -19,6 +20,7 @@ plot_doublet_scores(x, ...) x, dataset_name = character(0), plot = c("enrichment", "score", "density"), + legend_labels = c("quantile", "value"), verbose = getOption("MarchR.verbose", FALSE), ... ) @@ -31,6 +33,9 @@ plot_doublet_scores(x, ...) \item{plot}{(character) One or more of \code{"enrichment"}, \code{"score"}, \code{"density"}. Default plots all.} +\item{legend_labels}{(character) \code{"quantile"} or \code{"value"}. \code{"value"} labels the +color bar in the units of the \code{filter_doublets()} cutoffs. Default \code{"quantile"}.} + \item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{dataset_name}{(character) For MarchRProject only.} @@ -42,3 +47,8 @@ ggplot object or patchwork composition. Plots doublet enrichment, score, or simulated-doublet density. Must be run after \code{add_doublet_scores()} and before \code{filter_doublets()}. } +\details{ +\strong{ArchR correspondence}: the doublet summary plots of \code{addDoubletScores()}, which clip +enrichment and score at the 95th percentile and label the color bar in data units +(\code{legend_labels = "value"}). +} diff --git a/man/plot_embedding.Rd b/man/plot_embedding.Rd index 37fc156..5c19ece 100644 --- a/man/plot_embedding.Rd +++ b/man/plot_embedding.Rd @@ -41,6 +41,7 @@ plot_embedding(x, ...) legend_position = "bottom", legend_text_size = 5, legend_title = NULL, + legend_labels = c("quantile", "value"), verbose = getOption("MarchR.verbose", FALSE), ... ) @@ -79,6 +80,7 @@ plot_embedding(x, ...) legend_position = "bottom", legend_text_size = 5, legend_title = NULL, + legend_labels = c("quantile", "value"), verbose = getOption("MarchR.verbose", FALSE), ... ) @@ -157,6 +159,10 @@ plotting. NULL plots all cells. Default NULL.} \item{legend_title}{(character) Legend title. NULL for auto.} +\item{legend_labels}{(character) Continuous color bar labels: \code{"quantile"} marks the +\code{quant_cut} ends (e.g. "p1", "p99"); \code{"value"} shows data units. +Default \code{"quantile"}.} + \item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{color_by}{(character) \code{"cell_metadata"} or matrix assay name.} diff --git a/man/score_doublets.Rd b/man/score_doublets.Rd index 07719bc..701ff9c 100644 --- a/man/score_doublets.Rd +++ b/man/score_doublets.Rd @@ -27,7 +27,7 @@ arguments such as \code{k} or \code{metric} inside the partial function.} \value{ A list with one row per real cell: \describe{ -\item{doublet_score}{log10(doublet_enrichment + 1) - primary scalar score} +\item{doublet_score}{-log10(Bonferroni-adjusted binomial p-value)} \item{doublet_enrichment}{observed / expected doublet neighbor fraction} } } diff --git a/tests/testthat/test-plotting.R b/tests/testthat/test-plotting.R index 9f56a33..852ac81 100644 --- a/tests/testthat/test-plotting.R +++ b/tests/testthat/test-plotting.R @@ -65,6 +65,26 @@ test_that(".prepare_color_data returns raw range when quant_cut = NULL", { expect_equal(range(result$values), c(0, 1)) }) +test_that(".prepare_color_data keeps data units when legend_labels = 'value'", { + vals <- c(rep(0, 50), seq(0, 10, length.out = 100), rep(100, 5)) + cutoffs <- quantile(vals, c(0.01, 0.95), names = FALSE) + quant <- MarchR:::.prepare_color_data(vals, quant_cut = c(0.01, 0.95)) + value <- MarchR:::.prepare_color_data(vals, quant_cut = c(0.01, 0.95), legend_labels = "value") + expect_equal(quant$limits, c(0, 1)) + expect_equal(quant$labels, c("p1", "p95")) + expect_equal(value$limits, cutoffs) + expect_equal(range(value$values), cutoffs) + expect_equal((value$values - cutoffs[1]) / diff(cutoffs), quant$values) +}) + +test_that(".prepare_color_data falls back to the maximum when the upper quantile is 0", { + vals <- c(rep(0, 97), 5, 10, 20) + result <- MarchR:::.prepare_color_data(vals, quant_cut = c(0, 0.95)) + expect_equal(result$cutoffs, c(0, 20)) + expect_equal(result$labels, c("p0", "p100")) + expect_equal(max(result$values), 1) +}) + test_that(".point_geom returns geom_point by default", { geom <- MarchR:::.point_geom(size = 0.5) expect_s3_class(geom, "LayerInstance") @@ -120,6 +140,24 @@ test_that("plot_embedding.default auto-selects hexplot for continuous", { expect_true(any(grepl("Hex", layer_classes))) }) +test_that("plot_embedding.default legend_labels = 'value' labels the color bar in data units", { + set.seed(1) + emb <- matrix(rnorm(400), ncol = 2, dimnames = list(NULL, c("UMAP1", "UMAP2"))) + vals <- rexp(200, 1 / 8) + cutoffs <- quantile(vals, c(0.01, 0.99), names = FALSE) + scale_of <- function(p, aes) ggplot2::ggplot_build(p)$plot$scales$get_scales(aes) + + pts <- plot_embedding.default(vals, emb, plot_as = "points", legend_labels = "value") + expect_equal(scale_of(pts, "colour")$get_limits(), cutoffs) + expect_false(any(grepl("^p", scale_of(pts, "colour")$get_labels()))) + hex <- plot_embedding.default(vals, emb, legend_labels = "value") + expect_gt(max(scale_of(hex, "fill")$get_limits()), 1) + + default <- plot_embedding.default(vals, emb, plot_as = "points") + expect_equal(scale_of(default, "colour")$get_labels(), c("p1", "p99")) + expect_error(plot_embedding.default(vals, emb, legend_labels = "raw"), "should be one of") +}) + test_that("plot_embedding.default hides axis ticks when keep_axis = FALSE", { set.seed(1) emb <- matrix(rnorm(200), ncol = 2, dimnames = list(NULL, c("UMAP_1", "UMAP_2"))) @@ -317,6 +355,34 @@ test_that("plot_gene_scores patchwork = TRUE yields one shared bottom legend", { for (lim in fill_limits) expect_equal(lim, c(0, 1)) }) +test_that("plot_gene_scores patchwork keeps per-panel limits with legend_labels = 'value'", { + skip_if_not_installed("patchwork") + proj <- create_test_project(cells = c(40), rna_val_method = "pois") + ds_name <- names(proj$datasets)[[1]] + ds_cells <- cell_names(proj$datasets[[ds_name]]) + vals1 <- rnorm(length(ds_cells)); names(vals1) <- ds_cells + vals2 <- rnorm(length(ds_cells)); names(vals2) <- ds_cells + proj$datasets[[ds_name]] <- add_cell_metadata_col( + proj$datasets[[ds_name]], values = vals1, col_name = "UMAP_1", overwrite = TRUE + ) + proj$datasets[[ds_name]] <- add_cell_metadata_col( + proj$datasets[[ds_name]], values = vals2, col_name = "UMAP_2", overwrite = TRUE + ) + rna_mat <- get_matrix(proj$datasets[[ds_name]], assay_name = "RNA") + proj$datasets[[ds_name]] <- add_matrix( + proj$datasets[[ds_name]], rna_mat, mat_name = "GeneScoreMatrix", overwrite = TRUE + ) + genes <- c("gene_1", "gene_2", "gene_3") + fill_limits <- function(p) ggplot2::ggplot_build(p)$plot$scales$get_scales("fill")$get_limits() + + lst <- plot_gene_scores(proj, genes = genes, impute = FALSE, legend_labels = "value") + pw <- plot_gene_scores( + proj, genes = genes, impute = FALSE, patchwork = TRUE, legend_labels = "value" + ) + panels <- c(pw$patches$plots, list(pw)) + expect_equal(lapply(panels, fill_limits), unname(lapply(lst, fill_limits))) +}) + test_that("plot_gene_scores reports each step and its result", { withr::local_options(rlib_message_verbosity = "verbose", MarchR.verbose = NULL) proj <- create_test_trajectory_project()$proj @@ -370,6 +436,32 @@ test_that("plot_doublet_scores uses plot_embedding for enrichment/score panels", expect_equal(p$theme$legend.position, "bottom") }) +test_that("plot_doublet_scores legend_labels = 'value' labels the color bar in cutoff units", { + set.seed(3) + n <- 200 + scores <- data.frame( + doublet_enrichment = rexp(n), + doublet_score = c(rep(0, n - 5), 3, 8, 15, 30, 60) + ) + ds <- MarchRDataset() + ds$doublet_data <- list( + scores = scores, cell_umap = data.frame(UMAP1 = rnorm(n), UMAP2 = rnorm(n)) + ) + colour_scale <- function(p) ggplot2::ggplot_build(p)$plot$scales$get_scales("colour") + + enrich <- colour_scale(plot_doublet_scores(ds, plot = "enrichment", legend_labels = "value")) + expect_equal(enrich$get_limits(), quantile(scores$doublet_enrichment, c(0, 0.95), names = FALSE)) + expect_equal(enrich$name, "Enrichment") + expect_equal(colour_scale(plot_doublet_scores(ds, plot = "score"))$name, "Score (Quantile)") + + # Over 95% of scores are 0, so the upper cutoff falls back to the maximum + score <- colour_scale(plot_doublet_scores(ds, plot = "score", legend_labels = "value")) + expect_equal(score$get_limits(), c(0, 60)) + + unclipped <- colour_scale(plot_doublet_scores(ds, plot = "enrichment", quant_cut = NULL)) + expect_equal(unclipped$get_labels(), round(range(scores$doublet_enrichment), 2)) +}) + test_that("plot_doublet_scores reports its setup and result", { withr::local_options(rlib_message_verbosity = "verbose", MarchR.verbose = NULL) n <- 50