visualize_nearest_neighbor

spac.visualization.visualize_nearest_neighbor(adata, annotation, distance_from, distance_to=None, stratify_by=None, spatial_distance='spatial_distance', facet_plot=False, method=None, plot_type=None, log=False, annotation_colorscale='rainbow', defined_color_map=None, ax=None, **kwargs)[source]

Visualize nearest-neighbor (spatial distance) data between groups of cells with optional pin-color map via numeric or distribution plots.

This landing function first constructs a tidy long-form DataFrame via function _prepare_spatial_distance_data, then dispatches plotting to function _plot_spatial_distance_dispatch. A pin-color feature guarantees consistent mapping from annotation labels to colors across figures, drawing the mapping from adata.uns (if present) or generating one automatically through spac.utils.color_mapping.

Plot arrangement logic:
  1. If stratify_by is not None and facet_plot=True => single figure with subplots (faceted).

  2. If stratify_by is not None and facet_plot=False => multiple separate figures, one per group.

  3. 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.

  • 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.

  • 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’.

  • facet_plot (bool, optional) – If True (and stratify_by is not None), subplots in a single figure. Otherwise, multiple or single figure(s).

  • method ({'numeric', 'distribution'}) – Determines the plotting style (catplot vs displot).

  • plot_type (str or None, optional) – Specific seaborn plot kind. If None, sensible defaults are selected (‘boxen’ for numeric, ‘violin’ for distribution). For method=’numeric’: ‘box’, ‘violin’, ‘boxen’, ‘strip’, ‘swarm’. For method=’distribution’: ‘hist’, ‘kde’, ‘ecdf’.

  • log (bool, optional) – If True, applies np.log1p transform to the distance values.

  • annotation_colorscale (str, optional) – Matplotlib colormap name used when auto-enerating a new mapping. Ignored if ‘defined_color_map’ is provided.

  • defined_color_map (str, optional) – Key in ‘adata.uns’ holding a pre-computed color dictionary. Falls back to automatic generation from ‘annotation’ values.

  • ax (matplotlib.axes.Axes, optional) – The matplotlib Axes containing the analysis plots. The returned ax is the passed ax or new ax created. Only works if plotting a single component. Default is None.

  • **kwargs (dict) – Additional arguments for seaborn figure-level functions.

Returns:

{

‘data’: pd.DataFrame, # long-form table for plotting ‘fig’ : matplotlib.figure.Figure | list[Figure] | None, ‘ax’: matplotlib.axes.Axes | list[matplotlib.axes.Axes], ‘palette’: dict # {label: ‘#rrggbb’}

}

Return type:

dict

Raises:

ValueError – If required parameters are invalid.

Examples

>>> res = visualize_nearest_neighbor(
...     adata=my_adata,
...     annotation='cell_type',
...     distance_from='Tumour',
...     distance_to=['Stroma', 'B cell'],
...     method='numeric',
...     plot_type='box',
...     facet_plot=True,
...     stratify_by='image_id',
...     defined_color_map='pin_color_map'
... )
>>> fig = res['fig']      # matplotlib.figure.Figure
>>> ax_list = res['ax']   # list[matplotlib.axes.Axes] (faceted plot)
>>> df  = res['data']     # long-form DataFrame
>>> ax_list[0].set_title('Tumour → Stroma distances')