Map expression and compare cluster fits
Expression clusters group spots with similar transcript profiles. Their labels do not identify cells, anatomical layers, or independent samples. This example fits the expression graph without tissue coordinates and then returns the labels to the image, so physical adjacency remains a separate observation. One mouse supplies the section; its cluster labels do not change that experimental unit.
The two fits share their input counts, retained spots, variable gene identifiers,
normalization, component count, and requested neighbor count. Seurat selects
the variable genes with vst before either spatial statistic is calculated.
Python reads that exported feature list instead of selecting a different set.
Normalization precedes feature exclusion, so both fits use the complete spot
totals as their denominators.
State the method differences
Section titled “State the method differences”| Setting | Seurat | Scanpy |
|---|---|---|
| Eligible features | Genes detected in at least three spots | The same eligibility rule |
| Selected features | 2,000 genes from Seurat vst |
The exported Seurat identifiers |
| Transformation | log1p counts per 10,000 |
The same transformation |
| Scaling | Centered and scaled without clipping | Centered and scaled without clipping |
| PCA | 30 components with IRLBA | 30 components with ARPACK |
| Expression graph | Annoy neighbors and a pruned shared-neighbor graph | Euclidean neighbors and UMAP connectivity weights |
| Requested neighbors | 15 | 15 |
| Community fit | Leiden modularity through R igraph | Leiden modularity through Python igraph |
| Resolution and seed | 0.5 and 20261031 |
0.5 and 20261031 |
The Seurat clustering documentation and Scanpy Leiden documentation describe their graph and community choices. The same numeric settings do not make their neighbor graphs identical. The comparison therefore reports an adjusted Rand index and a complete overlap table rather than requiring matching cluster numbers.
source("/shared/spatial_utils.R")suppressPackageStartupMessages(library(Seurat))data <- ReadSection()counts <- data$countseligible <- rowSums(counts > 0) >= 3object <- CreateSeuratObject(counts, min.cells = 0, min.features = 0)object <- NormalizeData(object, scale.factor = 10000, verbose = FALSE)object <- subset(object, features = rownames(counts)[eligible])object <- FindVariableFeatures(object, selection.method = "vst", nfeatures = 2000, verbose = FALSE)features <- VariableFeatures(object)stopifnot(length(features) == 2000, !anyDuplicated(features))object <- ScaleData(object, features = features, scale.max = Inf, verbose = FALSE)object <- RunPCA(object, features = features, npcs = 30, seed.use = 20261031, verbose = FALSE)object <- FindNeighbors(object, dims = 1:30, k.param = 15, nn.method = "annoy", n.trees = 50, prune.SNN = 1 / 15, verbose = FALSE)object <- FindClusters(object, algorithm = 4, leiden_method = "igraph", leiden_objective_function = "modularity", resolution = 0.5, n.iter = 10, random.seed = 20261031, verbose = FALSE)clusters <- as.character(Idents(object))stopifnot(identical(names(Idents(object)), data$barcodes))dir.create("outputs", showWarnings = FALSE)write.table(data.frame(feature_id = features), "outputs/variable_features.tsv", sep = "\t", quote = FALSE, row.names = FALSE)write.table(data.frame(barcode = data$barcodes, cluster = clusters), "outputs/clusters_r.tsv", sep = "\t", quote = FALSE, row.names = FALSE)normalized <- NormalizeCounts(counts)panel <- PanelIndices(data$features)png("outputs/expression_r.png", width = 1800, height = 650, res = 150)par(mfrow = c(1, 3), mar = c(4, 4, 3, 1))DrawSpatial(data, as.numeric(normalized[panel[1], ]), "Slc17a7 expression")DrawSpatial(data, as.numeric(normalized[panel[4], ]), "Mbp expression")DrawSpatial(data, as.numeric(clusters), "Seurat expression clusters", categorical = TRUE)invisible(dev.off())WriteMetrics(list(spots = ncol(counts), features = length(features), components = 30, clusters = length(unique(clusters))))cat(sprintf("Seurat fits %d expression clusters across %d spots.\n", length(unique(clusters)), ncol(counts)))cat(sprintf("Both fits use the same %d selected feature identifiers.\n", length(features)))Seurat fits 15 expression clusters across 2695 spots.Both fits use the same 2000 selected feature identifiers.
Gene colors show log1p counts per 10,000 UMIs. Cluster colors represent
expression groups within this section and carry no cell type assignment.
import sys
import anndata as adimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport scanpy as scfrom sklearn.metrics import adjusted_rand_score
sys.path.insert(0, "/shared")import spatial_utils as spatial
data = spatial.read_section()counts = data["counts"]features = pd.read_csv("outputs/variable_features.tsv", sep="\t")selected = features["feature_id"].tolist()feature_index = pd.Index(data["features"]["feature_id"]).get_indexer(selected)assert len(selected) == 2000 and len(set(selected)) == 2000assert np.all(feature_index >= 0)assert np.all(np.asarray((counts[feature_index] > 0).sum(axis=1)) >= 3)normalized = spatial.normalize_counts(counts)expression = ad.AnnData(normalized[feature_index].T.toarray())expression.obs_names = data["barcodes"]expression.var_names = selectedsc.pp.scale(expression, zero_center=True, max_value=None)sc.tl.pca(expression, n_comps=30, svd_solver="arpack", random_state=20261031)sc.pp.neighbors(expression, n_neighbors=15, n_pcs=30, method="umap", metric="euclidean", random_state=20261031)sc.tl.leiden(expression, resolution=0.5, random_state=20261031, flavor="igraph", directed=False, n_iterations=10, objective_function="modularity")clusters = expression.obs["leiden"].astype(str).to_numpy()reference = pd.read_csv("outputs/clusters_r.tsv", sep="\t", dtype=str)assert reference["barcode"].tolist() == data["barcodes"].tolist()agreement = adjusted_rand_score(reference["cluster"], clusters)overlap = pd.crosstab(reference["cluster"], pd.Series(clusters, name="Scanpy"))overlap.to_csv("outputs/cluster_overlap.tsv", sep="\t")pd.DataFrame(dict(barcode=data["barcodes"], cluster=clusters)).to_csv( "outputs/clusters_python.tsv", sep="\t", index=False,)panel = spatial.panel_indices(data["features"])fig, axes = plt.subplots(1, 3, figsize=(17, 5))spatial.draw_spatial(axes[0], data, normalized[panel[0]].toarray().ravel(), "Slc17a7 expression")spatial.draw_spatial(axes[1], data, normalized[panel[3]].toarray().ravel(), "Mbp expression")spatial.draw_spatial(axes[2], data, clusters.astype(int), "Scanpy expression clusters", categorical=True)fig.tight_layout()fig.savefig("outputs/expression_python.png", dpi=150, bbox_inches="tight")plt.close(fig)fig, ax = plt.subplots(figsize=(7, 6))image = ax.imshow(overlap.to_numpy(), cmap="Blues", aspect="auto")ax.set_xticks(range(overlap.shape[1]), overlap.columns)ax.set_yticks(range(overlap.shape[0]), overlap.index)ax.set(xlabel="Scanpy cluster", ylabel="Seurat cluster", title=f"Cluster overlap, adjusted Rand index = {agreement:.3f}")fig.colorbar(image, ax=ax, label="Shared spots")fig.savefig("outputs/cluster_overlap.png", dpi=160, bbox_inches="tight")plt.close(fig)spatial.write_metrics(dict(spots=counts.shape[1], features=len(selected), components=30, clusters=len(set(clusters)), adjusted_rand=agreement))print(f"Scanpy fits {len(set(clusters))} expression clusters " f"across {counts.shape[1]} spots.")print(f"The adjusted Rand index is {agreement:.6f}.")print(overlap.to_string(index_names=False))Scanpy fits 15 expression clusters across 2695 spots.The adjusted Rand index is 0.851585. 0 1 10 11 12 13 14 2 3 4 5 6 7 8 91 0 0 0 0 0 0 1 0 0 1 0 0 500 1 010 0 0 0 0 0 0 0 0 130 0 0 0 0 0 011 0 0 125 0 0 0 0 0 0 0 0 0 0 0 012 0 0 0 0 0 0 0 0 0 0 0 74 1 0 013 0 0 0 0 24 0 36 0 0 0 0 0 0 5 014 0 0 0 0 0 0 0 0 2 0 0 0 0 0 3515 0 32 0 0 0 0 0 0 0 0 0 0 0 0 02 0 0 0 124 0 0 0 291 0 0 0 0 0 0 03 0 0 32 3 0 234 0 0 0 0 0 0 0 1 04 0 0 0 228 0 3 0 0 0 0 0 0 0 0 05 1 0 3 0 0 0 0 1 0 0 195 1 0 1 06 2 0 0 0 0 0 0 0 0 0 1 0 0 165 07 1 0 3 0 0 0 0 0 0 156 0 1 0 0 08 0 138 0 0 0 0 0 0 5 0 2 0 0 0 09 134 0 0 0 0 0 0 0 0 1 0 0 0 1 0
The Python fit uses the exported Seurat feature list, but it calculates its own principal components, expression neighbors, and cluster labels. The printed overlap table uses Seurat clusters as rows and Scanpy clusters as columns.

Each cell counts shared spots. The adjusted Rand index compares partitions without assuming that the cluster numbers have the same meaning.
The tissue images are supplied by 10x Genomics under CC BY 4.0. These figures add expression and cluster overlays. No archived provider cluster assignments enter either fresh fit.
Spatially coherent clusters can reflect anatomy, cell composition, technical variation, or a combination of these factors. The maps do not distinguish those explanations by themselves. The graph lesson defines physical neighbors independently of this expression fit.
Scientific references
Section titled “Scientific references”Hao and colleagues, 2023 describe the Seurat methods for integrative, multimodal, and scalable single-cell analysis.
Wolf, Angerer, and Theis, 2018 describe Scanpy, the Python toolkit for large-scale single-cell expression analysis.
Further reading
Section titled “Further reading”The Scanpy 1.11 Leiden reference documents resolution, partition options, and the random state. The man/FindClusters.Rd reference in the Seurat 5.6.0 source package describes its Leiden option and clustering objective. Compare those definitions with the method table before interpreting agreement between the two fits.