Connect counts, coordinates, and images
A spatial object has several linked parts. Expression columns identify capture spots, position rows locate those spots, and scale factors connect the original image to the smaller image displayed here. Matching dimensions cannot replace a barcode join, because a reordered table can have the expected row count and still place every expression value at the wrong position. This example contains one tissue section from one mouse donor.
Preserve the coordinate convention
Section titled “Preserve the coordinate convention”This Space Ranger 1.1.0 archive uses a headerless
tissue_positions_list.csv. The explicit fields are the barcode, tissue flag,
array row, array column, full resolution pixel row, and full resolution pixel
column. Newer files named tissue_positions.csv have a header and require a
different import instruction.
The Space Ranger spatial output specification defines pixel columns as x and pixel rows as y. Both coordinates must use the same image scale factor. Here the origin stays at the upper left, y increases downward, and equal axis scales preserve shape. The capture circle diameter also uses that scale factor; a large plotting symbol would otherwise suggest coverage that the assay did not measure.
Check the join before the overlay
Section titled “Check the join before the overlay”The shared readers load the checked public fixture from the overview. R and Python then repeat the barcode join and bounds checks independently. Stable Ensembl identifiers remain the feature identity even when two rows have the same gene symbol.
source("/shared/spatial_utils.R")data <- ReadCounts()positions <- ReadPositions()index <- match(data$barcodes, positions$barcode)stopifnot(!anyNA(index), !anyDuplicated(index))positions <- positions[index, ]stopifnot(identical(positions$barcode, colnames(data$counts)))scales <- fromJSON("/fixtures/spatial/scalefactors_json.json")positions$x <- positions$full_x * scales$tissue_lowres_scalefpositions$y <- positions$full_y * scales$tissue_lowres_scalefdata$image <- png::readPNG("/fixtures/spatial/tissue_lowres_image.png")stopifnot(all(positions$x >= 0 & positions$x < dim(data$image)[2]))stopifnot(all(positions$y >= 0 & positions$y < dim(data$image)[1]))data$positions <- positionsdata$scales <- scalesdiameter <- scales$spot_diameter_fullres * scales$tissue_lowres_scalefdir.create("outputs", showWarnings = FALSE)write.table(positions, "outputs/coordinates_r.tsv", sep = "\t", quote = FALSE, row.names = FALSE)png("outputs/alignment_r.png", width = 1000, height = 900, res = 140)DrawSpatial(data, positions$array_row, "Capture circles on the tissue image")invisible(dev.off())WriteMetrics(list(spots = nrow(positions), diameter = diameter, duplicate_symbols = sum(duplicated(data$features$symbol))))cat(sprintf("All %d barcodes have one coordinate row.\n", nrow(positions)))cat(sprintf("The displayed capture diameter is %.6f pixels.\n", diameter))cat(sprintf("Gene symbols contain %d repeated names.\n", sum(duplicated(data$features$symbol))))All 2695 barcodes have one coordinate row.The displayed capture diameter is 4.619896 pixels.Gene symbols contain 40 repeated names.
The overlay preserves the image origin and uses the supplied capture diameter. Circle color shows the native array row, which helps reveal a reversed axis.
import sysfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pd
sys.path.insert(0, "/shared")import spatial_utils as spatial
data = spatial.read_section()positions = data["positions"]assert positions.index.tolist() == data["barcodes"].tolist()assert not positions.index.has_duplicatesdiameter = (data["scales"]["spot_diameter_fullres"] * data["scales"]["tissue_lowres_scalef"])reference = pd.read_csv("outputs/coordinates_r.tsv", sep="\t")assert reference["barcode"].tolist() == positions.index.tolist()np.testing.assert_allclose(reference[["x", "y"]], positions[["x", "y"]], rtol=0, atol=1e-8)Path("outputs").mkdir(exist_ok=True)positions.to_csv("outputs/coordinates_python.tsv", sep="\t")fig, ax = plt.subplots(figsize=(8, 7))spatial.draw_spatial(ax, data, positions["array_row"], "Capture circles on the tissue image")fig.savefig("outputs/alignment_python.png", dpi=160, bbox_inches="tight")plt.close(fig)duplicates = int(data["features"]["symbol"].duplicated().sum())spatial.write_metrics(dict(spots=len(positions), diameter=diameter, duplicate_symbols=duplicates))print(f"All {len(positions)} barcodes have one coordinate row.")print(f"The displayed capture diameter is {diameter:.6f} pixels.")print(f"Gene symbols contain {duplicates} repeated names.")All 2695 barcodes have one coordinate row.The displayed capture diameter is 4.619896 pixels.Gene symbols contain 40 repeated names.
The Python overlay checks every displayed x and y coordinate against the R
result within 1e-8 pixels.
Circle color shows the native array row, which helps reveal a reversed axis.
The tissue image is supplied by 10x Genomics under CC BY 4.0. These figures add colored capture circles and axes to that image. The coordinate unit remains pixels; the examples do not infer a micrometer calibration from the image.
An overlay can reveal a mirror image, a swapped axis, or a scale mismatch. It does not establish cell segmentation or assign each captured transcript to one cell. The quality lesson checks what those spots actually measured.
Further reading
Section titled “Further reading”The Space Ranger spatial output specification explains position fields, image scale factors, and the change from a headerless position file to a file with a header. Use it to check the row and column conventions before drawing an overlay.
The 10x Genomics specimen record identifies the mouse brain section and its Space Ranger 1.1.0 archive. It anchors the file version and tissue image used by this lesson.