Skip to content

voronoi

voronoi

voronoi(
    data,
    colorBy=None,
    colors=None,
    xCoordinate="X_centroid",
    yCoordinate="Y_centroid",
    imageId="imageid",
    subset=None,
    xLim=None,
    yLim=None,
    flipY=True,
    voronoiEdgeColor="black",
    voronoiLineWidth=0.1,
    voronoiAlpha=0.5,
    sizeMax=inf,
    overlayPoints=None,
    overlayPointsCategories=None,
    overlayDropCategories=None,
    overlayPointsColors=None,
    overlayPointSize=5,
    overlayPointAlpha=1,
    overlayPointShape=".",
    plotLegend=True,
    fileName="voronoi.pdf",
    outputDir=None,
    saveDir=None,
    legendSize=6,
    show=True,
    returnData=False,
    returnFig=False,
    dpi=300,
    transparent=False,
    sdataTable=None,
    **kwargs
)

Voronoi tessellation of the tissue, one polygon per cell.

Every cell claims the region of the slide closer to it than to any other cell, which fills the image and makes tissue compartments legible in a way a point scatter does not. Infinite regions at the convex hull are clipped to a finite radius.

This is O(n log n) but plots one polygon at a time, so it gets slow past a few tens of thousands of cells. Use subset to work one image at a time.

Parameters:

Name Type Description Default
data (AnnData | SpatialData | str, required)

The cell table. An AnnData, a path to an .h5ad file, a SpatialData object, or a path to a .zarr SpatialData store.

required
colorBy str

Column in obs to colour polygons by. All polygons share one colour when None.

None
colors dict

Explicit {category: colour} mapping.

None
xCoordinate str

Column in obs holding x positions.

'X_centroid'
yCoordinate str

Column in obs holding y positions.

'Y_centroid'
imageId str

Column in obs holding image identifiers, used by subset.

'imageid'
subset str | list

Restrict to these images.

None
xLim tuple

(low, high) x limits, to zoom into a region.

None
yLim tuple

(low, high) y limits.

None
flipY bool

Invert the y axis so the plot matches the orientation of the raw image.

True
voronoiEdgeColor str

Polygon outline colour.

'black'
voronoiLineWidth float

Polygon outline width.

0.1
voronoiAlpha float

Polygon opacity.

0.5
sizeMax float

Accepted for signature compatibility with scimap; polygons are not currently clipped by area. Use xLim and yLim to crop.

inf
overlayPoints str

Truthy to draw the cell centroids on top of the polygons.

None
overlayPointsCategories list

Accepted for signature compatibility with scimap.

None
overlayDropCategories list

Accepted for signature compatibility with scimap.

None
overlayPointsColors dict

Accepted for signature compatibility with scimap; overlaid points are drawn black.

None
overlayPointSize float

Size of the overlaid centroids.

5
overlayPointAlpha float

Opacity of the overlaid centroids.

1
overlayPointShape str

Accepted for signature compatibility with scimap.

'.'
plotLegend bool

Accepted for signature compatibility with scimap.

True
legendSize int

Accepted for signature compatibility with scimap.

6
fileName str

File name for the saved figure. The extension decides the format.

'voronoi.pdf'
outputDir str

Directory to save the figure in. When None nothing is written.

None
saveDir str

Deprecated alias for outputDir, kept for scripts carried over from scimap. outputDir wins when both are given.

None
show bool

Call plt.show() before returning. Set False in scripts and notebooks that save rather than display.

True
returnData bool

Return the DataFrame behind the plot instead of drawing it.

False
returnFig bool

Return (fig, axes). With returnData as well, returns (fig, axes, plotData).

False
dpi int

Resolution of the saved figure.

300
transparent bool

Save with a transparent background.

False
sdataTable str

Which SpatialData table to read. Ignored for AnnData input, and optional when the store has exactly one table.

None

Returns:

Name Type Description
result None | DataFrame | tuple

None by default; with returnData=True a DataFrame of coordinates and colours whose .attrs carry the computed regions and vertices; (fig, ax) with returnFig=True.

Example
sp.pl.voronoi(adata, colorBy="phenotype", subset="sample_1")

# Zoom into a region and overlay the centroids.
sp.pl.voronoi(
    adata,
    colorBy="phenotype",
    subset="sample_1",
    xLim=(2000, 3000),
    yLim=(1500, 2500),
    overlayPoints=True,
    outputDir="figures",
    show=False,
)

Building blocks

voronoi is the two functions below composed together. They are exported so you can drop a tessellation into a figure of your own.

computeVoronoiRegions

computeVoronoiRegions(points, radius=None)

Compute finite Voronoi regions for a set of 2D points.

scipy.spatial.Voronoi leaves the regions on the convex hull open. This reconstructs them as finite polygons by projecting each unbounded ridge out to radius and closing the region, so every point ends up with a drawable polygon.

Parameters:

Name Type Description Default
points (ndarray, required)

An (n, 2) array of coordinates.

required
radius float

How far to project unbounded ridges. Defaults to twice the largest coordinate range, which is far enough to leave no visible gap.

None

Returns:

Name Type Description
regions list

One list of vertex indices per input point, ordered counter-clockwise.

vertices ndarray

The vertex coordinates the indices refer to, including the synthetic far points added for unbounded regions.

Example
regions, vertices = sp.pl.computeVoronoiRegions(
    adata.obs[["X_centroid", "Y_centroid"]].to_numpy()
)

plotVoronoi

plotVoronoi(
    regions,
    vertices,
    values=None,
    colors=None,
    ax=None,
    edgeColor="black",
    lineWidth=0.1,
    alpha=0.5,
)

Draw Voronoi polygons on a Matplotlib axis.

The drawing half of sp.pl.voronoi, separated out so you can compose the tessellation into a larger figure.

Parameters:

Name Type Description Default
regions (list, required)

Vertex-index lists, as returned by computeVoronoiRegions.

required
vertices (ndarray, required)

Vertex coordinates, as returned by computeVoronoiRegions.

required
values array - like

One value per region, used to colour it. All polygons share one colour when None.

None
colors dict

Explicit {category: colour} mapping. A tab20-based palette is built from values when omitted.

None
ax Axes

Axis to draw on. A new figure is created when None.

None
edgeColor str

Polygon outline colour.

'black'
lineWidth float

Polygon outline width.

0.1
alpha float

Polygon opacity.

0.5

Returns:

Name Type Description
fig Figure

The figure the polygons were drawn on.

ax Axes

The axis the polygons were drawn on, with an equal aspect ratio.

Example
import matplotlib.pyplot as plt

coords = adata.obs[["X_centroid", "Y_centroid"]].to_numpy()
regions, vertices = sp.pl.computeVoronoiRegions(coords)

fig, ax = plt.subplots(figsize=(8, 8))
sp.pl.plotVoronoi(regions, vertices, values=adata.obs["phenotype"], ax=ax)