- spac.visualization.visualize_nearest_neighbor(adata, annotation, stratify_by=None, spatial_distance='spatial_distance', distance_from=None, distance_to=None, facet_plot=False, plot_type=None, log=False, method=None, **kwargs)[source]
Visualize nearest-neighbor (spatial distance) data between groups of cells as numeric or distribution plots.
This user-facing function assembles the data by calling _prepare_spatial_distance_data and then creates plots through _plot_spatial_distance_dispatch.
- Plot arrangement logic:
If stratify_by is not None and facet_plot=True => single figure with subplots (faceted).
If stratify_by is not None and facet_plot=False => multiple separate figures, one per group.
If stratify_by is None => a single figure with one plot.
- Parameters:
adata (anndata.AnnData) – Annotated data matrix with distances in adata.obsm[spatial_distance].
annotation (str) – Column in adata.obs containing cell phenotypes or annotations.
stratify_by (str, optional) – Column in adata.obs used to group or stratify data (e.g. imageid).
spatial_distance (str, optional) – Key in adata.obsm storing the distance DataFrame. Default is ‘spatial_distance’.
distance_from (str) – Reference phenotype from which distances are measured. Required.
distance_to (str or list of str, optional) – Target phenotype(s) to measure distance to. If None, uses all available phenotypes.
facet_plot (bool, optional) – If True (and stratify_by is not None), subplots in a single figure. Else, multiple or single figure(s).
plot_type (str, optional) – For method=’numeric’: ‘box’, ‘violin’, ‘boxen’, etc. For method=’distribution’: ‘hist’, ‘kde’, ‘ecdf’, etc.
log (bool, optional) – If True, applies np.log1p transform to the distance values.
method ({'numeric', 'distribution'}) – Determines the plotting style (catplot vs displot).
**kwargs (dict) – Additional arguments for seaborn figure-level functions.
- Returns:
- {
“data”: pd.DataFrame, # Tidy DataFrame used for plotting “fig”: Figure or list[Figure] # Single or multiple figures
}
- Return type:
dict
- Raises:
ValueError – If required parameters are missing or invalid.
Examples
>>> # Numeric box plot comparing Tumor distances to multiple targets >>> res = visualize_nearest_neighbor( ... adata=my_adata, ... annotation='cell_type', ... stratify_by='sample_id', ... spatial_distance='spatial_distance', ... distance_from='Tumor', ... distance_to=['Stroma', 'Immune'], ... facet_plot=True, ... plot_type='box', ... method='numeric' ... ) >>> df_long, fig = res["data"], res["fig"]
>>> # Distribution plot (kde) for a single target, single figure >>> res2 = visualize_nearest_neighbor( ... adata=my_adata, ... annotation='cell_type', ... distance_from='Tumor', ... distance_to='Stroma', ... method='distribution', ... plot_type='kde' ... ) >>> df_dist, fig2 = res2["data"], res2["fig"]