Skip to content

nGraph

nGraph

nGraph(
    data,
    layer="raw",
    standardScale=False,
    runPCA=False,
    kNeighbors=15,
    nPcs=20,
    sdataTable=None,
)

Build a k-nearest-neighbour graph from the expression matrix.

Returns a bare igraph.Graph rather than modifying the object, so it is a building block: sp.tl.cluster with method='leiden' builds its own graph internally, and this is here for when you want to run igraph's own algorithms — betweenness, communities, shortest paths — over the same structure.

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
layer str

Which matrix to build the graph from. 'raw' uses .raw.X, None uses .X, any other string names a key in .layers.

'raw'
standardScale bool

Z-score each marker before computing neighbours, so markers with large dynamic range do not dominate the distances.

False
runPCA bool

Reduce to nPcs principal components first. Worth doing above a few dozen markers.

False
kNeighbors int

Neighbours per cell.

15
nPcs int

Components to keep when runPCA=True. Clipped to what the data allows.

20
sdataTable str

Which SpatialData table to read.

None

Returns:

Name Type Description
graph Graph

An undirected graph with one vertex per cell, in obs order.

Raises:

Type Description
ValueError

When layer='raw' and the object has no .raw.

Example
graph = sp.pp.nGraph(adata, layer="raw", standardScale=True, runPCA=True)
graph.vcount(), graph.ecount()

# Any igraph algorithm now applies.
communities = graph.community_multilevel()
adata.obs["igraph_community"] = [str(c) for c in communities.membership]