scider is a user-friendly R package providing functions
to model the global density of cells in a slide of spatial
transcriptomics data. All functions in the package are built on the
SpatialExperiment object, allowing integration into various
spatial transcriptomics-related packages from Bioconductor. After
modelling density, scider supports several downstream
analyses, including colocalization analysis, boundary detection and
differential density analysis.
The plotting functions return ggplot objects, so figures
can be further customised with any ggplot2 layer.
This vignette walks through a typical workflow on a Xenium breast cancer dataset.
The example dataset is a small SpatialExperiment object
(one Xenium breast cancer section) hosted as a GitHub Release asset.
Download it once and cache locally:
data_url <- "https://github.com/ChenLaboratory/example_data/releases/download/v1.0.0/spe_xenium_bc_s1rep1.rds"
cache_dir <- tools::R_user_dir("scider", "cache")
data_file <- file.path(cache_dir, "spe_xenium_bc_s1rep1.rds")
if (!file.exists(data_file)) {
dir.create(cache_dir, recursive = TRUE, showWarnings = FALSE)
download.file(data_url, data_file, mode = "wb")
}
spe <- readRDS(data_file)
spe
#> class: SpatialExperiment
#> dim: 313 163797
#> metadata(0):
#> assays(1): counts
#> rownames(313): ABCC11 ACTA2 ... ZEB2 ZNF562
#> rowData names(3): ID Symbol Type
#> colnames(163797): cell_1 cell_2 ... cell_167779 cell_167780
#> colData names(12): cell_id transcript_counts ... gene_counts cell_type
#> reducedDimNames(0):
#> mainExpName: NULL
#> altExpNames(0):
#> spatialCoords names(2) : x_centroid y_centroid
#> imgData names(1): sample_idThe Xenium data was annotated by 10X Genomics. The cell type annotation is summarized below.
table(colData(spe)$cell_type)
#>
#> Stromal Invasive_Tumor DCIS Macrophages Myoepi Endothelial CD4+_T_Cells CD8+_T_Cells Others B_Cells
#> 41422 38149 24604 12798 9938 8931 8453 6940 5769 4987
#> Perivascular-Like DCs Mast_Cells
#> 847 792 167We can visualize the spatial distribution of all the cell types across the tissue as follows.
Or visualize the spatial distribution of specific cell types (e.g., DCIS and Invasive Tumor).
COI <- c("DCIS", "Invasive_Tumor")
sel <- spe$cell_type %in% COI
plotSpatial(spe[, sel], group.by = "cell_type")We can also examine the expression level of each individual gene
spatially. Because the returned object is a ggplot, we can
add a title with ggtitle().
scider implements grid-based density analysis for
spatial transcriptomics data. We first calculate density for each cell
type using function gridDensity. The calculated density and
grid information are saved in the metadata of the
SpatialExperiment object. The size of the grid (bin) is set
by the grid.length.x parameter, and the level of smoothing
is set by bandwidth.
We can visualise the overall (all cell types) density of the whole
tissue using function plotDensity. The probs
parameter indicates the density percentile below which the grids are
filtered (not plotted). Setting probs to 0 will plot
everything including the background.
Alternatively, user can specify cutoff to filter grids
with low cell density. The density values represent the expected numbers
of cells at each grid.
We can also visualise the density of specific cell type(s).
After obtaining grid-based density for each cell type, we can then
detect regions-of-interest (ROIs) based on density of certain cell
type(s). This is done by using the findROI function.
Here we identify ROIs based on the cell density of DCIS and invasive
tumor. The min.density parameter filters grids with low
cell density, whereas the ngrid.min gives the minimum
number of grids that each ROI should have.
spe <- findROI(spe, coi = COI, min.density = 0.5, ngrid.min = 20)
#> Overwriting the probs argument. Grids are filtered by the min.density value.The ROIs can then be visualized using plotROI.
After defining ROIs, we can test whether the densities of any two
cell types are spatially correlated, within each ROI or overall while
accounting for ROI variation. This is done with function
corDensity. By default it compares the observed correlation
between two cell type densities with the correlations obtained under
random labelling: cell locations are kept, cell type labels are shuffled
and the densities are recomputed (999 times by default). Because the
p-values come from these random relabellings, we set a seed for
reproducible results. The modified t-test of Dutilleul, which accounts
for the spatial autocorrelation between neighbouring grids, is available
with method = "modified.ttest".
We can examine the correlation between each pair of cell types in
each ROI. Besides the observed correlation (cor.coef), the
results give its expected value under random labelling
(cor.expected), the difference between the two
(shift), and one-sided p-values for positive
(p.Pos) and negative (p.Neg) association.
results$ROI
#> DataFrame with 3276 rows and 9 columns
#> celltype1 celltype2 ROI ngrid cor.coef cor.expected shift p.Pos p.Neg
#> <character> <character> <character> <integer> <numeric> <numeric> <numeric> <numeric> <numeric>
#> 1 Stromal Invasive tumor 1 202 -0.0774348 0.613646 -0.691081 1 0.001
#> 2 Stromal Invasive tumor 2 128 -0.6751916 0.732848 -1.408039 1 0.001
#> 3 Stromal Invasive tumor 3 248 -0.8019436 0.825980 -1.627924 1 0.001
#> 4 Stromal Invasive tumor 4 171 -0.8022129 0.778160 -1.580373 1 0.001
#> 5 Stromal Invasive tumor 5 227 -0.6857148 0.769038 -1.454753 1 0.001
#> ... ... ... ... ... ... ... ... ... ...
#> 3272 D cs Mast cells 38 54 NA 0.055113517 NA NA NA
#> 3273 D cs Mast cells 39 108 -0.0571595 0.015804798 -0.0729643 0.5844422 0.416581
#> 3274 D cs Mast cells 40 132 0.1020318 0.010188023 0.0918438 0.3750000 0.626000
#> 3275 D cs Mast cells 41 103 0.6772782 -0.000472391 0.6777506 0.0111675 0.989848
#> 3276 D cs Mast cells 42 62 NA 0.093383468 NA NA NAOr the correlation between each pair of cell types across all ROIs.
The overall results also count the ROIs in which the observed
correlation lies above (n.above) or below
(n.below) its expected value, or is significantly so
(n.sig.Pos, n.sig.Neg):
results$overall
#> DataFrame with 78 rows and 12 columns
#> celltype1 celltype2 cor.coef cor.expected shift p.Pos p.Neg n.roi n.above n.below n.sig.Pos n.sig.Neg
#> <character> <character> <numeric> <numeric> <numeric> <numeric> <numeric> <integer> <integer> <integer> <integer> <integer>
#> 1 Stromal Invasive tumor -0.5021193 0.678683 -1.1808023 1.000 0.001 41 0 41 0 41
#> 2 Stromal Dcis -0.2910660 0.632843 -0.9239088 1.000 0.001 40 1 39 0 39
#> 3 Stromal Macrophages 0.2575724 0.550896 -0.2933232 1.000 0.001 42 8 34 3 20
#> 4 Stromal Myoepi 0.0541824 0.514875 -0.4606926 1.000 0.001 40 1 39 0 33
#> 5 Stromal Endothelial 0.5209102 0.499207 0.0217035 0.132 0.869 42 17 25 8 8
#> ... ... ... ... ... ... ... ... ... ... ... ... ...
#> 74 B cells D cs 0.318719 0.1409202 0.1777986 0.001 1.000 40 31 9 13 2
#> 75 B cells Mast cells 0.261348 0.0776230 0.1837254 0.001 1.000 39 26 13 7 1
#> 76 Perivascular like D cs 0.175935 0.0770501 0.0988851 0.001 1.000 40 26 14 7 0
#> 77 Perivascular like Mast cells 0.132619 0.0473268 0.0852918 0.014 0.987 39 24 15 5 1
#> 78 D cs Mast cells 0.164990 0.0449535 0.1200369 0.001 1.000 38 22 16 7 3We can visualise the statistics between each pair of cell types using
function plotCorHeatmap. Two cell type densities tend to
rise and fall together with the local number of cells, so the observed
correlations are mostly positive. The shift measures
co-localization (positive) or segregation (negative) beyond this, and is
easier to interpret. Here we show the shift in each ROI for a selection
of cell types:
plotCorHeatmap(results, level = "ROI", stats = "shift",
cell.type = c("DCIS", "Invasive_Tumor", "Stromal",
"Macrophages", "CD8+_T_Cells", "B_Cells"),
fontsize_col = 6)Or the shift for all cell type pairs across the whole slide:
The strongest results above are between tumour cells and the
surrounding cells, which largely reflects the separation of the tumour
from the rest of the tissue. To look for structure beyond such
compartments, corDensity can shuffle the cell type labels
only among cells of the same compartment, given by a column of
colData passed to permute.within. The
arrangement explained by the compartments then becomes part of the
expected value.
Here we group the cell types into epithelial, stromal and immune
compartments. Cells annotated as Others are placed in the
stromal compartment. Compartments should be coarse: a cell type that is
the only type in its compartment is never shuffled.
compartment <- c(DCIS = "epithelial", Invasive_Tumor = "epithelial",
Myoepi = "epithelial",
Stromal = "stromal", Endothelial = "stromal",
`Perivascular-Like` = "stromal", Others = "stromal",
Macrophages = "immune", `CD4+_T_Cells` = "immune",
`CD8+_T_Cells` = "immune", B_Cells = "immune",
DCs = "immune", Mast_Cells = "immune")
spe$compartment <- unname(compartment[spe$cell_type])
table(spe$compartment)
#>
#> epithelial immune stromal
#> 104175 19502 40120For two cell types in the same compartment, a positive shift now means that they share neighbourhoods more than two random cells of that compartment would. For cell types in different compartments, it means that they lie closer to each other than random cells of their compartments would. The pairs with the largest shifts are:
res <- as.data.frame(results_within$overall)
res <- res[order(abs(res$shift), decreasing = TRUE),
c("celltype1", "celltype2", "cor.coef", "cor.expected", "shift",
"n.sig.Pos", "n.sig.Neg")]
res[3:5] <- round(res[3:5], 2)
print(head(res, 12), row.names = FALSE)
#> celltype1 celltype2 cor.coef cor.expected shift n.sig.Pos n.sig.Neg
#> Stromal Invasive tumor -0.50 0.85 -1.35 0 37
#> Stromal Dcis -0.29 0.81 -1.10 0 40
#> Stromal B cells 0.57 -0.27 0.85 30 3
#> Stromal Endothelial 0.52 -0.20 0.72 29 1
#> Stromal Cd8 t cells 0.42 -0.29 0.71 33 2
#> Invasive tumor Dcis 0.12 0.81 -0.69 2 32
#> Myoepi Endothelial 0.05 0.70 -0.65 0 38
#> Macrophages Myoepi 0.08 0.73 -0.65 0 39
#> Stromal Cd4 t cells 0.44 -0.20 0.64 28 3
#> Myoepi Cd4 t cells 0.09 0.69 -0.60 0 36
#> Dcis Myoepi 0.37 -0.19 0.56 35 0
#> Stromal Others 0.25 -0.28 0.53 25 1Within the epithelium, DCIS cells co-localize with myoepithelial cells and segregate from invasive tumour cells, consistent with the myoepithelial layer that surrounds ducts in DCIS but is lost in invasive carcinoma. The fibroblast-like stromal cells lie further from tumour cells, and closer to B and T cells, than random cells of the respective compartments would.
Another strategy to partition a tissue spatially is to construct cell
density contours. This can be done using the getContour
function.
The equal.cell parameter ensures roughly equal cell
numbers across all density levels.
spe <- getContour(spe, coi = COI, equal.cell = TRUE)
#> Finding contour using total density of input COIs.
#> Using bins = 10 to draw contours with equal cell numbers.The constructed contours can be visualised using
plotContour.
sessionInfo()
#> R version 4.6.2 (2026-10-29 ucrt)
#> Platform: x86_64-w64-mingw32/x64
#> Running under: Windows 11 x64 (build 26300)
#>
#> Matrix products: default
#> LAPACK version 3.12.1
#>
#> locale:
#> [1] LC_COLLATE=English_Australia.utf8 LC_CTYPE=English_Australia.utf8 LC_MONETARY=English_Australia.utf8 LC_NUMERIC=C LC_TIME=English_Australia.utf8
#>
#> time zone: Australia/Sydney
#> tzcode source: internal
#>
#> attached base packages:
#> [1] stats4 stats graphics grDevices utils datasets methods base
#>
#> other attached packages:
#> [1] ggplot2_4.0.4 SpatialExperiment_1.22.0 SingleCellExperiment_1.34.0 SummarizedExperiment_1.42.0 Biobase_2.72.0 GenomicRanges_1.64.0
#> [7] Seqinfo_1.2.0 IRanges_2.46.0 S4Vectors_0.50.3 BiocGenerics_0.58.1 generics_0.1.4 MatrixGenerics_1.24.0
#> [13] matrixStats_1.5.0 scider_1.11.1
#>
#> loaded via a namespace (and not attached):
#> [1] tidyselect_1.2.1 viridisLite_0.4.3 dplyr_1.2.1 farver_2.1.2 S7_1.0.0 fastmap_1.2.0 spatstat.geom_3.8-3
#> [8] spatstat.explore_3.8-3 janitor_2.2.1 promises_1.5.0 digest_0.6.39 timechange_0.4.0 mime_0.13 lifecycle_1.0.5
#> [15] sf_1.1-3 hexDensity_1.4.11 spatstat.data_3.1-9 magrittr_2.0.5 dbscan_1.3.0 compiler_4.6.2 rlang_1.3.0
#> [22] tools_4.6.2 igraph_2.3.4 data.table_1.18.6.1 knitr_1.52 S4Arrays_1.12.1 labeling_0.4.3 htmlwidgets_1.6.4
#> [29] classInt_0.4-11 DelayedArray_0.38.2 RColorBrewer_1.1-3 KernSmooth_2.23-27 abind_1.4-8 withr_3.0.3 purrr_1.2.2
#> [36] fastmatrix_0.6-6 grid_4.6.2 polyclip_1.10-7 e1071_1.7-17 xtable_1.8-8 scales_1.4.0 spatstat.utils_3.2-6
#> [43] cli_3.6.6 otel_0.3.0 httr_1.4.9 rjson_0.2.23 proxy_0.4-29 DBI_1.3.0 stringr_1.6.0
#> [50] XVector_0.52.0 SpatialPack_0.4-1 vctrs_0.7.3 Matrix_1.7-6 jsonlite_2.0.0 fftwtools_0.9-11 tensor_1.5.1
#> [57] magick_2.9.1 plotly_4.12.1 hexbin_1.28.6 spatstat.univar_3.2-0 tidyr_1.3.2 units_1.0-1 goftest_1.2-3
#> [64] glue_1.8.1 spatstat.random_3.5-2 codetools_0.2-20 stringi_1.8.9 lubridate_1.9.5 gtable_0.3.6 later_1.4.8
#> [71] deldir_2.0-4 tibble_3.3.1 pillar_1.11.1 htmltools_0.5.9 R6_2.6.1 evaluate_1.0.5 shiny_1.15.0
#> [78] lattice_0.23-1 pheatmap_1.0.13 snakecase_0.11.1 httpuv_1.6.17 class_7.3-24 Rcpp_1.1.2 SparseArray_1.12.3
#> [85] nlme_3.1-172 spatstat.sparse_3.2-0 xfun_0.62 pkgconfig_2.0.3