Skip to main content

Spatial domains and spatially variable genes in spatial transcriptomics

Illustrated principles, R workflows and multi-sample analysis strategies for spatial domains and spatially variable genes in Visium HD.
STx
Created

Thursday, November 26, 2026

Modified

Thursday, November 26, 2026

In spatial transcriptomics, particularly 10x Visium HD, there are two complementary approaches to analysing gene expression:

Spatial domain identification and spatially variable gene (SVG) detection are two fundamental spatial-specific analyses. Both incorporate physical coordinates, but they address different biological questions.

1. Overview of the analysis principles

Characteristics Spatial domain Spatially variable genes
Main question How is the tissue organized? Which genes exhibit spatial patterns?
Analysis target Bins, spots or cells Individual genes
Input Expression features and coordinates Gene expression and coordinates
Principle Spatial-aware clustering Spatial autocorrelation or spatial statistical modelling
Output Domain label for each bin/cell Gene ranking, spatial statistic and method-dependent significance
Common R tools BANKSY, BayesSpace Seurat, SPARK-X, nnSVG
Biological interpretation Tissue architecture and microenvironment Spatially organized molecular programs

2. Spatial domain identification

2.1 What is a spatial domain?

A spatial domain is a tissue region characterized by a particular combination of gene expression profiles and spatial organization.

For example, in a tumour tissue, spatial domains might represent:

  • Tumour core
  • Invasive tumour boundary
  • Immune-enriched microenvironment
  • Fibroblast-enriched stroma
  • Normal epithelial region

A spatial domain is not necessarily a cell type. It may contain multiple cell types that collectively constitute a functional tissue compartment.

Illustrative spatial domain annotation of a tumour tissue. Biological identities must be validated using markers and histology.

2.2 Why is standard single-cell clustering insufficient?

Although every Visium HD bin has spatial coordinates, standard clustering algorithms such as Louvain and Leiden do not automatically use these coordinates.

In a standard Seurat workflow, the KNN graph is constructed using transcriptional similarity in PCA space, rather than physical distance within the tissue.

Both results are useful. Expression-based clusters are generally more suitable for identifying cell types or states, whereas spatial domains are more suitable for characterizing tissue architecture.

2.3 How does BANKSY work?

BANKSY incorporates the transcriptional profile of each bin or cell together with information derived from its spatial neighbours. It constructs an augmented feature matrix for dimensionality reduction and clustering.

The parameter lambda controls the contribution of spatial neighbourhood information.

The following interactive example illustrates this principle.

Typical starting parameters:

Parameter Cell typing Spatial domain detection
lambda 0.2 0.8
k_geom 15 15
Number of PCs 30 30
Clustering resolution 0.5–1.0 0.3–0.8

These are starting values rather than universal optimal settings. Neighbourhood size should also reflect bin resolution, tissue morphology and the desired spatial scale.

2.4 R example: spatial domain detection per sample

Input: QC-filtered, normalized gene expression and spatial coordinates from Space Ranger.

The following example uses Seurat v5 and BANKSY with Visium HD 8 µm bins.

# Install packages if needed
BiocManager::install("Banksy")
remotes::install_github("satijalab/seurat-wrappers")

library(Seurat)
library(SeuratWrappers)
library(Banksy)
library(ggplot2)

set.seed(123)

# 1. Load Space Ranger output
obj <- Load10X_Spatial(
    data.dir = "Sample1/outs",
    bin.size = 8,
    slice = "Sample1"
)

assay_name <- "Spatial.008um"
DefaultAssay(obj) <- assay_name

# 2. QC filtering
# Illustrative thresholds; adjust based on QC distributions
obj <- subset(
    obj,
    subset = nCount_Spatial.008um >= 100 &
             nFeature_Spatial.008um >= 50
)

# 3. Normalize gene expression
obj <- NormalizeData(obj)

# 4. Select highly variable genes
obj <- FindVariableFeatures(obj, nfeatures = 2000)

# 5. Construct BANKSY feature matrix
obj <- RunBanksy(
    obj, assay = assay_name, slot = "data",
    features = "variable", lambda = 0.8,
    k_geom = 15, verbose = TRUE
)

# 6. PCA using BANKSY features
DefaultAssay(obj) <- "BANKSY"
obj <- RunPCA(
    obj, assay = "BANKSY",
    features = rownames(obj[["BANKSY"]]),
    reduction.name = "pca.banksy", npcs = 30
)

# 7. Construct KNN graph
obj <- FindNeighbors(obj, reduction = "pca.banksy", dims = 1:30)

# 8. Spatial domain clustering
obj <- FindClusters(obj, resolution = 0.5,
                    cluster.name = "spatial_domain")

# 9. Visualize spatial domains
DefaultAssay(obj) <- assay_name
SpatialDimPlot(obj, group.by = "spatial_domain", label = TRUE)

# 10. Save results
saveRDS(obj, "Sample1_BANKSY.rds")

This follows the approach described in the official Seurat Visium HD analysis tutorial.

Notice that we do not use the previously generated standard PCA or UMAP embeddings as BANKSY input. BANKSY generates its own feature representation and PCA.

2.5 What are the outputs?

The primary output is a domain annotation table.

Example output — simulated values

Barcode Sample X Y Spatial domain
Bin_001 S1 8 8 D1
Bin_002 S1 8 16 D1
Bin_003 S1 16 8 D2
Bin_004 S1 16 16 D2
Bin_005 S1 24 8 D3

Additional analysis can then be performed to characterize these domains.

# Use original normalized gene expression,
# NOT the BANKSY augmented feature matrix
DefaultAssay(obj) <- "Spatial.008um"
Idents(obj) <- "spatial_domain"

# Identify domain-associated marker genes
domain_markers <- FindAllMarkers(
    obj, only.pos = TRUE, min.pct = 0.1,
    logfc.threshold = 0.25
)

# Number of bins in each domain
table(obj$spatial_domain)

# Relative abundance of each domain
prop.table(table(obj$spatial_domain))

These marker genes are useful for exploratory domain characterization. Their bin-level statistical significance should not be interpreted as independent biological replication.

Example domain characterization

Domain Representative markers Possible identity
D1 EPCAM, KRT19 Tumour epithelium
D2 VIM, MMP2 Invasive boundary
D3 COL1A1, DCN Stroma
D4 CD3D, CD8A Immune-enriched
D5 Tissue-specific genes Normal tissue

Hypothetical annotations. Histology, cell-type composition and additional markers are needed to confirm domain identities.

3. Spatially variable genes (SVGs)

3.1 What is a spatially variable gene?

A spatially variable gene is a gene whose expression distribution is associated with physical location within a tissue.

Importantly, a gene can have highly variable expression without being spatially variable.

For example, in tumour tissue, different genes may display different spatial patterns.

3.2 Highly variable genes vs spatially variable genes vs differentially expressed genes

HVGs SVGs DEGs
Full name Highly variable genes Spatially variable genes Differentially expressed genes
Detects High expression variability Spatially structured expression Expression differences between groups
Uses spatial coordinates No Yes Not usually
Requires predefined groups No No Yes
Common method Seurat VST Moran’s I, SPARK-X Wilcoxon, DESeq2, edgeR
Main purpose Feature selection for clustering Discover spatial patterns Characterize differences

SVG detection can identify spatial expression patterns without first defining cell types or spatial domains.

Therefore, spatial domain detection and SVG detection can be performed independently in parallel.

3.3 How does Moran’s I work?

Moran’s I measures spatial autocorrelation: whether neighbouring locations tend to have similar expression values.

\[ I=\frac{N}{W}\frac{\sum_i\sum_j w_{ij}(x_i-\bar{x})(x_j-\bar{x})}{\sum_i(x_i-\bar{x})^2} \]

Where:

Parameter Meaning
\(N\) Number of bins or cells
\(x_i\) Expression of the gene in bin \(i\)
\(\bar{x}\) Mean expression of the gene
\(w_{ij}\) Spatial weight between bins \(i\) and \(j\)
\(W\) Sum of all spatial weights

The key idea is to compare the expression of spatial neighbours.

A high positive Moran’s I indicates that bins with similar expression levels tend to be located close to one another. It does not, by itself, establish statistical significance.

3.4 R example: SVG detection using Moran’s I

Input: Normalized or scaled gene expression and physical coordinates from one tissue section.

Seurat’s spatial workflow supports Moran’s I using FindSpatiallyVariableFeatures().

library(Seurat)
DefaultAssay(obj) <- "Spatial.008um"

# 1. Identify candidate genes
obj <- FindVariableFeatures(obj, nfeatures = 2000)
genes <- VariableFeatures(obj)

# 2. Scale candidate gene expression
obj <- ScaleData(obj, features = genes)

# 3. Identify spatially variable genes
obj <- FindSpatiallyVariableFeatures(
    obj, assay = "Spatial.008um", layer = "scale.data",
    features = genes, selection.method = "moransi"
)

# 4. Extract ranked SVGs
svg_genes <- SpatiallyVariableFeatures(
    obj, assay = "Spatial.008um", selection.method = "moransi"
)
head(svg_genes, 10)

# 5. Visualize top SVGs
SpatialFeaturePlot(obj, features = head(svg_genes, 6), ncol = 3)

# 6. Export feature-level results
svg_results <- obj[["Spatial.008um"]][[]]
write.csv(svg_results, "Sample1_MoransI_results.csv")

Restricting the analysis to HVGs reduces computational cost but can miss spatially patterned genes with low overall variability. For comprehensive discovery, use an expression-prevalence filter and test a broader gene set where computationally feasible.

Visium HD consideration: Seurat’s Moran’s I implementation can encounter substantial memory and matrix-size limitations for large numbers of bins. For full-resolution Visium HD sections, SPARK-X or a suitable sparse spatial-graph implementation is generally a better starting point than constructing dense pairwise distance matrices.

3.5 Alternative: SPARK-X for large Visium HD datasets

SPARK-X uses statistical tests based on spatial kernels to detect different types of spatial expression patterns. It is designed for large and sparse spatial transcriptomics datasets.

Unlike the preceding Seurat example, SPARK-X can directly use raw counts.

# Install SPARK
remotes::install_github("xzhoulab/SPARK")
library(SPARK)
library(Matrix)
library(Seurat)

run_sparkx <- function(obj,
                       assay = "Spatial.008um",
                       ncores = 8) {
    # 1. Raw UMI counts: genes x bins
    counts <- LayerData(obj, assay = assay, layer = "counts")

    # 2. Physical spatial coordinates
    coords <- GetTissueCoordinates(obj, image = Images(obj)[1])

    # 3. Match coordinates to count matrix
    common <- intersect(colnames(counts), rownames(coords))
    stopifnot(length(common) > 0)
    counts <- counts[, common, drop = FALSE]
    coords <- as.matrix(coords[common, c("x", "y")])

    # 4. Remove poorly detected genes
    keep <- Matrix::rowSums(counts > 0) >= 50
    counts <- counts[keep, , drop = FALSE]

    # 5. Run SPARK-X
    fit <- sparkx(count_in = counts, locus_in = coords,
                  numCores = ncores, option = "mixture")

    # 6. Extract statistical results
    res <- as.data.frame(fit$res_mtest)
    res$gene <- rownames(res)
    res
}

svg_results <- run_sparkx(obj)
write.csv(svg_results, "Sample1_SPARKX_results.csv", row.names = FALSE)

The function returns gene-level combined P-values and multiple-testing-adjusted P-values.

Check the coordinate column names in your Seurat image object before running the function, as they can differ between object types.

3.6 What are the outputs?

Typical downstream applications include pathway enrichment of SVGs, identification of spatial expression gradients, discovery of region-specific biomarkers and analysis of spatially organized immune responses.

4. Per-sample vs joint-sample analysis

This is particularly important when analysing multiple Visium HD samples. Unlike standard scRNA-seq analysis, each tissue section has its own independent physical coordinate system.

4.1 Why can’t we simply merge all spatial coordinates?

For example, coordinates (100, 200) in Sample 1 and Sample 2 do not represent the same physical tissue location.

The correct strategy is to preserve each tissue section’s spatial neighbourhood structure.

5. Joint-sample spatial domain detection

Suppose there are six Visium HD samples: three controls and three disease samples.

If BANKSY is run separately, domain 1 in one sample may represent a different biological structure from domain 1 in another sample.

Joint clustering helps establish a consistent set of spatial domain labels.

5.1 Correct joint-sample BANKSY workflow

The important distinction is that spatial neighbourhood features are calculated within each sample, while PCA and clustering are performed jointly across samples. This strategy is supported by BANKSY’s multi-sample workflow.

5.2 R example: joint-sample BANKSY

library(Seurat)
library(SeuratWrappers)
library(Banksy)

sample_ids <- c("Ctrl1", "Ctrl2", "Ctrl3", "Dis1", "Dis2", "Dis3")
assay_name <- "Spatial.008um"

# 1. Per-sample preprocessing
obj_list <- lapply(sample_ids, function(id) {
    obj <- Load10X_Spatial(
        data.dir = file.path(id, "outs"), bin.size = 8, slice = id
    )
    DefaultAssay(obj) <- assay_name
    obj$sample_id <- id
    obj$condition <- ifelse(grepl("^Ctrl", id), "Control", "Disease")
    obj <- subset(obj, subset = nCount_Spatial.008um >= 100 &
                                nFeature_Spatial.008um >= 50)
    obj <- NormalizeData(obj)
    obj <- FindVariableFeatures(obj, nfeatures = 2000)
    obj
})
names(obj_list) <- sample_ids

# 2. Select common analysis features
features <- SelectIntegrationFeatures(object.list = obj_list, nfeatures = 2000)

# 3. Merge all samples
joint <- merge(x = obj_list[[1]], y = obj_list[-1],
               add.cell.ids = sample_ids, merge.data = TRUE)
joint <- JoinLayers(joint, assay = assay_name)

# 4. Sample-aware BANKSY feature construction
joint <- RunBanksy(
    joint, assay = assay_name, slot = "data", features = features,
    lambda = 0.8, k_geom = 15, group = "sample_id",
    split.scale = TRUE, verbose = TRUE
)
# group = "sample_id" ensures that spatial
# neighbourhood calculations respect sample boundaries

# 5. Joint PCA
DefaultAssay(joint) <- "BANKSY"
joint <- RunPCA(joint, assay = "BANKSY",
                features = rownames(joint[["BANKSY"]]),
                reduction.name = "pca.banksy", npcs = 30)

# 6. Joint clustering
joint <- FindNeighbors(joint, reduction = "pca.banksy", dims = 1:30)
joint <- FindClusters(joint, resolution = 0.5, cluster.name = "spatial_domain")

# 7. Joint UMAP
joint <- RunUMAP(joint, reduction = "pca.banksy", dims = 1:30,
                 reduction.name = "umap.banksy")

# 8. Visualize shared domains
DimPlot(joint, reduction = "umap.banksy", group.by = "spatial_domain",
        split.by = "condition")

# 9. Visualize domains in individual tissues
DefaultAssay(joint) <- assay_name
SpatialDimPlot(joint, group.by = "spatial_domain", ncol = 3)

The group and split.scale parameters allow sample-aware neighbourhood calculations and group-specific feature scaling, respectively.

Batch correction, such as Harmony, can optionally be applied to the BANKSY PCA embeddings before joint clustering. However, avoid removing genuine disease-associated differences through excessive integration.

5.3 Downstream analysis: differential spatial domain abundance

After obtaining shared spatial domains, we can investigate whether the tissue architecture differs between control and disease samples.

library(dplyr)
library(ggplot2)

domain_prop <- joint[[]] |>
    count(sample_id, condition, spatial_domain) |>
    group_by(sample_id) |>
    mutate(proportion = n / sum(n)) |>
    ungroup()

ggplot(domain_prop, aes(x = sample_id, y = proportion, fill = spatial_domain)) +
    geom_col() +
    facet_grid(~condition, scales = "free_x", space = "free_x") +
    theme_classic()

For equal-sized Visium HD bins, these proportions approximate the relative coverage of retained tissue bins, rather than the proportion of cells.

For formal statistical comparisons, the biological sample or patient—not each individual bin—should be treated as the independent replicate. Multiple sections from the same patient also need to be accounted for.

6. Multi-sample SVG analysis

6.2 Example of cross-sample SVG results

Gene Potential interpretation
EPCAM Conserved spatial organization across conditions
COL1A1 Conserved stromal organization
CXCL13 Increased spatial organization of immune-associated expression in disease
CA9 Disease-associated localized expression
CD8A Reduced spatial autocorrelation in disease
ACTB Weak spatial autocorrelation in both conditions

Notice that increased Moran’s I does not necessarily mean increased average expression.

For example, CXCL13 might have the same average expression in both conditions but become concentrated in specific immune hotspots in disease tissue.

6.3 R example: identify reproducible SVGs across samples

Using the run_sparkx() function defined earlier:

library(dplyr)
library(tidyr)

# 1. Run SVG detection separately
svg_list <- lapply(names(obj_list), function(id) {
    result <- run_sparkx(obj_list[[id]])
    result$sample_id <- id
    result$condition <- ifelse(grepl("^Ctrl", id), "Control", "Disease")
    result
})

# 2. Combine gene-level results
svg_all <- bind_rows(svg_list)

# 3. Define significant SVGs
svg_all <- svg_all |> mutate(significant = adjustedPval < 0.05)

# 4. Summarize reproducibility
svg_summary <- svg_all |>
    group_by(gene, condition) |>
    summarise(n_tested = n_distinct(sample_id),
              n_significant = sum(significant),
              reproducibility = n_significant / n_tested,
              .groups = "drop")

# 5. Identify reproducible SVGs
reproducible_svg <- svg_summary |>
    filter(n_tested == 3, n_significant >= 2)

# 6. Compare conditions
svg_comparison <- svg_summary |>
    select(gene, condition, n_significant) |>
    pivot_wider(names_from = condition, values_from = n_significant)

# 7. Candidate disease-associated SVGs
disease_svg <- svg_comparison |>
    filter(Disease >= 2, Control == 0)

This identifies candidate genes with reproducible spatial patterns. It does not constitute a formal test of differential spatial variability.

A gene being significant in disease but not significant in control does not automatically mean that its spatial variability is significantly different between conditions.

For formal comparisons, calculate comparable sample-level spatial effect sizes and test differences across biological replicates, or use an appropriate multi-sample spatial statistical model.

7. What biological level should be used?

Spatial variability can arise from different biological processes. Therefore, the level of analysis should depend on the research question.

Scenario Input data Purpose
Whole tissue SVG All QC-passed bins/cells Overall tissue organization
Tumour-specific SVG Tumour domain or malignant cells Intratumour spatial heterogeneity
Immune-specific SVG Annotated immune cells or carefully selected immune-enriched bins Local immune activation and exhaustion
Domain marker identification Expression + domain labels Molecular characterization
Cell-type distribution Cell-type abundance or deconvolution scores + coordinates Spatial localization of cell populations

Example: tumour-specific SVG analysis

# Assume spatial domains have been biologically annotated
tumour <- subset(obj, subset = domain_annotation == "Tumour")
DefaultAssay(tumour) <- "Spatial.008um"

# Re-select features within the tumour region
tumour <- FindVariableFeatures(tumour, nfeatures = 2000)
tumour <- ScaleData(tumour, features = VariableFeatures(tumour))
tumour <- FindSpatiallyVariableFeatures(
    tumour, assay = "Spatial.008um", layer = "scale.data",
    features = VariableFeatures(tumour), selection.method = "moransi"
)
tumour_svg <- SpatiallyVariableFeatures(tumour, selection.method = "moransi")

The spatial neighbourhood structure should be recalculated after subsetting, while avoiding artificial connections across large tissue gaps.

For Visium HD, a bin annotated as CD8-enriched is not necessarily a pure CD8+ T cell. Cell segmentation, reference-based annotation or deconvolution should be considered when interpreting cell-type-specific SVGs.

8. Which data representation should be used?

This table summarizes the required data at each stage.

Analysis step Raw counts Normalized expression Scaled expression Embeddings Coordinates
QC filtering ✓ Optional
Normalization ✓
HVG selection (VST) ✓
Standard PCA ✓
Standard clustering ✓
Cell-type annotation Method-dependent ✓ Method-dependent Optional
BANKSY feature construction ✓ ✓
BANKSY PCA Augmented features
Spatial domain clustering BANKSY PCA
SVG: Moran’s I ✓ ✓ ✓
SVG: SPARK-X ✓ ✓
Domain marker detection Method-dependent ✓
Pseudobulk DEG ✓
Spatial feature visualization ✓ Optional ✓

Important: Do not use integrated expression values, UMAP coordinates or standard PCA embeddings as the default input for gene-level SVG detection. SVG detection needs gene-level measurements and actual tissue coordinates.

8.1 Which Visium HD bin resolution should be used?

Resolution Characteristics Recommended application
2 µm Very high resolution, extremely sparse Cell segmentation, specialized subcellular analysis
8 µm Higher spatial detail, increased computational requirements Spatial domains, localized SVGs, cell-type-enriched regions
16 µm More aggregated expression, lower spatial resolution Initial exploration, broad domains and scalable SVG analysis
Segmented cells Cell-associated transcript counts Cell-type-specific spatial analyses

I would use 8 µm bins as the primary starting resolution and 16 µm bins for initial exploration or computationally intensive analyses. Compare results across resolutions when possible.

The chosen resolution also changes the physical scale of the neighbourhood used by BANKSY.

10. How to integrate the results biologically

Consider a cancer study comparing control and disease tissue.

Analysis Hypothetical finding Biological implication
Standard clustering Similar immune cell types in both conditions Broadly conserved cell populations
Spatial domain detection Expanded tumour domain Tissue architecture remodeling
Cell-type spatial distribution CD8+ T cells concentrated at the tumour boundary Potential immune exclusion
Whole-tissue SVG CXCL13 exhibits stronger spatial autocorrelation Localized immune-associated expression
Cell-type-specific SVG Spatially patterned exhaustion-associated genes in CD8+ cells Potential location-dependent immune state
Domain-specific DEG Increased hypoxia-associated genes in tumour core Microenvironment-associated transcriptional changes

Together, these analyses provide a much more complete biological interpretation than standard expression-based clustering alone.

11. Summary

Spatial domain Spatially variable genes
Recommended tool BANKSY Moran’s I / SPARK-X
Analysis unit Bin, spot or cell Gene
Input Normalized expression + coordinates Raw or normalized expression + coordinates
Per-sample step Spatial neighbourhood calculation Spatial statistical testing
Joint-sample step Shared PCA and clustering Reproducibility and condition comparison
Primary output Domain labels Spatial statistics and/or significance
Main visualization Spatial domain map Spatial gene expression map
Biological purpose Understand tissue architecture Understand spatial molecular organization

The key distinction:

  • Standard clustering tells you what cells or transcriptional states are present.
  • Spatial domain analysis tells you how the tissue is organized.
  • SVG analysis tells you which genes contribute to spatial molecular patterns.
  • Cross-sample analysis tells you how these spatial characteristics differ between biological conditions.
Back to top