Skip to content

Plotting

Static matplotlib scatter plot of embeddings colored by RGB values (pipeline step 4).

plot_embedding

plot_embedding(
    adata_or_coords: object,
    rgb: RGBResult | NDArray,
    *,
    basis: str | None = None,
    components: tuple[int, int] = (0, 1),
    legend: bool = True,
    legend_style: Literal["inset", "side"] = "inset",
    legend_loc: str = "lower right",
    legend_size: float = 0.3,
    legend_resolution: int = 128,
    legend_kwargs: dict | None = None,
    method: str | None = None,
    gene_set_names: list[str] | None = None,
    colors: list[tuple[float, float, float]] | None = None,
    point_size: float | None = None,
    alpha: float = 1.0,
    figsize: tuple[float, float] = (4.0, 4.0),
    dpi: int = 100,
    title: str | None = None,
    ax: Axes | None = None,
    show: bool = True,
) -> Axes | None

Plot embedding coordinates coloured by projected RGB values.

Parameters:

Name Type Description Default
adata_or_coords object

An AnnData object (with basis in .obsm) or a raw (n_cells, 2) coordinate array.

required
rgb RGBResult | NDArray

:class:RGBResult from blend_to_rgb/reduce_to_rgb, or a plain (n_cells, 3) RGB array. When an RGBResult is passed the method, gene_set_names and colors metadata are used automatically (explicit parameters still override).

required
basis str | None

Full obsm key name (e.g. "X_umap", "umap_consensus"). Required when adata_or_coords is AnnData.

None
components tuple[int, int]

Which two components to plot (0-indexed).

(0, 1)
legend bool

Whether to add a colour-space legend.

True
legend_style Literal['inset', 'side']

"inset" (default) or "side".

'inset'
legend_loc str

Position for inset legends ("lower right", etc.).

'lower right'
legend_size float

Size of the legend as a fraction of the plot area (0-1).

0.3
legend_resolution int

Pixel resolution of the legend image.

128
legend_kwargs dict | None

Extra keyword arguments forwarded to render_legend (excluding resolution, which is controlled by legend_resolution).

None
method str | None

"direct", "pca", "nmf" etc. — needed to select the legend type. Inferred from rgb when it is an RGBResult. If None and legend=True with a plain ndarray, a ValueError is raised.

None
gene_set_names list[str] | None

Gene set labels for the legend. Inferred from rgb when it is an RGBResult.

None
colors list[tuple[float, float, float]] | None

Base colours for direct-mode legends.

None
point_size float | None

Scatter point size. Default: 120_000 / n_cells.

None
alpha float

Scatter point opacity.

1.0
figsize tuple[float, float]

Figure size (inches) when creating a new figure.

(4.0, 4.0)
dpi int

Figure resolution when creating a new figure.

100
title str | None

Plot title.

None
ax Axes | None

Pre-existing axes to draw on. A new figure is created if None.

None
show bool

If True, call plt.show() and return None. If False, return the axes (scanpy convention).

True

Returns:

Type Description
Axes or None

The axes when show=False; None when show=True.

Source code in src/multiscoresplot/_plotting.py
def plot_embedding(
    adata_or_coords: object,
    rgb: RGBResult | NDArray,
    *,
    basis: str | None = None,
    components: tuple[int, int] = (0, 1),
    # legend
    legend: bool = True,
    legend_style: Literal["inset", "side"] = "inset",
    legend_loc: str = "lower right",
    legend_size: float = 0.30,
    legend_resolution: int = 128,
    legend_kwargs: dict | None = None,
    # legend metadata (overrides RGBResult when provided)
    method: str | None = None,
    gene_set_names: list[str] | None = None,
    colors: list[tuple[float, float, float]] | None = None,
    # scatter
    point_size: float | None = None,
    alpha: float = 1.0,
    # figure
    figsize: tuple[float, float] = (4.0, 4.0),
    dpi: int = 100,
    title: str | None = None,
    ax: Axes | None = None,
    show: bool = True,
) -> Axes | None:
    """Plot embedding coordinates coloured by projected RGB values.

    Parameters
    ----------
    adata_or_coords
        An ``AnnData`` object (with *basis* in ``.obsm``) or a raw
        ``(n_cells, 2)`` coordinate array.
    rgb
        :class:`RGBResult` from ``blend_to_rgb``/``reduce_to_rgb``, or a
        plain ``(n_cells, 3)`` RGB array.  When an ``RGBResult`` is passed
        the ``method``, ``gene_set_names`` and ``colors`` metadata are used
        automatically (explicit parameters still override).
    basis
        Full obsm key name (e.g. ``"X_umap"``, ``"umap_consensus"``).
        Required when *adata_or_coords* is AnnData.
    components
        Which two components to plot (0-indexed).
    legend
        Whether to add a colour-space legend.
    legend_style
        ``"inset"`` (default) or ``"side"``.
    legend_loc
        Position for inset legends (``"lower right"``, etc.).
    legend_size
        Size of the legend as a fraction of the plot area (0-1).
    legend_resolution
        Pixel resolution of the legend image.
    legend_kwargs
        Extra keyword arguments forwarded to ``render_legend``
        (excluding *resolution*, which is controlled by *legend_resolution*).
    method
        ``"direct"``, ``"pca"``, ``"nmf"`` etc. — needed to select the
        legend type.  Inferred from *rgb* when it is an ``RGBResult``.
        If *None* and ``legend=True`` with a plain ndarray, a
        ``ValueError`` is raised.
    gene_set_names
        Gene set labels for the legend.  Inferred from *rgb* when it is
        an ``RGBResult``.
    colors
        Base colours for direct-mode legends.
    point_size
        Scatter point size.  Default: ``120_000 / n_cells``.
    alpha
        Scatter point opacity.
    figsize
        Figure size (inches) when creating a new figure.
    dpi
        Figure resolution when creating a new figure.
    title
        Plot title.
    ax
        Pre-existing axes to draw on.  A new figure is created if *None*.
    show
        If *True*, call ``plt.show()`` and return *None*.  If *False*,
        return the axes (scanpy convention).

    Returns
    -------
    Axes or None
        The axes when ``show=False``; *None* when ``show=True``.
    """
    import matplotlib.pyplot as plt

    # Unpack RGBResult metadata
    rgb_arr, meta_method, meta_names, meta_colors = _unpack_rgb(rgb)
    eff_method = method if method is not None else meta_method
    eff_names = gene_set_names if gene_set_names is not None else meta_names
    eff_colors = colors if colors is not None else meta_colors

    coords, basis_label = _extract_coords(adata_or_coords, basis, components)
    n_cells = coords.shape[0]
    rgb_arr = _validate_rgb(rgb_arr, n_cells)

    if point_size is None:
        point_size = 120_000 / n_cells

    # Create figure / axes
    if ax is None:
        fig, ax = plt.subplots(figsize=figsize, dpi=dpi)
    else:
        fig = ax.figure  # type: ignore[assignment]

    # Scatter
    ax.scatter(
        coords[:, 0],
        coords[:, 1],
        c=rgb_arr,
        s=point_size,
        marker=".",
        edgecolors="none",
        alpha=alpha,
        plotnonfinite=True,
    )

    _style_axes(ax, basis_label, title, components)

    # Legend
    if legend:
        if eff_method is None:
            raise ValueError(
                "Cannot draw legend: 'method' is unknown. Pass method= explicitly "
                "or use an RGBResult from blend_to_rgb()/reduce_to_rgb()."
            )
        _add_legend(
            fig,
            ax,
            legend_style=legend_style,
            legend_loc=legend_loc,
            legend_size=legend_size,
            legend_resolution=legend_resolution,
            legend_kwargs=legend_kwargs,
            method=eff_method,
            gene_set_names=eff_names,
            colors=eff_colors,
        )

    if show:
        if matplotlib.is_interactive():
            plt.show()
        return None

    return ax