-
Notifications
You must be signed in to change notification settings - Fork 0
/
plotDensity.R
68 lines (61 loc) · 1.73 KB
/
plotDensity.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#' Plot grid-based density.
#'
#' @param spe A SpatialExperiment object.
#' @param coi A character vector of cell types of interest (COIs).
#' @param probs Numeric value between 0 and 1, used for filtering
#' uninformative grid, default is 0.8.
#'
#' @return A ggplot object.
#' @export
#'
#' @examples
#'
#' data("xenium_bc_spe")
#'
#' spe <- gridDensity(spe)
#'
#' plotDensity(spe, coi = "Breast cancer")
#'
#' plotDensity(spe, coi = "Fibroblasts")
#'
plotDensity <- function(spe, coi, probs = 0.8) {
grid_data <- as.data.frame(spe@metadata$grid_density)
coi_clean <- janitor::make_clean_names(coi)
dens_cols <- paste("density", coi_clean, sep = "_")
if (!all(dens_cols %in% colnames(grid_data))) {
stop("Density of COI is not yet computed.")
}
grid_data$density_coi_average <- rowMeans(as.matrix(
grid_data[, which(colnames(grid_data) %in% dens_cols),
drop = FALSE
]
))
kp <- grid_data$density_coi_average >=
quantile(grid_data$density_coi_average,
probs = probs
)
p <- ggplot() +
geom_tile(
data = grid_data[kp, ],
aes(
x = x_grid, y = y_grid,
fill = density_coi_average
)
) +
theme_classic() +
scale_fill_gradientn(colours = rev(col.spec)) +
labs(x = "x", y = "y", fill = "Density") +
lims(
x = c(
min(grid_data[, "x_grid"]),
max(grid_data[, "x_grid"])
),
y = c(
min(grid_data[, "y_grid"]),
max(grid_data[, "y_grid"])
)
)
ggtitle(coi)
return(p)
}
utils::globalVariables(c("x_grid", "y_grid", "density_coi_average"))