spatial_segment

spatial_segment#

squidpy.pl.spatial_segment(adata, *, color=None, groups=None, library_id=None, library_key=None, spatial_key='spatial', img=True, img_res_key='hires', img_alpha=None, img_cmap=None, img_channel=None, seg=None, seg_key='segmentation', seg_cell_id=None, seg_contourpx=None, seg_outline=False, use_raw=None, layer=None, alt_var=None, crop_coord=None, cmap=None, palette=None, alpha=1.0, norm=None, na_color=(0, 0, 0, 0), connectivity_key=None, edges_width=1.0, edges_color='grey', library_first=True, frameon=None, wspace=None, hspace=0.25, ncols=4, outline=False, outline_color=('black', 'white'), outline_width=(0.3, 0.05), legend_loc='right margin', legend_fontsize=None, legend_fontweight='bold', legend_fontoutline=None, legend_na=True, colorbar=True, scalebar_dx=None, scalebar_units=None, title=None, axis_label=None, fig=None, ax=None, return_ax=False, figsize=None, dpi=None, save=None, scalebar_kwargs=mappingproxy({}), edges_kwargs=mappingproxy({}), **kwargs)[source]#

Plot spatial omics data with segmentation masks on top.

Argument seg_cell_id in anndata.AnnData.obs controls unique segmentation mask’s ids to be plotted. By default, 'segmentation', seg_key for the segmentation and 'hires' for the image is attempted.

  • Use seg_key to display the image in the background.

  • Use seg_contourpx or seg_outline to control how the segmentation mask is displayed.

Use library_id to select the image. If multiple library_id are available, use library_key in anndata.AnnData.obs to plot the subsets. Use crop_coord to crop the spatial plot based on coordinate boundaries.

This function has few key assumptions about how coordinates and libraries are handled:

  • The arguments library_key and library_id control which dataset is plotted. If multiple libraries are present, specifying solely library_key will suffice, and all unique libraries will be plotted sequentially. To select specific libraries, use the library_id argument.

  • The argument color controls which features in obs/var are plotted. They are plotted for all available/specified libraries. The argument groups can be used to select categories to be plotted. This is valid only for categorical features in anndata.AnnData.obs.

  • If multiple library_id are available, arguments such as size and crop_coord accept lists to selectively customize different library_id plots. This requires that the length of such lists matches the number of unique libraries in the dataset.

  • Coordinates are in the pixel space of the source image, so an equal aspect ratio is assumed.

  • The origin (0, 0) is on the top left, as is common convention with image data.

  • The plotted points (dots) do not have a real “size” but it is relative to their coordinate/pixel space. This does not hold if no image is plotted, then the size corresponds to points size passed to matplotlib.axes.Axes.scatter().

If anndata.AnnData.uns ['spatial'] is present, use img_res_key, seg_key and size_key arguments to find values for img, seg and size. Alternatively, these values can be passed directly via img.

See also

Parameters:
adata AnnData

Annotated data object.

seg_cell_id str | None (default: None)

Column in anndata.AnnData.obs with unique segmentation mask ids. Required to filter valid segmentation masks.

seg bool | NDArray[Any] | Sequence[NDArray[Any]] | None (default: None)

Whether to plot the segmentation mask. One (or more) numpy.ndarray can also be passed for plotting.

seg_key str | None (default: 'segmentation')

Key of segmentation mask in anndata.AnnData.uns.

seg_contourpx int | None (default: None)

Draw contour of specified width for each segment. If None, fills entire segment, see skimage.morphology.erosion().

seg_outline bool (default: False)

Whether to plot boundaries around segmentation masks.

color str | Sequence[str | None] | None (default: None)

Key for annotations in anndata.AnnData.obs or variables/genes.

groups str | Sequence[str] | None (default: None)

For discrete annotation in color, select which values to plot (other values are set to NAs).

library_id str | Sequence[str] | None (default: None)

Name of the Z-dimension(s) that this function should be applied to. For not specified Z-dimensions, the identity function is applied.

library_key str | None (default: None)

If multiple library_id, column in anndata.AnnData.obs which stores mapping between library_id and obs.

spatial_key str (default: 'spatial')

Key in anndata.AnnData.obsm where spatial coordinates are stored.

img bool | NDArray[Any] | Sequence[NDArray[Any]] | None (default: True)

Whether to plot the image. One (or more) numpy.ndarray can also be passed for plotting.

img_res_key str | None (default: 'hires')

Key for image resolution, used to get img and scale_factor from 'images' and 'scalefactors' entries for this library.

img_alpha float | None (default: None)

Alpha value for the underlying image.

image_cmap

Colormap for the image, see matplotlib.colors.Colormap.

img_channel int | list[int] | None (default: None)

To select which channel to plot (all by default).

use_raw bool | None (default: None)

If True, use anndata.AnnData.raw.

layer str | None (default: None)

Key in anndata.AnnData.layers or None for anndata.AnnData.X.

alt_var str | None (default: None)

Which column to use in anndata.AnnData.var to select alternative var_name.

size

Size of the scatter point/shape. In case of spatial_shape it represents to the scaling factor for shape (accessed via size_key). In case of spatial_point, it represents the size argument in matplotlib.pyplot.scatter().

size_key

Key of of pixel size of shapes to be plotted, stored in anndata.AnnData.uns. Only needed for spatial_shape.

scale_factor

Scaling factor used to map from coordinate space to pixel space. Found by default if library_id and img_res_key can be resolved. Otherwise, defaults to 1.

crop_coord tuple[int, int, int, int] | Sequence[tuple[int, int, int, int]] | None (default: None)

Coordinates to use for cropping the image (left, right, top, bottom). These coordinates are expected to be in pixel space (same as spatial) and will be transformed by scale_factor. If not provided, image is automatically cropped to bounds of spatial, plus a border.

cmap str | Colormap | None (default: None)

Colormap for continuous annotations, see matplotlib.colors.Colormap.

palette str | ListedColormap | None (default: None)

Palette for discrete annotations, see matplotlib.colors.Colormap.

alpha float (default: 1.0)

Alpha value for scatter point/shape.

norm Normalize | Sequence[Normalize] | None (default: None)

Colormap normalization for continuous annotations, see matplotlib.colors.Normalize.

na_color str | tuple[float, ...] (default: (0, 0, 0, 0))

Color to be used for NAs values, if present.

connectivity_key str | None (default: None)

Key for neighbors graph to plot. Default is: anndata.AnnData.obsp ['spatial_connectivities'].

edges_width float (default: 1.0)

Width of the edges. Only used when connectivity_key != None .

edges_color str | Sequence[str] | Sequence[float] (default: 'grey')

Color of the edges.

library_first bool (default: True)

If multiple libraries are plotted, set the plotting order with respect to color.

frameon bool | None (default: None)

If True, draw a frame around the panels.

wspace float | None (default: None)

Width space between panels.

hspace float (default: 0.25)

Height space between panels.

ncols int (default: 4)

Number of panels per row.

outline bool (default: False)

If True, a thin border around points/shapes is plotted.

outline_color tuple[str, str] (default: ('black', 'white'))

Color of the border.

outline_width tuple[float, float] (default: (0.3, 0.05))

Width of the border.

legend_loc str | None (default: 'right margin')

Location of the legend, see matplotlib.legend.Legend.

legend_fontsize int | float | Literal['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'] | None (default: None)

Font size of the legend, see matplotlib.text.Text.set_fontsize().

legend_fontweight int | Literal['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black'] (default: 'bold')

Font weight of the legend, see matplotlib.text.Text.set_fontweight().

legend_fontoutline int | None (default: None)

Font outline of the legend, see matplotlib.patheffects.withStroke.

legend_na bool (default: True)

Whether to show NA values in the legend.

colorbar bool (default: True)

Whether to show the colorbar, see matplotlib.pyplot.colorbar().

scalebar_dx float | Sequence[float] | None (default: None)

Size of one pixel in units specified by scalebar_units.

scalebar_units str | Sequence[str] | None (default: None)

Units of scalebar_dx.

title str | Sequence[str] | None (default: None)

Panel titles.

axis_label str | Sequence[str] | None (default: None)

Panel axis labels.

fig Figure | None (default: None)

Optional matplotlib.figure.Figure to use.

ax Axes | Sequence[Axes] | None (default: None)

Optional matplotlib.axes.Axes to use.

return_ax bool (default: False)

Whether to return matplotlib.axes.Axes object(s).

figsize tuple[float, float] | None (default: None)

Size of the figure in inches.

dpi int | None (default: None)

Dots per inch.

save str | Path | None (default: None)

Whether to save the plot.

scalebar_kwargs Mapping[str, Any] (default: mappingproxy({}))

Keyword arguments for matplotlib_scalebar.ScaleBar.

edges_kwargs Mapping[str, Any] (default: mappingproxy({}))

Keyword arguments for networkx.drawing.nx_pylab.draw_networkx_edges() [Hagberg et al., 2008].

kwargs Any

Keyword arguments for matplotlib.pyplot.scatter() or matplotlib.pyplot.imshow().

Returns:

Axes | Sequence[Axes] | None – Nothing, just plots the figure and optionally saves the plot.