Before using code patterns, verify installed versions match. If versions differ:
Python: pip show <package> then help(module.function) to check signatures
If code throws ImportError, AttributeError, or TypeError, introspect the installed
package and adapt the example to match the actual API rather than retrying.
Spatial Neighbor Graphs
"Build a spatial neighborhood graph" → Construct spatial connectivity graphs using k-nearest neighbors, Delaunay triangulation, or radius-based methods for downstream spatial statistics.
Goal: Display the spatial neighbor graph overlaid on tissue coordinates for visual inspection.
Approach: Draw edges between connected spots and scatter plot the spot positions.
import matplotlib.pyplot as plt
# Get coordinates
coords = adata.obsm['spatial']
conn = adata.obsp['spatial_connectivities']
fig, ax = plt.subplots(figsize=(10, 10))
# Draw edges
rows, cols = conn.nonzero()
for i, j in zip(rows, cols):
if i < j: # Avoid drawing twice
ax.plot([coords[i, 0], coords[j, 0]], [coords[i, 1], coords[j, 1]], 'k-', alpha=0.1, linewidth=0.5)
# Draw nodes
ax.scatter(coords[:, 0], coords[:, 1], s=10, c='blue', alpha=0.5)
ax.set_aspect('equal')
plt.title('Spatial neighbor graph')
Compute Graph Statistics
Goal: Calculate summary statistics of the spatial neighbor graph (nodes, edges, connectivity).
Approach: Convert the sparse connectivity matrix to a NetworkX graph and compute standard graph metrics.
import networkx as nx
from scipy.sparse import csr_matrix
conn = adata.obsp['spatial_connectivities']
G = nx.from_scipy_sparse_array(conn)
print(f'Nodes: {G.number_of_nodes()}')
print(f'Edges: {G.number_of_edges()}')
print(f'Average degree: {2 * G.number_of_edges() / G.number_of_nodes():.2f}')
print(f'Connected components: {nx.number_connected_components(G)}')
Store Multiple Neighbor Graphs
# Store different neighborhood sizes
for n_neighs in [4, 6, 10]:
sq.gr.spatial_neighbors(adata, n_neighs=n_neighs, coord_type='generic')
adata.obsp[f'spatial_conn_{n_neighs}'] = adata.obsp['spatial_connectivities'].copy()
adata.obsp[f'spatial_dist_{n_neighs}'] = adata.obsp['spatial_distances'].copy()
Related Skills
spatial-statistics - Use neighbor graph for spatial statistics
spatial-domains - Identify domains using spatial graph