Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion R/doublet.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
88 changes: 63 additions & 25 deletions R/plotting.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
)
}
Expand Down Expand Up @@ -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),
...
) {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -925,18 +947,24 @@ 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.',
i = 'Install: install.packages("patchwork")',
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") &
Expand Down Expand Up @@ -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")
Expand All @@ -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.")
Expand All @@ -1381,23 +1417,24 @@ 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
))
}
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
))
Expand Down Expand Up @@ -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),
...
) {
Expand All @@ -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)
Expand Down
10 changes: 10 additions & 0 deletions man/plot_doublet_scores.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions man/plot_embedding.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion man/score_doublets.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading