Skip to main content
v2026.11,986 entries · CC-BY 4.0

Squidpy: Spatial Omics Analysis in Python, Install and Workflow

Install Squidpy, run neighbourhood enrichment and Moran’s I on spatial omics data, and learn where results are stored and how to read them.

Written and maintained by CASRAI Editorial Board

Published

On this page

Squidpy is a Python package for analysing and visualising spatial molecular data, such as spatial transcriptomics, using the spatial coordinates and tissue images that come with each measurement. It builds on Scanpy and AnnData, installs with pip install squidpy and requires Python 3.11 or newer. The core workflow is to build a spatial neighbourhood graph, run a graph statistic such as neighbourhood enrichment or Moran’s I, and plot the result.

This guide is for researchers and analysts who already hold an annotated spatial dataset and need to know which Squidpy call answers which question. It lists the modules, gives the install options, walks through the neighbourhood-enrichment and spatial-autocorrelation steps in the order the official Visium H&E tutorial uses them, explains where each result is stored and how to read it, and maps the errors a new user is most likely to meet. It covers Squidpy 1.8.4, the version shown in the stable documentation.

What Squidpy is used for in research

The Squidpy documentation describes the package as a tool for the analysis and visualisation of spatial molecular data. It works with the spatial coordinates of each observation and, where they exist, with the tissue image, and it is built on Scanpy and AnnData, so a dataset that is already an AnnData object can be passed straight in. Its stated capabilities include neighbourhood graphs, spatial statistics, and image analysis for large tissue images through scikit-image.

In practice that means three kinds of question. The first is about layout: which cell-type or cluster labels sit next to each other in the tissue, and which sit apart. The second is about genes: which genes have expression that varies in a spatially structured way rather than at random. The third is about the image: what features can be computed from the tissue image underneath each spot. The package was published in 2022 by Palla, Spitzer and colleagues in Nature Methods (doi 10.1038/s41592-021-01358-2), which is the reference to cite when a paper reports Squidpy results.

Squidpy sits downstream of data generation and quality control. It does not replace the clustering step: the neighbourhood tools take a cluster or cell-type column you have already stored in the observation table. For readers choosing a platform before analysis, the CASRAI guide to the CosMx Spatial Molecular Imager covers one imaging-based spatial platform, and the guide to multi-omics places spatial data among the other data layers.

The Squidpy modules

The API reference groups the package into eight namespaces. Knowing them is most of the navigation work, because every function is called as sq.module.function_name after import squidpy as sq.

Module Role in the workflow
sq.gr Graph tools: neighbourhood graph construction and the statistics computed on it
sq.im Image tools, for example calculate_image_features
sq.pl Plotting functions that mirror the analysis calls, such as spatial_scatter and nhood_enrichment
sq.read Reading functions, listed in the API reference
sq.tl Tools namespace, listed in the API reference
sq.datasets Example datasets used in the tutorials, such as visium_hne_adata and visium_hne_image
sq.experimental Experimental namespace, listed in the API reference
sq.types Type definitions, listed in the API reference

The graph module is where most analyses happen. Its documented functions are mask_graph (mask the graph with a polygon), nhood_enrichment (neighbourhood enrichment by permutation test), co_occurrence (co-occurrence probability of clusters), centrality_scores (per cluster or cell type), interaction_matrix, ripley (Ripley’s statistics for point processes), ligrec (a permutation test for ligand-receptor analysis following the CellPhoneDB work of Efremova and colleagues, 2020), spatial_autocorr (global autocorrelation by Moran’s I or Geary’s C) and sepal (spatially variable genes with the Sepal method).

How to install Squidpy

The installation page of the official documentation gives these routes. Check the Python version first, because Squidpy requires Python 3.11 or newer.

  1. Check the interpreter: python --version must report 3.11 or later. Create a fresh virtual environment or conda environment if it does not.
  2. Install the release from PyPI: pip install squidpy.
  3. Or install from conda-forge: conda install -c conda-forge squidpy.
  4. For the development version, use pip install git+https://github.com/scverse/squidpy@main. Use this only when you need a change that has not been released.
  5. For interactive visualisation, install the napari plugin separately with pip install napari-spatialdata. The documentation notes that the Squidpy napari plugin moved into napari-spatialdata.
  6. Confirm the install in Python: import squidpy as sq; print(sq.__version__). The official tutorial prints the version the same way.

Record the version number you print in your methods section or analysis log. Function signatures have changed between releases, as the troubleshooting section below shows, so a result is only reproducible with the version that produced it. The CASRAI guide to SpatialData, the scverse framework for spatial omics data, is the companion reference when your data lives in a SpatialData object rather than an AnnData one.

How to run neighbourhood enrichment step by step

This workflow follows the official Visium H&E tutorial, which uses a pre-processed dataset bundled with the package so that every call can be reproduced without your own data. The clustering column in that dataset is called cluster; in your own data, use the name of your own annotation column.

  1. Import the libraries: import numpy as np, import pandas as pd, import anndata as ad, import scanpy as sc and import squidpy as sq.
  2. Load the example data: img = sq.datasets.visium_hne_image() and adata = sq.datasets.visium_hne_adata(). With your own data, adata is an AnnData object with spatial coordinates and a stored cluster or cell-type column in adata.obs.
  3. Look at the clusters in tissue space: sq.pl.spatial_scatter(adata, color="cluster").
  4. Build the spatial neighbourhood graph: sq.gr.spatial_neighbors(adata). This step is required before every graph statistic.
  5. Run the permutation test: sq.gr.nhood_enrichment(adata, cluster_key="cluster"). The default is 1000 permutations.
  6. Plot the result: sq.pl.nhood_enrichment(adata, cluster_key="cluster").

Step 4 in detail: the neighbourhood graph

The signature of spatial_neighbors exposes the choices that matter. The coord_type argument takes 'grid' or 'generic'; when it is left as None, the function resolves it to grid for Visium-style data with six neighbours and to generic otherwise. For generic coordinates, n_neighs sets the number of neighbours, radius builds a radius-based graph (a tuple prunes edges to the interval between its minimum and maximum), and delaunay=True builds the graph from a Delaunay triangulation. For data with several tissue sections, library_key names the observation column that maps each library to its observations.

With the default key_added='spatial', the graph is written to adata.obsp['spatial_connectivities'] and adata.obsp['spatial_distances'], and the parameters used are recorded in adata.uns['spatial']. Because the graph definition changes every downstream statistic, state the construction (grid or generic, neighbour count or radius) when you report results.

Step 5 in detail: the permutation test

The documented signature is nhood_enrichment(adata, *, cluster_key, library_key=None, connectivity_key=None, n_perms=1000, rng=None, copy=False, n_jobs=None, show_progress_bar=True, normalization='none', min_cell_count=0, handle_nan='keep', table_key=None). Three parameters deserve attention. normalization accepts 'none', 'total' (divide by the number of cells in the index cluster) or 'conditional' (divide by the number of index-cluster cells with at least one neighbour of the given type). min_cell_count drops clusters smaller than the stated size. rng sets the random generator so the permutation result can be repeated; it replaces the older seed and random_state names as of version 1.8.4.

How to test spatially variable genes with Moran’s I

The same tutorial computes spatial autocorrelation for genes, which answers the second kind of question: which genes are expressed in a spatially patterned way.

  1. Make sure the neighbourhood graph from the previous section exists.
  2. Select genes. The tutorial takes the first 1000 highly variable genes: genes = adata[:, adata.var.highly_variable].var_names.values[:1000].
  3. Run the test: sq.gr.spatial_autocorr(adata, mode="moran", genes=genes, n_perms=100, n_jobs=1). The mode argument also accepts Geary’s C according to the function description.
  4. Read the table: adata.uns["moranI"].head(10).
  5. Plot the top genes beside the clusters: sq.pl.spatial_scatter(adata, color=["Olfm1", "Plp1", "Itpka", "cluster"]).

Restricting the gene list to highly variable genes is a choice made in the tutorial, not a requirement of the function; running every gene multiplies the number of permutation tests.

How to read the output

Neighbourhood enrichment

The tutorial explains the score in terms of proximity. If spots of two different clusters are often close to each other, the pair gets a high score and the clusters are called enriched. If they are far apart and seldom neighbours, the score is low and the pair is depleted. The score comes from a permutation test, so it is compared against label shuffles rather than against a fixed threshold. In the tutorial’s dataset, the pyramidal-layer clusters often neighbour the larger Hippocampus cluster, which shows as high enrichment in the heatmap.

When the function is run with the default copy=False, results are written to adata.uns['{cluster_key}_nhood_enrichment'] with the entries zscore, count and conditional_ratio. With cluster_key="cluster" the location is adata.uns['cluster_nhood_enrichment']. The z-score matrix is what sq.pl.nhood_enrichment draws. Clusters dropped by min_cell_count have NaN z-scores; handle_nan='zero' replaces them with 0 instead of leaving them undefined.

Moran’s I

Results are stored in adata.uns['moranI'], already sorted by the Moran’s I statistic, so the top rows are the genes with the strongest global spatial autocorrelation. The table has the columns I, pval_norm, var_norm, pval_z_sim, pval_sim, var_sim and three Benjamini-Hochberg-adjusted columns, pval_norm_fdr_bh, pval_z_sim_fdr_bh and pval_sim_fdr_bh. Because many genes are tested at once, report the adjusted p-value columns and not the raw ones. In the tutorial, genes near the top, such as Olfm1, Plp1 and Itpka, relate to the pyramidal layers and the fibre tract, which is the check to repeat on your own data: confirm that top genes map onto anatomy you recognise before trusting the ranking.

Co-occurrence

The tutorial’s next analysis, sq.gr.co_occurrence(adata, cluster_key="cluster"), scores the conditional probability of a cluster given another cluster divided by the probability of that cluster in the radius of interest, computed across increasing radii around each observation. Distance is expressed in pixels of the Visium source image. The tutorial notes that the result largely recapitulates the neighbourhood-enrichment analysis, with the Pyramidal_layer cluster co-occurring at short distances with the Hippocampus cluster. Treat co-occurrence as a second view of the same layout question, not independent confirmation.

Troubleshooting Squidpy

Symptom Cause documented in the Squidpy docs What to do
Install fails or the package cannot be found on an older interpreter Squidpy requires Python 3.11 or newer Check python --version; create a new environment with Python 3.11 or later
A FutureWarning about seed or random_state Since 1.8.4 the random generator argument is rng; the old names still work but warn Pass rng instead
A deprecation notice on spatial_neighbors The function is documented as deprecated since 1.7.0 and slated for removal in 1.9.0, with mode-specific functions recommended Pin the Squidpy version for existing analyses and read the current API page before upgrading
NaN values in the neighbourhood-enrichment z-scores Clusters smaller than min_cell_count are dropped and get NaN z-scores Lower min_cell_count, or set handle_nan='zero' if zeros are acceptable for your plot
An error when setting n_jobs For nhood_enrichment, None and -1 use numba’s default thread count, while 0 and values below -1 raise an error Use None, -1 or a positive integer
A SpatialData object is rejected or the table is not found For SpatialData input, table_key names the table in SpatialData.tables and is required Pass table_key
Several tissue sections analysed as one library Multi-section data needs a library column Pass library_key naming the observation column that maps libraries to observations

Free alternatives to Squidpy

Squidpy is one component of a Python stack, and some neighbours in that stack cover parts of the same work. The table lists only roles stated in the Squidpy documentation or in the pages linked here.

Tool How it relates to Squidpy
Scanpy The single-cell toolkit Squidpy builds on. The Squidpy tutorial uses it for scaling, PCA, neighbours and Leiden clustering of image features
AnnData The annotated data container Squidpy reads and writes; results land in adata.uns, adata.obsp and adata.obsm
SpatialData A scverse framework for spatial omics data. nhood_enrichment accepts a SpatialData object with table_key; see the CASRAI guide to SpatialData
napari-spatialdata The interactive viewer that replaced the Squidpy napari plugin, installed with pip install napari-spatialdata

For the underlying statistics of spatial dependence outside any single package, the CASRAI guide to spatial data analysis explains autocorrelation and related methods. Researchers who work on trajectories rather than tissue layout may instead want the guide to Monocle 3.

Frequently asked questions

What is Squidpy used for?

Squidpy analyses and visualises spatial molecular data using spatial coordinates and tissue images. Typical outputs are neighbourhood graphs, cluster neighbourhood enrichment, co-occurrence, ligand-receptor permutation tests and spatially variable genes, plus image features for large tissue images.

Which Python version does Squidpy need?

The installation page of the stable documentation states Python 3.11 or newer.

How do I install Squidpy?

Run pip install squidpy, or conda install -c conda-forge squidpy. Add pip install napari-spatialdata if you want interactive visualisation.

Does Squidpy work with SpatialData objects?

The documented nhood_enrichment function accepts either an AnnData or a SpatialData object. For SpatialData, give the table_key of the table to analyse.

How do I cite Squidpy?

The documentation gives Palla, Spitzer and colleagues, Nature Methods 2022, doi 10.1038/s41592-021-01358-2. Also report the Squidpy version and the neighbourhood-graph settings you used.

Sources

Data: Squidpy 1.8.4 graph-module functions and what each computes

Functions of the squidpy.gr module as listed in the Squidpy 1.8.4 stable documentation, with the one-line description the documentation gives for each. Compiled from the Squidpy graph module reference page, checked 2026-11-20.

Squidpy 1.8.4 graph-module functions and what each computes
FunctionDocumented purposeTypical question
gr.nhood_enrichmentCompute neighborhood enrichment by permutation testWhich clusters sit next to each other more often than chance?
gr.co_occurrenceCompute co-occurrence probability of clustersHow does cluster co-occurrence change with distance?
gr.spatial_autocorrCalculate Global Autocorrelation Statistic (Moran's I or Geary's C)Which genes are spatially patterned?
gr.ripleyCalculate various Ripley's statistics for point processesAre points clustered or dispersed across scales?
gr.ligrecPermutation test for ligand-receptor analysis, as in the CellPhoneDB work (Efremova et al., 2020)Which ligand-receptor pairs differ between cluster pairs?
gr.sepalIdentify spatially variable genes with SepalWhich genes are spatially variable?
gr.centrality_scoresCompute centrality scores per cluster or cell typeHow central is each cluster in the graph?
gr.interaction_matrixCompute interaction matrix for clustersHow many graph edges join each pair of clusters?
gr.mask_graphMask the graph based on a polygon maskRestrict analysis to a tissue region

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about Squidpy: Spatial Omics Analysis in Python, Install and Workflow

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →