Visualization#

This section covers visualization of spatial transcriptomics data using TrackCell.

Basic Plotting with Cell Polygons#

TrackCell provides a specialized plotting function that visualizes cells as polygons instead of points, providing a more accurate representation of cell boundaries:

# Plot cells as polygons (requires data loaded with read_hd_cellseg)
tcl.pl.spatial_cell(
    adata,
    color="classification",  # Color by cell type
    groups=['Cluster-2', 'Cluster-3'],  # Optional: filter specific groups
    figsize=(6, 6),
    edges_width=0.5,
    edges_color="black",
    alpha=0.8
)

# Plot continuous values (e.g., distance to a label)
tcl.pl.spatial_cell(
    adata,
    color="Cluster-2_dist",  # Distance to Cluster-2
    cmap="Reds",
    figsize=(6, 6)
)

# Plot gene expression
tcl.pl.spatial_cell(
    adata,
    color="PDPN",  # Gene name
    cmap="viridis",
    figsize=(6, 6)
)

# Plot multiple variables in subplots
tcl.pl.spatial_cell(
    adata,
    color=["classification", "Cluster-2_dist"],  # Two subplots
    figsize=(12, 6)
)

Custom Color Palettes#

You can customize colors for categorical variables using the palette parameter. The palette parameter accepts either a dictionary or a list/array of colors.

Using a Dictionary (Category-to-Color Mapping)

When using a dictionary, you explicitly map each category to a color:

# Define custom color palette as dictionary
custom_palette = {
    'Cluster-1': 'red',
    'Cluster-2': 'blue',
    'Cluster-3': 'green',
    'Cluster-4': 'orange'
}

tcl.pl.spatial_cell(
    adata,
    color="classification",
    palette=custom_palette,
    figsize=(6, 6)
)

Using a List/Array (Sequential Color Assignment)

When using a list or array, colors are assigned to categories in alphabetical order:

# Define custom color palette as list
# Colors will be assigned to categories in sorted order
color_list = ['#FF0000', '#0000FF', '#00FF00', '#FFA500']

tcl.pl.spatial_cell(
    adata,
    color="classification",
    palette=color_list,
    figsize=(6, 6)
)

# Or using numpy array
import numpy as np
color_array = np.array(['red', 'blue', 'green', 'yellow'])

tcl.pl.spatial_cell(
    adata,
    color="classification",
    palette=color_array,
    figsize=(6, 6)
)

Note: If the palette has fewer colors than categories, colors will be cycled. A warning will be issued if this occurs.

Reusing a stored palette (``adata.uns``)

When palette is left as None, spatial_cell looks for adata.uns['<color>_colors'] — the scanpy convention — before falling back to its built-in discrete palette. The color list is aligned with adata.obs[color].cat.categories first (AnnData prunes both together when a subset is taken, so ROI panels keep the same color per group), then with adata.uns['<color>_categories'] for a plain object column, then with its sorted unique values:

# Store a palette once, reuse it for every plot of that column
adata.uns['classification_colors'] = ['#e41a1c', '#377eb8', '#4daf4a', '#984ea3']
adata.uns['classification_categories'] = ['Cluster-1', 'Cluster-2', 'Cluster-3', 'Cluster-4']

tcl.pl.spatial_cell(adata, color='classification')          # uses the stored palette
tcl.pl.spatial_cell(adata, color='classification', palette={'Cluster-1': 'black'})  # explicit wins

If the stored list length disagrees with the number of categories, it is ignored with a warning. The same colors are always used for the polygons and for the legend swatches, so the two cannot disagree.

Atera bundles already arrive in this form: io.read_atera(load_groups=True) writes uns['cell_group_colors'] as a list aligned with obs['cell_group'].cat.categories, and keeps the raw {group: hex} map under uns['atera_cell_group_palette']. Both spatial_cell and squidpy therefore pick up Atera’s own 19-color palette with no palette= argument:

adata = tcl.io.read_atera(bundle, sample="breast", build_polygons=True)
tcl.pl.spatial_cell(adata, color="cell_group")              # vendor colors
sq.pl.spatial_scatter(adata, color="cell_group", library_id="breast")

Axes Frame (frameon)#

frameon mirrors squidpy.pl.spatial_scatter(frameon=...):

# Default (None): leave the axes frame alone
tcl.pl.spatial_cell(adata, color='classification')

# No frame, no ticks, no axis labels -- publication-ready image
tcl.pl.spatial_cell(adata, color='classification', frameon=False)

frameon=None (the default) never touches the styling of a ax= passed by the caller; True forces the frame on; False calls ax.axis('off'). Note that frameon is a real parameter and not forwarded to geopandas — passing it through **kwargs would reach PatchCollection.set() and raise.

Dual-Color Visualization (Fill + Edge)#

Use edge_color to color cell boundaries by a categorical column (e.g., cell type), while color controls the fill (gene expression or continuous value). This creates a two-layer visualization where:

  • Fill color maps a continuous variable (gene expression, UMI counts, etc.)

  • Edge color maps a categorical variable (cell type, cluster, etc.)

Fill = Gene Expression, Edge = Cell Type#

import trackcell as tcl

# Fill: gene expression (continuous), Edge: cell type (categorical)
tcl.pl.spatial_cell(
    adata,
    color='EPCAM',              # Fill: gene expression
    cmap='Reds',
    edge_color='cell_type',     # Edge: cell type
    edge_palette={
        'T cell': '#e41a1c',
        'B cell': '#377eb8',
        'Myeloid': '#4daf4a',
    },
    edges_width=1.2,
    alpha=0.7,
)

Fill = Continuous obs, Edge = Categorical obs#

# Fill: continuous observation, Edge: categorical observation
tcl.pl.spatial_cell(
    adata,
    color='total_counts',       # Fill: UMIs per cell
    cmap='YlOrRd',
    edge_color='cell_type',     # Edge: cell type
    edges_width=1.5,
    alpha=0.7,
)

Using edge_palette#

The edge_palette parameter accepts the same formats as palette:

  • Dictionary: Map categories to specific colors

  • List/Array: Assign colors to categories in sorted order

If edge_palette is not specified, a default colormap (tab10 or tab20) is used.

Both legends are automatically generated:

  • Fill: colorbar (continuous) or legend (categorical), positioned on the right

  • Edge: categorical legend, positioned below the plot

Important

Boundary overlap behavior: Adjacent cells share edges. When edge_color uses a categorical column, overlapping edges are drawn by category order — the last-drawn category determines the visible edge colour at shared boundaries. This is a cosmetic rendering artefact and does not affect the underlying data.

Multi-Gene Visualization (cell2location-style)#

TrackCell provides tl.multigene_blend() for co-expression visualization in two modes, controlled by the mode parameter.

Mode 1: Blended Composite (mode='blend')#

Maps each gene to a base color, blends by expression level using weighted RGB averaging. The result is a hex color per cell, stored in adata.obs:

import trackcell as tcl

# Compute blended colors
tcl.tl.multigene_blend(
    adata,
    genes=['EPCAM', 'PECAM1', 'VWF'],
    mode='blend',
)

# Visualize as composite. ``pl.multigene_blend`` is the same picture as
# ``spatial_cell(color='multigene_blend')`` plus the legend that
# ``spatial_cell`` cannot build: a raw-hex column carries no category names,
# so only the ``uns`` parameters know which colour came from which gene.
tcl.pl.multigene_blend(adata)

Equivalently, without the legend:

tcl.pl.spatial_cell(adata, color='multigene_blend')

Custom colors and gamma correction:

tcl.tl.multigene_blend(
    adata,
    genes=['EPCAM', 'PECAM1', 'VWF', 'ACTA2', 'PTPRC'],
    colors=['#e41a1c', '#377eb8', '#4daf4a', '#ff7f00', '#984ea3'],
    vmax_percentile=98,
    gamma=0.8,
)

How blending works: Each gene gets a base RGB color. Per-cell expression is normalized (percentile-clipped to [0, 1]), then blended as:

|color| = Σ (normalized_expr_i × RGB_i) / Σ normalized_expr_i

Zero-expression cells get the background color (default #e0e0e0).

The weights sum to 1, so the colour encodes relative composition, not expression level: a cell with one UMI of gene A and a cell with 1,000 UMIs of gene A get the same colour when no other gene is expressed. Use mode='facet' or a single-gene plot when intensity matters. Genes expressed in fewer cells than the upper percentile tail (e.g. 3 cells in 1,000 at vmax_percentile=99) fall back to the observed maximum instead of being dropped.

Mode 2: Faceted Subplots (mode='facet')#

Each gene gets its own panel with a single-hue colormap (white → gene color). This matches the cell2location paper style:

tcl.tl.multigene_blend(
    adata,
    genes=['EPCAM', 'PECAM1', 'VWF', 'ACTA2'],
    mode='facet',
    ncols=2,           # 2 columns of subplots
    edges_width=0.3,
)

Facet-specific parameters:

  • ncols: Number of columns (default 3)

  • figsize: Figure size (auto-computed if None)

  • edges_width: Cell boundary width (default 0.3)

  • edges_color: Cell boundary color (default '#cccccc30')

  • alpha_facet: Cell transparency for facet plots (default 0.8)

  • show: Whether to call plt.show() (default True)

Square-bin visualization#

For Visium HD square-bin outputs loaded with read_hd_bin(), use spatial_squarebin():

adata_bin = tcl.io.read_hd_bin(
    datapath="SpaceRanger4.0/Cse1/binned_outputs/square_016um",
    sample="Cse1",
    binsize=16,
)

# Show H&E image only, with coordinate range
tcl.pl.spatial_squarebin(adata_bin, color=None)

# Equivalent alias
tcl.pl.spatial_bin(adata_bin, color=None)

# Plot gene expression on square bins
tcl.pl.spatial_squarebin(
    adata_bin,
    color="EPCAM",
    cmap="Reds",
    alpha=0.8,
    alpha_img=0.4,
)

Key spatial_squarebin() parameters:

  • color: Key in adata.obs, a gene name, None (HE-only), or a list of keys

  • library_id: Spatial library key (auto-detected if None)

  • binsize: Bin size in micrometers (optional, auto-detected)

  • shape: Marker shape — 'circle' (default) or 'square'

  • invert_y: If True (default), y increases top-to-bottom (image coordinates); set False for Cartesian convention

  • crop_coord: Optional (x_min, x_max, y_min, y_max) crop in spatial coordinates

  • na_color: Color for missing values (default '#d3d3d3')

  • rasterized: Whether to rasterize patches (default False)

Compatibility with sc.pl.spatial#

For sc.pl.spatial (point-based): use mode='facet' or manually create individual gene subplots. The blend mode hex colors work best with trackcell’s spatial_cell polygon rendering.

Marking Regions#

The mark_region() function draws a rectangular highlight on any spatial plot, useful for annotating regions of interest (ROI) in figures. It works with spatial_cell, spatial_squarebin, sc.pl.spatial, and any matplotlib Axes.

By default, mark_region calls plt.show() automatically (show=True), so the simplest usage works out of the box:

import trackcell as tcl

# spatial_cell returns ax even when show=True
ax = tcl.pl.spatial_cell(adata, color="CellType")
tcl.pl.mark_region(ax, xlim=(54500, 56000), ylim=(15000, 16000))

For full control over display timing, use show=False and call plt.show() manually:

import matplotlib.pyplot as plt
import trackcell as tcl

fig, ax = plt.subplots(figsize=(10, 10))
tcl.pl.spatial_cell(adata, color="CellType", ax=ax, show=False)
tcl.pl.mark_region(
    ax,
    xlim=(54500, 56000),
    ylim=(15000, 16000),
    edges_color='red',
    edges_width=2.0,
    show=False           # defer display
)
plt.show()

With spatial_squarebin() (Visium HD):

fig, ax = plt.subplots(figsize=(10, 10))
tcl.pl.spatial_squarebin(adata, color="GeneA", ax=ax, show=False)

tcl.pl.mark_region(
    ax,
    xlim=(3000, 5000),
    ylim=(2000, 4000),
    edges_color='cyan',
    edges_width=2.0,
    show=False           # defer display
)
plt.show()

Filled regions for better visibility against H&E backgrounds:

tcl.pl.mark_region(
    ax,
    xlim=(54500, 56000),
    ylim=(15000, 16000),
    fill_color='red',      # semi-transparent fill
    fill_alpha=0.15,        # fill opacity
    edges_width=3.0,
    show=False              # defer display
)

Marking multiple regions efficiently (suppress intermediate refreshes):

tcl.pl.mark_region(ax, xlim=(40000, 42000), ylim=(5000, 7000),
                   edges_color='cyan', fill_color='cyan',
                   refresh=False, show=False)
tcl.pl.mark_region(ax, xlim=(55000, 57000), ylim=(15000, 17000),
                   edges_color='yellow', fill_color='yellow',
                   refresh=False, show=False)
tcl.pl.mark_region(ax, xlim=(60000, 62000), ylim=(10000, 12000),
                   edges_color='magenta', fill_color='magenta')
# plt.show() is called by the last mark_region (show=True by default)

Key parameters:

  • ax: The matplotlib Axes to annotate (required).

  • xlim: (x_min, x_max) tuple for the region. If None, uses the current x-axis limits.

  • ylim: (y_min, y_max) tuple for the region. If None, uses the current y-axis limits.

  • edges_color: Rectangle edge color (default 'red').

  • edges_width: Rectangle edge line width (default 2.0).

  • fill_color: Optional fill color with fill_alpha opacity (default None).

  • fill_alpha: Fill opacity when fill_color is set (default 0.15).

  • zorder: Z-order for rendering (default 100). Ensures the rectangle is drawn on top of all other plot elements.

  • refresh: Whether to call ax.figure.canvas.draw_idle() after adding the rectangle (default True). Set to False when adding multiple regions before a single refresh.

  • show: Whether to call plt.show() after adding the rectangle (default True). Set to False when chaining multiple mark_region calls or when you want to call plt.show() manually.

Note

When the y-axis is inverted (invert_y=True, the default), ax.get_ylim() returns (bottom, top) with bottom > top. mark_region normalizes these limits so the Rectangle always has positive dimensions, ensuring robust rendering across all matplotlib backends.

The function returns the matplotlib.patches.Rectangle object, which can be further customized or removed later:

rect = tcl.pl.mark_region(ax, xlim=(1000, 2000), ylim=(3000, 4000))
rect.set_linestyle('--')  # Make it dashed
rect.set_linewidth(3.0)

Physical Scale Bars#

A spatial figure needs a scale bar whose physical length is honest: a full section a few millimetres across needs a 500 µm bar, while a 200 µm zoom-in needs a 10 µm bar. TrackCell therefore derives the bar from the data instead of hard-coding a pixel length.

Enable it with scalebar=True on tcl.pl.spatial_cell() or tcl.pl.spatial_squarebin():

# Automatic length: ~18% of the visible width, rounded to 1/2/5 x 10^n µm
tcl.pl.spatial_cell(adata, color="celltype", scalebar=True)

# Whole section -> 500 µm bar; 200 µm zoom-in -> 20 µm bar (same object!)
tcl.pl.spatial_cell(
    adata, color="celltype", crop_coord=(4100, 4300, 2600, 2800), scalebar=True
)

How the µm-per-unit factor is resolved#

The bar length is a physical length (µm), so TrackCell must know what one unit of adata.obsm['spatial'] means. tcl.pl.resolve_microns_per_unit() decides in this order:

  1. an explicit microns_per_unit you pass in;

  2. coord_unit / spatial_units metadata — Atera and the trackcell readers store 'um', meaning coordinates are already micrometers (the factor is 1.0, and pixel_size is not applied);

  3. metadata['pixel_size_um'] / metadata['resolution_nm'] — a fixed physical scale for the coordinate unit. STOmics GEF coordinates are resolution units (500 nm by default), so one unit is 0.5 µm;

  4. scalefactors['microns_per_pixel'] — Visium / Visium HD coordinates are full-resolution image pixels, so this factor is required;

  5. fallback 1.0 (assume µm), which is correct for Xenium, Atera and MERSCOPE cells.

If your object uses pixel coordinates but carries no scalefactors, pass the factor yourself:

scalebar=dict(microns_per_unit=0.2125)

Automatic vs. fixed length#

scalebar= accepts four shapes:

Value

Behaviour

True

Auto length (frac=0.18 of the visible width, nice 1/2/5 value)

50 / "50um" / "100 µm" / "20px"

Fixed length (µm by default, px for raw data units)

dict(...)

Keyword arguments for tcl.pl.add_scale_bar()

None / False

No bar (default)

Accepted length units are µm / um, micron / micrometre (and their plurals) for micrometers, and px / pixel / data for raw data units. A bare number always means micrometers, so 50 and "50" are the same request. Any other suffix — "20mm", "50nm", "3in" — raises ValueError instead of being silently read as micrometers: a bar labelled 20 µm when 20 mm was asked for is wrong by a factor of 1000 and still looks perfectly drawn. The same applies to a misspelled unit=; convert manually and pass microns_per_unit= if you need a scale the reader cannot infer.

Styling and placement#

Every option lives in the dict form:

tcl.pl.spatial_cell(
    adata,
    color="celltype",
    scalebar=dict(
        length="50um",          # or "auto" / 50 / "20px"
        loc="lower left",       # lower right (default), upper left, center right, ...
        pad=0.03,               # inset from the axes border (axes fraction)
        offset=(8, 8),          # extra shift in points
        frac=0.18,              # auto length as a fraction of the visible width
        color="white",          # bar + label colour
        linewidth=3,            # bar thickness (points)
        fontsize=11,
        caps=True, cap_size=8,  # end caps: |----|
        label="50 µm",          # custom text (default '<length> µm')
        label_position="above", # auto / above / below / none
        frame=True,             # translucent box for busy H&E backgrounds
        frame_color="white", frame_alpha=0.85,
        zorder=20,
    ),
)

Standalone use on any matplotlib axes#

The bar is drawn in axes coordinates, so it stays valid after axis inversion (invert_y), cropping and bbox_inches='tight' saving. Use it on any matplotlib axes — a plain scatter, a gene-expression panel, or a manually composited figure.

Note

Bars shorter than ~2% of the visible width trigger a warning: a 10 µm bar in a 300 µm window is physically correct but barely legible — pick a longer length or raise frac.

fig, ax = plt.subplots(figsize=(6, 6))
ax.scatter(*adata.obsm['spatial'].T, s=1)
ax.set_aspect('equal')
info = tcl.pl.add_scale_bar(ax, adata, length="100um", loc="lower right")
print(info)   # {'length': 100.0, 'label': '100 µm', 'axes_fraction': 0.025, ...}

Circular ROI (point + physical radius)#

A hand-drawn polygon is hard to report and impossible to reproduce exactly. A circle is fully specified by a center point and a physical radius, so it can be written down in a methods section and re-run on another sample:

center = (4470.0, 2620.0)      # (x, y) in obsm['spatial'] units — µm for Atera
radius = 150.0                 # µm

mask = tcl.tl.cells_in_radius(adata, center, radius)
roi = adata[mask].copy()
print(mask.sum(), "cells within", radius, "µm")

center uses the coordinate system of adata.obsm['spatial'] — the numbers you read off the plot — while radius is a physical length (µm) by default. On pixel-coordinate data (Visium, Visium HD) scalefactors['microns_per_pixel'] is applied automatically, so the same call means the same thing on both kinds of object:

Object

obsm['spatial']

cells_in_radius(..., 150)

Xenium / Atera / MERSCOPE

µm

a 150 µm circle

Visium HD

full-resolution px (0.32512 µm/px)

a 150 µm (= 461 px) circle

Pass radius_unit="data" to use raw data units instead, and return_distances=True to also get each cell’s distance to the center in µm.

Annotate the same circle on the overview plot so readers can see where the zoom came from — mark_circle shares the unit semantics with cells_in_radius:

fig, (ax_l, ax_r) = plt.subplots(1, 2, figsize=(15, 7))

tcl.pl.spatial_cell(adata, color="celltype", scalebar=True,
                    legend=False, show=False, ax=ax_l)
tcl.pl.mark_circle(ax_l, center, radius, radius_unit="um", adata=adata,
                   edges_color="#b91c1c", linestyle="--",
                   label=f"ROI: r = {radius:.0f} µm", show=False)
ax_l.legend(loc="upper right", frameon=False)

tcl.pl.spatial_cell(roi, color="celltype", scalebar=True,
                    legend=False, show=False, ax=ax_r)

Each panel gets its own scale bar, and because the overview is ~3× wider than the zoom, its bar is ~3× longer — 100 µm against 50 µm here.

To pick the center interactively instead of typing coordinates:

%matplotlib widget
ax = tcl.pl.spatial_cell(adata, color="celltype", scalebar=True, show=False)
center = plt.ginput(1)[0]     # click once; returns obsm coordinates

Note

mark_circle defaults to radius_unit="data" because it is a pure drawing primitive; pass radius_unit="um" together with adata (or microns_per_unit) whenever the two figures must agree.

The scale bar itself is clamped against the axes: caps, label and backing frame are measured and re-placed on every draw, so tight_layout(), savefig(bbox_inches="tight") and window resizes cannot push them over the spine.

A complete runnable walkthrough on an Atera breast-cancer section — raw read with Atera’s own clustering, whole-section point plots, a 2 x 3 lattice of circular ROIs, the ROIs versus the remaining tissue, per-ROI distance maps, and cell polygons at a smaller radius — is in Atera 空间可视化 — 整体图、6 个圆形 ROI 与物理比例尺.

Interactive ROI Selection (Jupyter / matplotlib)#

TrackCell provides notebook-native interactive region-of-interest selection via tcl.pl.select_regions(). The backend uses matplotlib widgets / ipympl instead of napari, avoiding Qt event-loop crashes in Jupyter.

Important

In Jupyter Notebook / JupyterLab, run this before calling the selector:

%matplotlib widget

ipympl is available via the interactive extra. If your environment lacks it, run pip install "trackcell[interactive]" (or pip install ipympl).

import trackcell as tcl

selector = tcl.pl.select_regions(
    adata,
    color="CellType",
    key_added="ROI",
    inplace=True,           # write adata.obs["ROI"] after each ROI
)

# Draw ROIs interactively.  Use the toolbar buttons at the bottom
# of the figure, or press r/e/l while the figure has focus.
#
# ROIs are auto-named (ROI_1, ROI_2, ...).  Rename afterwards with:
#   selector.rename_roi("ROI_1", "tumor")
#
# Selected cells are highlighted with coloured scatter points.
#
# Results are available immediately:
selector.rois
adata.obs["ROI"].value_counts(dropna=False)

An inline toolbar at the bottom of the figure provides clickable buttons:

  • ■ Rect — rectangle selector

  • ● Ellipse — ellipse / circle selector

  • ✎ Lasso — lasso / freehand selector

  • ✕ Clear — remove all ROIs

  • ↩ Undo — remove the last ROI

The currently active mode is highlighted in blue.

While the figure has focus, press:

  • r — rectangle selector

  • e — ellipse / circle selector

  • l — lasso / freehand selector

Unlike the previous version, there is no ``input()`` prompt. ROIs are auto-named as ROI_1, ROI_2, … immediately after you draw each shape. This keeps the interactive workflow uninterrupted.

To rename an ROI after the fact:

selector.rename_roi("ROI_1", "tumor_region")
selector.rename_roi("ROI_2", "stroma")

The prefix is configurable via the roi_prefix parameter:

selector = tcl.pl.select_regions(adata, roi_prefix="zone")
# → auto-names: zone_1, zone_2, ...

tcl.pl.select_regions() returns a RegionSelector controller:

selector.rois          # dict: ROI name -> observation IDs
selector.polygons      # dict: ROI name -> ROI vertices
selector.rename_roi()  # rename an ROI
selector.undo()        # remove the last ROI
selector.save()        # write / rewrite adata.obs[key_added]
selector.clear()       # remove all ROIs and visual patches
selector.to_adata()    # get an AnnData copy with ROI labels
selector.disconnect()

With inplace=False, use selector.to_adata() to get an AnnData copy:

selector = tcl.pl.select_regions(adata, inplace=False)
adata_with_rois = selector.to_adata()
adata_with_rois.obs["ROI"].value_counts()

For squarebin data (e.g. Visium HD bin-level), set mode="squarebin" or let TrackCell auto-detect it. Bin centroids from adata.obsm[basis] are tested against each ROI polygon.

selector = tcl.pl.select_regions(
    adata_bins,
    mode="squarebin",
    basis="spatial",
    color="gene_of_interest",
    key_added="ROI_bins",
)

For cellbin data, cell geometries are used and cells are selected when their geometry intersects the ROI polygon.

selector = tcl.pl.select_regions(
    adata_cell,
    mode="cellbin",
    color="CellType",
    key_added="ROI_cell",
)
  • color — column in adata.obs or gene in adata.var_names to colour the spatial plot.

  • library_id — spatial library key (auto-detected if None).

  • mode — "auto" (default), "cellbin", or "squarebin".

  • basis — key in adata.obsm for squarebin coordinates (default "spatial").

  • key_added — column name in adata.obs for ROI labels.

  • inplace — True (default) writes labels to adata.obs[key_added] after every selection; False → use selector.to_adata().

  • roi_prefix — prefix for auto-generated names (default "ROI" → ROI_1, ROI_2, …).

  • figsize — figure size when ax is not provided.

  • invert_y — default True to match image/spatial coordinates where y increases from top to bottom.

  • Extra keyword arguments are forwarded to spatial_cell or spatial_squarebin.

Performance Optimization for Large Datasets#

When working with large datasets (e.g., 200,000+ cells), visualization can be slow. Here are recommended strategies to improve performance:

Performance Comparison#

Expected performance for different approaches with ~230,000 cells:

  • Full polygon plotting: Several minutes to tens of minutes

  • Using groups (filtering to ~10% of cells): ~10-30 seconds

  • Point-based plotting: ~1-5 seconds

  • Downsampling to 10,000 cells: ~5-15 seconds

Optimization Strategies#

Strategy 1: Filter by Cell Groups

The most effective optimization is to plot only cells of interest using the groups parameter:

# Plot only specific cell types
tcl.pl.spatial_cell(
    adata,
    color="classification",
    groups=['Cluster-2', 'Cluster-3', 'Cluster-5']  # Only these cell types
)

Strategy 2: Spatial Region Cropping

Crop to a specific spatial region of interest:

import numpy as np
import trackcell as tcl

# Define region of interest
x_min, x_max = 1000, 5000
y_min, y_max = 1000, 5000

# Create mask for spatial coordinates
spatial_coords = adata.obsm['spatial']
mask = ((spatial_coords[:, 0] >= x_min) & (spatial_coords[:, 0] <= x_max) &
        (spatial_coords[:, 1] >= y_min) & (spatial_coords[:, 1] <= y_max))

# Create subset
adata_subset = adata[mask].copy()

# IMPORTANT: Synchronize geometries after subsetting
# This is required when data was loaded with read_hd_cellseg()
tcl.io.sync_geometries_after_subset(adata_subset, sample="Cse1")

# Plot subset
tcl.pl.spatial_cell(adata_subset, color="classification")

Strategy 3: Use Point-based Visualization

For large datasets, point-based visualization is much faster:

import scanpy as sc

# Point-based visualization (much faster)
sc.pl.spatial(
    adata,
    color='classification',
    spot_size=1,      # Small spots
    size=0.5,         # Further reduce size
    groups=['Cluster-2', 'Cluster-3']
)

Strategy 4: Disable Edge Rendering

Disable polygon edges to improve rendering performance:

tcl.pl.spatial_cell(
    adata,
    color="classification",
    edges_width=0,  # Disable edges
    groups=['Cluster-2', 'Cluster-3']
)

Strategy 5: Use Low-Resolution Images

Use low-resolution background images when available:

tcl.pl.spatial_cell(
    adata,
    color="classification",
    img_key="lowres",  # Use low-resolution image
    groups=['Cluster-2', 'Cluster-3']
)

Best Practices#

  1. Always use GeoDataFrame format: Ensure your data uses adata.uns['spatial'][sample]['geometries'] (GeoDataFrame) rather than WKT strings for better performance.

  2. Start with point-based visualization: Use sc.pl.spatial() for initial exploration, then switch to polygon-based visualization for detailed analysis.

  3. Filter before plotting: Always use groups or spatial cropping to reduce the number of cells before plotting.

  4. Combine strategies: Use multiple optimization strategies together for best results.

  5. Save intermediate results: For repeated visualization, consider saving filtered subsets to avoid repeated filtering operations.

Example Workflow#

Here’s a recommended workflow for visualizing large datasets:

import trackcell as tcl
import scanpy as sc

# Step 1: Quick overview with point-based plot
sc.pl.spatial(
    adata,
    color='classification',
    spot_size=0.5,
    size=0.3
)

# Step 2: Detailed view of specific cell types with polygons
tcl.pl.spatial_cell(
    adata,
    color="classification",
    groups=['Cluster-2', 'Cluster-3'],  # Focus on specific types
    edges_width=0,                      # Optimize performance
    figsize=(6, 6)
)

# Step 3: High-resolution view of specific region
# (Use spatial cropping as shown in Strategy 2)