Spatial-segmented data with SpatialExperiment and RGraphSpace
Sysbiolab Team
2026-12-02
Source:vignettes/articles/spatial-segmentation2.Rmd
spatial-segmentation2.RmdPackages: RGraphSpace 1.5.8.1; RGraphSpaceExperiment 0.1.2
Overview
This vignette demonstrates how RGraphSpace renders sf features using spatial-segmented data pre-processed with the SpatialExperiment package (Righelli et al. 2022) and OSTA (Dong et al. 2026). We will use a high-definition spatial transcriptomic dataset generated by Oliveira et al. (2025). This dataset consists of Visium HD spatial gene expression data from formalin-fixed paraffin-embedded (FFPE) human colorectal cancer (CRC) tissue, profiled at single-cell scale resolution (2-µm barcoded capture features) with matched cell segmentation boundaries derived from paired histology imaging.
Before you start
This vignette assumes familiarity with SpatialExperiment (Righelli et al. 2022), particularly for handling Visium HD spatial transcriptomics data.
Note: If you are new to SpatialExperiment, we recommend reviewing the OSTA’s Visium HD Workflow before proceeding.
Computational requirements:
Hardware: Workstation with RAM ≥ 32 GB for large datasets
Software: R (≥4.5); RStudio recommended
Required packages
Before proceeding, ensure that all packages described in the Installation Instructions are installed.
# Check versions
if (packageVersion("RGraphSpace") < "1.5.8"){
message("Need to update 'RGraphSpace' for this vignette")
remotes::install_github("sysbiolab/RGraphSpace")
}
if (!requireNamespace("RGraphSpaceExperiment", quietly = TRUE)){
remotes::install_github("sysbiolab/RGraphSpaceExperiment")
}Setting input data
# Load packages
library("RGraphSpaceExperiment")
library("SpatialExperiment")
library("OSTA.data")
library("VisiumIO")
library("patchwork")
library("scrapper")
library("SingleR")
library("sf")Loading the dataset
The original Visium HD dataset is available from the 10x
Genomics repository. For convenience, we retrieve this dataset from
the Open Science Framework (OSF) repository using OSTA, then load it
into a SpatialExperiment.
# Set a temporary directory for download
id <- "VisiumHD_HumanColon_Oliveira"
dir.create(td <- tempfile())
# Retrieve data from OSF repo
unzip(OSTA.data_load(id), exdir = td)
# Read into 'SpatialExperiment'
fpath <- file.path(td, "segmented_outputs")
spe <- TENxVisiumHD(
segmented_outputs = fpath,
format = "h5",
images = "hires") |>
import()
# Assign unique symbols to rownames
rownames(spe) <- make.unique(rowData(spe)$Symbol)
# Optionally, keep the counts in memory for faster processing
counts(spe) <- as(counts(spe), "dgCMatrix")
# Optionally, load the physical scale of node coordinates
# directly from Space Ranger, to set the physical unit below
fpath <- file.path(fpath, "spatial", "scalefactors_json.json")
metadata(spe)$scalefactors <- jsonlite::fromJSON(fpath)Prepare cell geometries
This spe object has cell outlines, stored as polygon
geometries in metadata(), a free-form list that is not tied
to the cells. We will add these geometries to colData(),
aligned with the cells, so that each outline stays with its cell when
the object is subset or reordered, and the outlines become available as
cell data.
# Cell outlines, stored in metadata
cellseg <- metadata(spe)$cellseg
# One outline per cell, in column order
cellseg <- cellseg$geometry[match(colnames(spe), cellseg$cell_id)]
# Repair invalid outlines
cellseg <- sf::st_make_valid(cellseg)
# Add to colData()
spe$cellseg <- cellsegAt this point, OSTA
provides several pre-processing recommendations, including converting to
a SpatialFeatureExperiment, spatially-aware quality
control, and cell type annotation. These are general best practices for
preparing spatial data, already thoroughly demonstrated in the OSTA
workflow itself. Here, we apply only a basic quality control and
annotation, and focus on a possible downstream application using
RGraphSpace to manipulate and visualize the segmented data
directly.
Creating a GraphSpaceExperiment object
Create a GraphSpaceExperiment from the
SpatialExperiment. The object keeps the Bioconductor data
(assays, colData()) and adds the spatial graph used by
RGraphSpace. The tissue image, its scale factor and the cell
outlines in colData() are imported along with it.
# Create a GraphSpaceExperiment from the SpatialExperiment
gse <- GraphSpaceExperiment(spe)Set the scale factor
The hires image is imported with its scale factor. The
node coordinates refer to the original full-resolution image, which is
not included in the download; the scale factor, from
scaleFactors(), rescales them to fit the hires
image. If the image was not loaded with the data, it can be added at
this point:
# gs_image(gse) <- SpatialExperiment::imgRaster(spe, image_id = "hires")
# gs_scale_factor(gse) <- scaleFactors(spe, image_id = "hires")Set the physical unit
Optionally, set the physical unit, used to draw scale bars. Visium HD
coordinates are provided in pixels of the full-resolution image (Space Ranger outputs), and
microns_per_pixel gives the size of one pixel in
micrometers.
# For this dataset, one coordinate unit is one full-resolution pixel
gs_coords_unit(gse) <- c(um = metadata(spe)$scalefactors$microns_per_pixel)See defining coordinate units for the general rule.
Annotate and cluster cells
We first remove low-quality cells and log-normalize the counts. Each cell is then labelled with the most similar cell type of a matched single-cell reference from the same study (Oliveira et al. 2025), using SingleR. For other annotation strategies, see the OSTA annotation workflow.
Show the annotation steps
# Quality control: remove cells with outlying metrics
qc <- computeRnaQcMetrics(counts(gse),
subsets = list(mito = grepl("^MT-", rownames(gse))))
keep <- filterRnaQcMetrics(suggestRnaQcThresholds(qc), qc)
gse <- gse[, keep]
# Log-normalize the dataset
size.factors <- centerSizeFactors(Matrix::colSums(counts(gse)))
logcounts(gse) <- normalizeCounts(counts(gse), size.factors)The reference is single-cell data (Chromium) from the same study, annotated by the authors at two levels of detail. Only cells from the same patient as this tissue section (P2) are kept.
# Retrieve annotation dataset from OSF repo
id <- "Chromium_HumanColon_Oliveira"
pa <- OSTA.data_load(id)
dir.create(td <- tempfile())
unzip(pa, exdir=td)
# Read into 'SingleCellExperiment'
fs <- list.files(td, full.names=TRUE)
h5 <- grep("h5$", fs, value=TRUE)
sce_ref <- DropletUtils::read10xCounts(h5, col.names=TRUE)
# Use gene symbols as feature names
rownames(sce_ref) <- make.unique(rowData(sce_ref)$Symbol)
# Add cell metadata
csv <- grep("csv$", fs, value=TRUE)
cd <- read.csv(csv, row.names=1)
colData(sce_ref)[names(cd)] <- cd[colnames(sce_ref), ]
# Exclude cells deemed to be of low-quality
sce_ref <- sce_ref[, sce_ref$QCFilter == "Keep"]
# Keep cells from same patient ("P2" sample)
sce_ref <- sce_ref[, grepl("P2", sce_ref$Patient)]
# Optionally, keep the counts in memory for faster processing
counts(sce_ref) <- as(counts(sce_ref), "dgCMatrix")
# Log-normalize the reference
size.factors <- centerSizeFactors(Matrix::colSums(counts(sce_ref)))
logcounts(sce_ref) <- normalizeCounts(counts(sce_ref), size.factors)Each cell of gse is labelled with the most similar
reference cell type, at both levels: coarse cell types
(Level1, including tumor cells) and more detailed subtypes
(Level2). Cells without a confident match are labelled
“Unassigned”.
# Coarse cell types (Level1)
pred_level1 <- SingleR::SingleR(test = gse,
ref = sce_ref, labels = sce_ref$Level1,
de.method = "wilcox", aggr.ref = TRUE,
aggr.args = list(ncenters = 20))
pred_level1$pruned.labels[is.na(pred_level1$pruned.labels)] <- "Unassigned"
gse$celltype <- factor(pred_level1$pruned.labels)
# Detailed cell types (Level2)
pred_level2 <- SingleR::SingleR(test = gse,
ref = sce_ref, labels = sce_ref$Level2,
de.method = "wilcox", aggr.ref = TRUE,
aggr.args = list(ncenters = 20))
pred_level2$pruned.labels[is.na(pred_level2$pruned.labels)] <- "Unassigned"
gse$celltype_detailed <- factor(pred_level2$pruned.labels)
table(gse$celltype)
#> B cells Endothelial Fibroblast Intestinal Epithelial
#> 14550 9308 36374 16718
#> Myeloid Neuronal Smooth Muscle T cells
#> 18802 285 10879 5167
#> Tumor Unassigned
#> 99017 961 The clustering step is optional: none of the plots below use clusters, and the ROI provided for downstream analysis already includes them.
Show the clustering steps
# Highly variable genes and PCA on them
gene.var <- modelGeneVariances(logcounts(gse))
hvgs <- chooseHighlyVariableGenes(gene.var$statistics$residuals)
gse <- runPca.se(gse, features = hvgs)
# Build a cellular shared nearest-neighbor (SNN) graph,
# and cluster it with the Leiden community detection algorithm
gse <- clusterGraph.se(gse, reddim.type = "PCA", method = "leiden")
# UMAP of the PCA, stored as reducedDim(gse, "UMAP")
gse <- runUmap.se(gse, num.threads = 8)The cells are then plotted in UMAP space, colored by cluster and by cell type, to check that clusters and labels agree.
# Cells in UMAP space, colored by cluster and by cell type
df <- data.frame(reducedDim(gse, "UMAP"),
Clusters = gse$clusters,
Celltype = gse$celltype)
colnames(df)[1:2] <- c("UMAP1", "UMAP2")
# Legends below the plots, in compact rows
umap_theme <- theme(legend.position = "bottom",
legend.title.position = "top",
legend.text = element_text(size = 7),
legend.title = element_text(size = 8),
legend.key.size = unit(0.3, "cm"),
aspect.ratio = 1)
p1 <- ggplot(df, aes(UMAP1, UMAP2, colour = Clusters)) +
geom_point(size = 0.05) + theme_minimal() + umap_theme +
guides(colour = guide_legend(ncol = 6, override.aes = list(size = 2)))
p2 <- ggplot(df, aes(UMAP1, UMAP2, colour = Celltype)) +
geom_point(size = 0.05) + theme_minimal() + umap_theme +
guides(colour = guide_legend(ncol = 3, override.aes = list(size = 2)))
p1 + p2
Normalize node coordinates
Next, we examine the spatial boundaries of the nodes relative to the image. Some coordinates in this dataset fall outside the valid image range (e.g., negative values), a known artifact of tissue sampling at subcellular resolution (2 µm), where bins can extend beyond the tissue boundaries. The OSTA workflow addresses a related issue for some operations, filtering out bins that overlay empty tissue (see the setup section). These out-of-bounds nodes must also be removed here before the graph is normalized to the image space.
gse
#> class: GraphSpaceExperiment
#> dim: 18132 212061
#> metadata(6): resouces spatialList ... scalefactors PCA
#> assays(2): counts logcounts
#> rownames(18132): SAMD11 NOC2L ... MT-ND6 MT-CYB
#> rowData names(3): ID Symbol Type
#> colnames(212061): cellid_000000003-1 cellid_000000004-1 ... cellid_000268813-1 cellid_000268814-1
#> colData names(5): map sample_id celltype celltype_detailed clusters
#> reducedDimNames(2): PCA UMAP
#> mainExpName: NULL
#> altExpNames(0):
#> + graph: 212061 nodes, 0 edges
#> + node attributes(4): x y nodeLabel nodeSize
#> + geometries(1): cellseg
#> + feature source: counts
#> + node spatial boundaries: raw graph
#> | x: [3237, 5199] (cols)
#> | y: [-1, 1810] (rows)
#> + image spatial boundaries: raw image
#> | x: [1, 6000] (cols)
#> | y: [1, 3886] (rows)
#> + scale factor: 0.07973
#> + coordinate unit: 0.2737 um
# Remove out-of-bounds nodes
gse <- gs_subset_nodes(gse, y >= 1)
# Normalize node coordinates to the image space, cropping
# the image tightly around the nodes (no margin)
gse <- normalizeGraphSpace(gse, mar = 0, equal.mar = TRUE)Overview of cell types
With cells annotated, we plot each one at its position in the tissue, colored by cell type.
# Set a reusable theme
my_theme <- theme_gspace_coords(theme = "th3", is_norm = TRUE,
xlab = "Tissue coordinates 1", ylab = "Tissue coordinates 2")
# Set cell type colors
types <- c("Tumor", "Endothelial", "Fibroblast", "Myeloid",
"B cells", "T cells", "Intestinal Epithelial", "Smooth Muscle",
"Neuronal", "Unassigned")
ct_pal <- c(palette.colors(9, "Paired"), "grey")
ct_pal <- setNames(ct_pal, types)
# Plot each node at its position in the tissue
p <- ggplot(gse) +
geom_nodespace(mapping = aes(color = celltype), size = 0.1, pch = 19) +
scale_color_manual(values = ct_pal, name = "Cell type") +
annotation_gspace_scalebar(box = TRUE) +
my_theme + theme_gspace_legend(discrete_colour = TRUE)
p
Spatial feature visualization
Next, we visualize PIGR expression across the full tissue, overlaying node markers on the tissue image. Nodes with no detectable expression are made transparent. A box indicates the region selected for closer inspection.
# Set color palette and data range for use across plots
cpal <- hcl.colors(100, palette = "Spectral", rev = TRUE)
data_range <- c(0, 7)
# Plot node-level PIGR expression over the tissue image;
# a box marks the region of interest
p <- ggplot(gse) +
annotation_gspace_image(gse, opacity = 0.5) +
geom_nodespace(mapping = aes(colour = log2(PIGR + 1),
alpha = as.numeric(PIGR > 0) ), size = 0.3, pch = 19) +
scale_colour_continuous(palette = cpal, limits = data_range) +
scale_alpha_identity() + my_theme +
annotation_gspace_scalebar() +
annotate("rect",
xmin = 0.5, xmax = 0.8,
ymin = 0.3, ymax = 0.65,
fill = NA, colour = "white",
lty = "21", lwd = 1)
p
Crop to the selected region and re-normalize the node coordinates to the new spatial extent.
# Crop the selected region and re-normalize coordinates
gse_crop1 <- cropGraphSpace(gse,
xmin = 0.5, xmax = 0.8,
ymin = 0.3, ymax = 0.65)
gse_crop1 <- normalizeGraphSpace(gse_crop1, mar = 0)We can then zoom in further to inspect a smaller region. A second box indicates the area selected for the next crop.
# Plot the cropped region; a second box marks a smaller region for a closer crop
p <- ggplot(gse_crop1) +
annotation_gspace_image(gse_crop1, opacity = 0.5) +
geom_nodespace(mapping = aes(colour = log2(PIGR + 1),
alpha = as.numeric(PIGR > 0)), size = 0.7, pch = 19) +
scale_colour_continuous(palette = cpal, limits = data_range) +
scale_alpha_identity() + my_theme +
annotation_gspace_scalebar(box = TRUE) +
annotate("rect",
xmin = 0.2, xmax = 0.5,
ymin = 0.5, ymax = 0.8,
fill = NA, colour = "white",
lty = "21", lwd = 1)
p
Crop to this smaller region to define our region of interest (ROI). Here, we also explicitly re-normalize the cell geometries, ensuring they remain aligned with the node coordinates when plotted directly in the following steps.
# Crop the selected ROI and re-normalize node coordinates and geometries
gse_roi1 <- cropGraphSpace(gse_crop1,
xmin = 0.2, xmax = 0.5,
ymin = 0.5, ymax = 0.8)
gse_roi1 <- normalizeGraphSpace(gse_roi1, mar = 0,
norm.geometry = TRUE)At this resolution, the actual cell segmentation boundaries can be overlaid on the tissue image, together with the node centroids. Their alignment illustrates the correspondence between the segmented cell geometries and the spatial coordinates represented by the nodes.
# Plot segmentation boundaries over the tissue image, with node centroids
p <- ggplot(gse_roi1) +
annotation_gspace_image(gse_roi1, opacity = 1) +
geom_sf( aes(geometry = cellseg), fill = NA,
linewidth = 0.3, colour = "cyan") +
geom_nodespace(colour = "white", size = 0.5, pch = 19) +
my_theme
p
We can now map PIGR expression directly onto the individual cell shapes. With the tissue image omitted, the segmented geometries themselves provide the spatial context, revealing expression patterns at single-cell resolution.
# Fill each segmented shape by PIGR expression
p <- ggplot(gse_roi1) +
geom_sf( aes(geometry = cellseg, fill = log2(PIGR + 1) ),
colour = "white") +
geom_nodespace(colour = "black", size = 0.1, pch = 19) +
scale_fill_continuous(palette = cpal, limits = data_range) +
annotation_gspace_scalebar(box = TRUE) +
my_theme
p
Save the region of interest
The selected GraphSpaceExperiment, gse_roi1, holds the
cells of the ROI with their assays, outlines, image and coordinates
aligned. It is saved for downstream analysis, continued in downstream analysis of a spatial region
of interest.
# Assays as in-memory matrices, so the saved file is self-contained
counts(gse_roi1) <- as(counts(gse_roi1), "dgCMatrix")
logcounts(gse_roi1) <- as(logcounts(gse_roi1), "dgCMatrix")
# If the image is a 'SpatRaster', store it as a raster
# gs_image(gse_roi1) <- as.raster(terra::as.array(gs_image(gse_roi1)), max = 255)
# Save the region of interest
save(gse_roi1, file = "gs_spatial_roi1.RData")Coercing SpatialExperiment objects
When Bioconductor classes are not needed downstream, a plain
GraphSpace can be built directly from the components of a
SpatialExperiment. This gives direct control over what is
included. Note in particular that the expression matrix is attached to a
dedicated @fdata slot via gs_fdata(), rather
than merged into the node table, keeping the high-dimensional features
available for aesthetic mapping without being treated as node
attributes.
# Extract tissue coordinates
coords <- spatialCoords(spe)
colnames(coords) <- c("x", "y")
# Extract cell data
cdata <- colData(spe)
# Merge coordinates and cdata using common cell identifiers
ids <- intersect(rownames(coords), rownames(cdata))
coords <- cbind(coords[ids, ], cdata[ids, ])
# Construct a GraphSpace object
gs <- as.GraphSpace(coords)
# If available, add high-dimensional feature data
# Stored separately for lazy aesthetic mapping
gs_fdata(gs) <- as(SummarizedExperiment::assay(spe, "counts"), "dgCMatrix")
# If available, add tissue image and set a scale factor to node coordinates
gs_image(gs) <- SpatialExperiment::imgRaster(spe, image_id = "hires")
gs_scale_factor(gs) <- scaleFactors(spe, image_id = "hires")
# Set coordinate unit
gs_coords_unit(gs) <- c(um = metadata(spe)$scalefactors$microns_per_pixel)
# If not already in colData(), add geometry
# cellseg <- metadata(spe)$cellseg
# cellseg <- cellseg$geometry[match(gs$name, cellseg$cell_id)]
# gs_geometry(gs, "cellseg") <- sf::st_make_valid(cellseg)Session information
#> R version 4.6.2 (2026-10-29)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 24.04.5 LTS
#>
#> Matrix products: default
#> BLAS: /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3
#> LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.26.so; LAPACK version 3.12.0
#>
#> locale:
#> [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
#> [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
#> [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
#> [7] LC_PAPER=en_US.UTF-8 LC_NAME=C
#> [9] LC_ADDRESS=C LC_TELEPHONE=C
#> [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
#>
#> time zone: America/Sao_Paulo
#> tzcode source: system (glibc)
#>
#> attached base packages:
#> [1] stats4 stats graphics grDevices utils datasets methods
#> [8] base
#>
#> other attached packages:
#> [1] sf_1.1-3 SingleR_2.14.2
#> [3] scrapper_1.6.3 patchwork_1.3.2
#> [5] VisiumIO_1.8.0 TENxIO_1.14.0
#> [7] OSTA.data_1.4.0 SpatialExperiment_1.24.0
#> [9] SingleCellExperiment_1.36.0 SummarizedExperiment_1.44.0
#> [11] Biobase_2.74.0 GenomicRanges_1.66.0
#> [13] Seqinfo_1.4.0 IRanges_2.48.0
#> [15] S4Vectors_0.52.0 BiocGenerics_0.60.0
#> [17] generics_0.1.4 MatrixGenerics_1.26.0
#> [19] matrixStats_1.5.0 RGraphSpaceExperiment_0.1.2
#> [21] RGraphSpace_1.5.8.1 ggplot2_4.0.4
#>
#> loaded via a namespace (and not attached):
#> [1] DBI_1.3.0 httr2_1.3.0 rlang_1.3.0
#> [4] magrittr_2.0.5 otel_0.3.0 e1071_1.7-17
#> [7] compiler_4.6.2 RSQLite_3.54.1 systemfonts_1.3.4
#> [10] vctrs_0.7.3 httpcode_0.3.0 pkgconfig_2.0.3
#> [13] fastmap_1.2.0 dbplyr_2.6.0 magick_2.9.1
#> [16] XVector_0.54.0 fontawesome_0.5.3 rmarkdown_2.32
#> [19] tzdb_0.5.0 ggbeeswarm_0.7.3 ragg_1.5.2
#> [22] purrr_1.2.2 bit_4.6.0 xfun_0.62
#> [25] beachmat_2.28.0 cachem_1.1.0 jsonlite_2.0.0
#> [28] blob_1.3.0 DelayedArray_0.40.0 parallel_4.6.2
#> [31] R6_2.6.1 bslib_0.12.0 stringi_1.8.9
#> [34] RColorBrewer_1.1-3 jquerylib_0.1.4 Rcpp_1.1.2
#> [37] knitr_1.52 readr_2.2.0 BiocBaseUtils_1.14.2
#> [40] Matrix_1.7-6 igraph_2.3.4 tidyselect_1.2.1
#> [43] rstudioapi_0.19.0 dichromat_2.0-1 abind_1.4-8
#> [46] yaml_2.3.12 curl_8.2.0 lattice_0.23-1
#> [49] tibble_3.3.1 withr_3.0.3 S7_1.0.0
#> [52] evaluate_1.0.5 ggrastr_1.0.3 desc_1.4.3
#> [55] units_1.0-1 proxy_0.4-29 BiocFileCache_3.4.0
#> [58] pillar_1.11.1 filelock_1.0.3 KernSmooth_2.23-27
#> [61] hms_1.1.4 scales_1.4.0 class_7.3-24
#> [64] glue_1.8.1 tools_4.6.2 BiocIO_1.22.0
#> [67] BiocNeighbors_2.6.0 fs_2.1.0 tidygraph_1.3.1
#> [70] grid_4.6.2 tidyr_1.3.2 beeswarm_0.4.0
#> [73] vipor_0.4.7 cli_3.6.6 textshaping_1.1.0
#> [76] S4Arrays_1.14.0 dplyr_1.2.1 gtable_0.3.6
#> [79] sass_0.5.0 digest_0.6.39 classInt_0.4-11
#> [82] SparseArray_1.13.5 crul_1.6.0 osfr_0.2.9
#> [85] rjson_0.2.23 htmlwidgets_1.6.4 farver_2.1.2
#> [88] memoise_2.0.1 htmltools_0.5.9 pkgdown_2.2.1
#> [91] lifecycle_1.0.5 httr_1.4.9 bit64_4.8.6