plotomics

plotomics: high-performance bioinformatics visualization widgets.

Each component is an anywidget backed by a shared JavaScript core, designed to render large biological datasets smoothly in Jupyter, JupyterLab, marimo, Colab, VS Code, Shiny for Python and Streamlit.

Add new components here, keeping the list sorted so parallel PRs append cleanly.

 1"""plotomics: high-performance bioinformatics visualization widgets.
 2
 3Each component is an anywidget backed by a shared JavaScript core, designed to
 4render large biological datasets smoothly in Jupyter, JupyterLab, marimo,
 5Colab, VS Code, Shiny for Python and Streamlit.
 6
 7Add new components here, keeping the list sorted so parallel PRs append cleanly.
 8"""
 9
10from __future__ import annotations
11
12from ._base import PlotomicsWidget, pack_columns
13from .heatmap import Heatmap
14from .gosling import Gosling
15from .network import Network
16from .clustermap import Clustermap
17from .dotplot import Dotplot
18from .hic import HiC
19from .igv import IGV
20from .km import Km
21from .lollipop import Lollipop
22from .oncoplot import Oncoplot
23from .profile import Profile
24from .spatial import Spatial
25from .treemap import Treemap
26from .upset import Upset, upset_intersections
27from .violin import Violin, violin_density
28from .volcano import Volcano
29from .embedding import Embedding
30
31__all__ = [
32    "PlotomicsWidget",
33    "pack_columns",
34    "Heatmap",
35    "Gosling",
36    "Network",
37    "Clustermap",
38    "Dotplot",
39    "HiC",
40    "IGV",
41    "Km",
42    "Lollipop",
43    "Oncoplot",
44    "Profile",
45    "Spatial",
46    "Treemap",
47    "Upset",
48    "Violin",
49    "upset_intersections",
50    "violin_density",
51    "Volcano",
52    "Embedding",
53]
54
55__version__ = "0.2.0"
class PlotomicsWidget(anywidget.widget.AnyWidget):
330class PlotomicsWidget(anywidget.AnyWidget):
331    """Base class for all plotomics widgets.
332
333    Trait names mirror the JS adapter contract in
334    ``plotomics`` (``lib/anywidget.ts``).
335    """
336
337    # JSON side-channel: string columns + non-columnar metadata.
338    data = traitlets.Dict({"columns": {}, "meta": {}}).tag(sync=True)
339    """Text columns and metadata, sent to the browser as JSON."""
340    # Binary numeric columns + their schema.
341    buffer = traitlets.Bytes(b"").tag(sync=True)
342    """Numeric columns, packed into one binary buffer."""
343    schema = traitlets.Dict({"columns": []}).tag(sync=True)
344    """Name, type, length and byte offset of each column in the buffer."""
345    # Component options (camelCase keys, matching the TS options interface).
346    options = traitlets.Dict({}).tag(sync=True)
347    """Options of the plot, with the camelCase keys of the JavaScript."""
348    _height = traitlets.Int(480).tag(sync=True)
349    # JS -> Python: the latest selection from the component. Its shape depends on
350    # the component: a list of point indices for a lasso selection (Embedding),
351    # or a single clicked node id (a string) or None for a click selection
352    # (Network). Observe it with ``widget.observe(fn, names="selected")``.
353    selected = traitlets.Any(default_value=[]).tag(sync=True)
354    """The latest selection in the browser.
355
356    A list of point indices for a lasso selection in an Embedding, or the id
357    of the clicked node (a string), or None, in a Network. Observe it with
358    ``widget.observe(fn, names="selected")``.
359    """
360    # Whether ``options["theme"]`` is a plotomics theme, whose padding is
361    # checked. Gosling takes a Gosling theme there.
362    _plotomics_theme = True
363
364    @traitlets.validate("options")
365    def _validate_options(self, proposal: Any) -> dict[str, Any]:
366        options = proposal["value"]
367        if not self._plotomics_theme:
368            return options
369        return _check_theme_padding(options)
370
371    def export(self, fmt: str = "png") -> None:
372        """Download the current on-screen view as ``"png"`` or ``"svg"``.
373
374        The figure is rendered in the browser, so this posts a message to the
375        front-end which performs the download; nothing is returned to Python.
376        """
377        if fmt not in ("png", "svg"):
378            raise ValueError(f"fmt must be 'png' or 'svg', got {fmt!r}")
379        self.send({"plotomics": "export", "format": fmt})

Base class for all plotomics widgets.

Trait names mirror the JS adapter contract in plotomics (lib/anywidget.ts).

data

Text columns and metadata, sent to the browser as JSON.

buffer

Numeric columns, packed into one binary buffer.

schema

Name, type, length and byte offset of each column in the buffer.

options

Options of the plot, with the camelCase keys of the JavaScript.

selected

The latest selection in the browser.

A list of point indices for a lasso selection in an Embedding, or the id of the clicked node (a string), or None, in a Network. Observe it with widget.observe(fn, names="selected").

def export(self, fmt: str = 'png') -> None:
371    def export(self, fmt: str = "png") -> None:
372        """Download the current on-screen view as ``"png"`` or ``"svg"``.
373
374        The figure is rendered in the browser, so this posts a message to the
375        front-end which performs the download; nothing is returned to Python.
376        """
377        if fmt not in ("png", "svg"):
378            raise ValueError(f"fmt must be 'png' or 'svg', got {fmt!r}")
379        self.send({"plotomics": "export", "format": fmt})

Download the current on-screen view as "png" or "svg".

The figure is rendered in the browser, so this posts a message to the front-end which performs the download; nothing is returned to Python.

def pack_columns( numeric: Mapping[str, Any], *, equal_length: bool = True, quiet: Any = (), names: Optional[Mapping[str, str]] = None) -> tuple[bytes, dict]:
162def pack_columns(
163    numeric: Mapping[str, Any],
164    *,
165    equal_length: bool = True,
166    quiet: Any = (),
167    names: Mapping[str, str] | None = None,
168) -> tuple[bytes, dict]:
169    """Pack named numeric columns into one buffer + a ``BufferSchema`` dict.
170
171    Parameters
172    ----------
173    numeric:
174        Mapping of column name to array-like numeric values.
175    equal_length:
176        When ``True`` (default) every column must have the same length; a
177        mismatch raises ``ValueError`` naming the columns and their lengths.
178        Pass ``False`` when intentionally packing columns of different lengths
179        (e.g. per-node and per-edge columns share one buffer in ``network``).
180    quiet:
181        Names of columns whose NaN/Inf values are not warned about here,
182        because the caller warns about them in its own words.
183    names:
184        The name a warning or an error gives a column, where the user passed
185        it under another name, such as the ``matrix`` packed as ``values``.
186        A column not in it goes by its own name.
187    """
188    names = names or {}
189    converted: list[tuple[str, np.ndarray, str]] = []
190    for name, values in numeric.items():
191        arr, dtype = _to_transport(
192            np.asarray(values), names.get(name, name), warn=name not in quiet
193        )
194        converted.append((name, arr, dtype))
195
196    if equal_length and len(converted) > 1:
197        sizes = {name: int(arr.size) for name, arr, _ in converted}
198        if len(set(sizes.values())) > 1:
199            detail = ", ".join(f"{n}={s}" for n, s in sizes.items())
200            raise ValueError(
201                f"columns must all have the same length; got {detail}"
202            )
203
204    buf = bytearray()
205    specs: list[dict] = []
206    offset = 0
207    for name, arr, dtype in converted:
208        raw = arr.tobytes()
209        specs.append(
210            {
211                "name": name,
212                "dtype": dtype,
213                "length": int(arr.size),
214                "byteOffset": offset,
215            }
216        )
217        buf.extend(raw)
218        offset += len(raw)
219    return bytes(buf), {"columns": specs}

Pack named numeric columns into one buffer + a BufferSchema dict.

Parameters
  • numeric:: Mapping of column name to array-like numeric values.
  • equal_length:: When True (default) every column must have the same length; a mismatch raises ValueError naming the columns and their lengths. Pass False when intentionally packing columns of different lengths (e.g. per-node and per-edge columns share one buffer in network).
  • quiet:: Names of columns whose NaN/Inf values are not warned about here, because the caller warns about them in its own words.
  • names:: The name a warning or an error gives a column, where the user passed it under another name, such as the matrix packed as values. A column not in it goes by its own name.
class Heatmap(plotomics.PlotomicsWidget):
 22class Heatmap(PlotomicsWidget):
 23    """GPU-accelerated heatmap for large expression matrices (samples x genes).
 24
 25    The matrix is packed as a single row-major ``float32`` column and uploaded
 26    to the GPU as one texture, colormapped in a fragment shader, so matrices
 27    with a million or more cells pan and zoom smoothly. The colorbar legend and
 28    row/column tick labels are drawn as vector overlays. A matrix with more
 29    rows or columns than the plot has pixels is pooled for drawing: each pixel
 30    shows the mean of the cells under it, so a lone outlier row still shows,
 31    fainter the more rows share its pixel. A matrix with more rows or columns
 32    than the GPU's texture limit is averaged in blocks of two or more rows (or
 33    columns) to fit it. Zoomed in until each row and column in view has a
 34    pixel of its own, the view shows every row and column once it stops
 35    moving.
 36
 37    In R this plot is ``bioheatmap()``, with the alias
 38    ``heatmap_plotomics()``. A function named ``heatmap()`` would mask
 39    ``stats::heatmap()`` when the R package is attached. Python has no such
 40    clash, so the class keeps the name ``Heatmap``.
 41
 42    Parameters
 43    ----------
 44    matrix:
 45        A 2-D ``numpy`` array, nested list or ``pandas`` DataFrame of shape
 46        ``(nrows, ncols)``. For a DataFrame, the index becomes the row labels
 47        and the columns become the column labels. A missing cell (NaN, or NA
 48        in a nullable column) is drawn grey and left out of the colour range
 49        and the z-score. Where several rows or columns share a pixel, the
 50        pixel shows the mean of their finite cells, so it is grey only when
 51        all of them are missing.
 52    colormap:
 53        Color ramp: sequential ``"viridis"`` or ``"ltc"`` (an earthy teal to
 54        sand to rust ramp), or diverging ``"rdbu"`` or ``"ltcdiv"`` (its
 55        counterpart, neutral cream at the midpoint). ``None`` (the default)
 56        uses ``"rdbu"`` when ``z_score`` is on, so values above and below the
 57        row mean get opposite colours, and ``"viridis"`` otherwise.
 58    z_score:
 59        If ``True``, each row is z-score normalized before coloring.
 60    vmin, vmax:
 61        Lower/upper clamp of the color domain. ``None`` (the default)
 62        auto-scales from the data. For a diverging colormap the auto domain is
 63        symmetric about zero, and a positive ``vmax`` or a negative ``vmin``
 64        given alone is mirrored about zero, so zero keeps the neutral colour.
 65    show_colorbar:
 66        Draw the colorbar legend.
 67    legend_title:
 68        Colorbar title. ``None`` (the default) uses ``"value"``, or
 69        ``"z-score"`` when ``z_score=True``.
 70    row_labels, col_labels:
 71        Optional explicit labels; override any inferred from a DataFrame.
 72    theme:
 73        Optional theme overrides forwarded to the JS renderer. Its
 74        ``padding`` entry is the space in px between the edge of the widget
 75        and the plot: one number for every side, or a dict with any of the
 76        keys ``top``, ``right``, ``bottom`` and ``left``, a side left out
 77        keeping the default of 10.
 78        A colour given as a CSS custom property, such as
 79        ``"background": "var(--bg)"``, takes the value the page gives it when
 80        the plot draws. After the page changes the property, what the plot
 81        drew on a canvas keeps the old colour until it draws again: resize
 82        the widget or display it again.
 83    height:
 84        Initial widget height in CSS pixels.
 85
 86    Examples
 87    --------
 88    >>> import numpy as np
 89    >>> m = np.random.randn(1000, 1000).astype(np.float32)
 90    >>> Heatmap(m, z_score=True)  # doctest: +SKIP
 91    """
 92
 93    _esm = STATIC / "heatmap.js"
 94
 95    def __init__(
 96        self,
 97        matrix: Any,
 98        *,
 99        colormap: Literal["viridis", "rdbu", "ltc", "ltcdiv"] | None = None,
100        z_score: bool = False,
101        vmin: float | None = None,
102        vmax: float | None = None,
103        show_colorbar: bool = True,
104        legend_title: str | None = None,
105        row_labels: list[str] | None = None,
106        col_labels: list[str] | None = None,
107        theme: dict | None = None,
108        height: int = 480,
109        **kwargs: Any,
110    ) -> None:
111        if colormap is not None:
112            _check_choice(colormap, "colormap", _COLORMAPS)
113
114        # A DataFrame gives its labels; a nested list or array gives none.
115        arr, inferred_rows, inferred_cols = _as_matrix(matrix)
116        if row_labels is None:
117            row_labels = inferred_rows
118        if col_labels is None:
119            col_labels = inferred_cols
120        if arr.ndim != 2:
121            raise ValueError("`matrix` must be a 2-D array or DataFrame.")
122        nrows, ncols = int(arr.shape[0]), int(arr.shape[1])
123        if nrows == 0 or ncols == 0:
124            raise ValueError("`matrix` must contain at least one row and one column.")
125
126        # Row-major flatten: element (r, c) at index r * ncols + c.
127        values = np.ascontiguousarray(arr).reshape(-1)
128        buffer, schema = pack_columns(
129            {"values": values}, names={"values": "matrix"}
130        )
131
132        meta: dict[str, Any] = {"nrows": nrows, "ncols": ncols}
133        rlabels = _check_labels(row_labels, nrows, "row_labels")
134        clabels = _check_labels(col_labels, ncols, "col_labels")
135        if rlabels is not None:
136            meta["rowLabels"] = rlabels
137        if clabels is not None:
138            meta["colLabels"] = clabels
139
140        # A None colormap lets the browser pick: "rdbu" for z-scores and
141        # "viridis" otherwise.
142        options: dict[str, Any] = {
143            "colormap": colormap,
144            "zScore": z_score,
145            "vmin": vmin,
146            "vmax": vmax,
147            "showColorbar": show_colorbar,
148            # None asks the browser for its default title.
149            "legendTitle": legend_title,
150        }
151        if theme is not None:
152            options["theme"] = theme
153
154        super().__init__(
155            buffer=buffer,
156            schema=schema,
157            data={"columns": {}, "meta": meta},
158            options=options,
159            _height=height,
160            **kwargs,
161        )

GPU-accelerated heatmap for large expression matrices (samples x genes).

The matrix is packed as a single row-major float32 column and uploaded to the GPU as one texture, colormapped in a fragment shader, so matrices with a million or more cells pan and zoom smoothly. The colorbar legend and row/column tick labels are drawn as vector overlays. A matrix with more rows or columns than the plot has pixels is pooled for drawing: each pixel shows the mean of the cells under it, so a lone outlier row still shows, fainter the more rows share its pixel. A matrix with more rows or columns than the GPU's texture limit is averaged in blocks of two or more rows (or columns) to fit it. Zoomed in until each row and column in view has a pixel of its own, the view shows every row and column once it stops moving.

In R this plot is bioheatmap(), with the alias heatmap_plotomics(). A function named heatmap() would mask stats::heatmap() when the R package is attached. Python has no such clash, so the class keeps the name Heatmap.

Parameters
  • matrix:: A 2-D numpy array, nested list or pandas DataFrame of shape (nrows, ncols). For a DataFrame, the index becomes the row labels and the columns become the column labels. A missing cell (NaN, or NA in a nullable column) is drawn grey and left out of the colour range and the z-score. Where several rows or columns share a pixel, the pixel shows the mean of their finite cells, so it is grey only when all of them are missing.
  • colormap:: Color ramp: sequential "viridis" or "ltc" (an earthy teal to sand to rust ramp), or diverging "rdbu" or "ltcdiv" (its counterpart, neutral cream at the midpoint). None (the default) uses "rdbu" when z_score is on, so values above and below the row mean get opposite colours, and "viridis" otherwise.
  • z_score:: If True, each row is z-score normalized before coloring.
  • vmin, vmax:: Lower/upper clamp of the color domain. None (the default) auto-scales from the data. For a diverging colormap the auto domain is symmetric about zero, and a positive vmax or a negative vmin given alone is mirrored about zero, so zero keeps the neutral colour.
  • show_colorbar:: Draw the colorbar legend.
  • legend_title:: Colorbar title. None (the default) uses "value", or "z-score" when z_score=True.
  • row_labels, col_labels:: Optional explicit labels; override any inferred from a DataFrame.
  • theme:: Optional theme overrides forwarded to the JS renderer. Its padding entry is the space in px between the edge of the widget and the plot: one number for every side, or a dict with any of the keys top, right, bottom and left, a side left out keeping the default of 10. A colour given as a CSS custom property, such as "background": "var(--bg)", takes the value the page gives it when the plot draws. After the page changes the property, what the plot drew on a canvas keeps the old colour until it draws again: resize the widget or display it again.
  • height:: Initial widget height in CSS pixels.
Examples
>>> import numpy as np
>>> m = np.random.randn(1000, 1000).astype(np.float32)
>>> Heatmap(m, z_score=True)  # doctest: +SKIP
Heatmap( matrix: Any, *, colormap: Optional[Literal['viridis', 'rdbu', 'ltc', 'ltcdiv']] = None, z_score: bool = False, vmin: float | None = None, vmax: float | None = None, show_colorbar: bool = True, legend_title: str | None = None, row_labels: list[str] | None = None, col_labels: list[str] | None = None, theme: dict | None = None, height: int = 480, **kwargs: Any)
 95    def __init__(
 96        self,
 97        matrix: Any,
 98        *,
 99        colormap: Literal["viridis", "rdbu", "ltc", "ltcdiv"] | None = None,
100        z_score: bool = False,
101        vmin: float | None = None,
102        vmax: float | None = None,
103        show_colorbar: bool = True,
104        legend_title: str | None = None,
105        row_labels: list[str] | None = None,
106        col_labels: list[str] | None = None,
107        theme: dict | None = None,
108        height: int = 480,
109        **kwargs: Any,
110    ) -> None:
111        if colormap is not None:
112            _check_choice(colormap, "colormap", _COLORMAPS)
113
114        # A DataFrame gives its labels; a nested list or array gives none.
115        arr, inferred_rows, inferred_cols = _as_matrix(matrix)
116        if row_labels is None:
117            row_labels = inferred_rows
118        if col_labels is None:
119            col_labels = inferred_cols
120        if arr.ndim != 2:
121            raise ValueError("`matrix` must be a 2-D array or DataFrame.")
122        nrows, ncols = int(arr.shape[0]), int(arr.shape[1])
123        if nrows == 0 or ncols == 0:
124            raise ValueError("`matrix` must contain at least one row and one column.")
125
126        # Row-major flatten: element (r, c) at index r * ncols + c.
127        values = np.ascontiguousarray(arr).reshape(-1)
128        buffer, schema = pack_columns(
129            {"values": values}, names={"values": "matrix"}
130        )
131
132        meta: dict[str, Any] = {"nrows": nrows, "ncols": ncols}
133        rlabels = _check_labels(row_labels, nrows, "row_labels")
134        clabels = _check_labels(col_labels, ncols, "col_labels")
135        if rlabels is not None:
136            meta["rowLabels"] = rlabels
137        if clabels is not None:
138            meta["colLabels"] = clabels
139
140        # A None colormap lets the browser pick: "rdbu" for z-scores and
141        # "viridis" otherwise.
142        options: dict[str, Any] = {
143            "colormap": colormap,
144            "zScore": z_score,
145            "vmin": vmin,
146            "vmax": vmax,
147            "showColorbar": show_colorbar,
148            # None asks the browser for its default title.
149            "legendTitle": legend_title,
150        }
151        if theme is not None:
152            options["theme"] = theme
153
154        super().__init__(
155            buffer=buffer,
156            schema=schema,
157            data={"columns": {}, "meta": meta},
158            options=options,
159            _height=height,
160            **kwargs,
161        )

Public constructor

class Gosling(plotomics.PlotomicsWidget):
 14class Gosling(PlotomicsWidget):
 15    """Declarative genomics figures powered by Gosling.js.
 16
 17    Gosling (grammar of scalable, linked, interactive nucleotide graphics) is
 18    fully config-driven: you pass a Gosling *specification* as a ``dict`` and
 19    data flows through the ``"data"`` blocks of the spec (tileset URLs, indexed
 20    BAM/BED/VCF/BigWig, or CSV/JSON URLs and inline values). Gosling streams and
 21    tiles large genomic datasets on the GPU via HiGlass, so there is no separate
 22    data argument.
 23
 24    Parameters
 25    ----------
 26    spec:
 27        A Gosling specification as a (nested) ``dict``. It is passed through
 28        verbatim to Gosling.js, so keys use Gosling's own camelCase names (e.g.
 29        ``tracks``, ``xDomain``, ``alignment``). Must contain at least one of
 30        ``tracks``, ``views``, ``arrangement``, ``alignment`` or ``template``.
 31    padding:
 32        Optional outer padding (pixels) forwarded to Gosling's embed options.
 33        The widget keeps the default padding of 10 px around Gosling, so the
 34        views sit this padding plus 10 px in, and 10 px in with a padding of
 35        0. ``None`` gives Gosling 50, so the views sit 60 px in, as with
 36        Gosling's own default.
 37    theme:
 38        Optional Gosling theme: a built-in name such as ``"light"``,
 39        ``"dark"`` or ``"ggplot"``, or a Gosling theme dict. This is
 40        Gosling's own theme, not the plotomics theme that every other widget
 41        takes. Gosling draws its own tracks, so no plotomics theme field
 42        applies: ``background``, ``foreground``, ``muted``, ``grid``,
 43        ``axis``, ``fontFamily``, ``fontSize``, ``categorical`` and
 44        ``padding`` are not read. Set colours and fonts in the Gosling theme
 45        or in the spec; the widget keeps the default padding of 10 px around
 46        Gosling.
 47    height:
 48        Initial widget height in CSS pixels.
 49
 50    Examples
 51    --------
 52    >>> spec = {
 53    ...     "responsiveSize": {"width": True},
 54    ...     "tracks": [
 55    ...         {
 56    ...             "data": {
 57    ...                 "url": "https://server.gosling-lang.org/api/v1/"
 58    ...                 "tileset_info/?d=cistrome-multivec",
 59    ...                 "type": "multivec",
 60    ...                 "row": "sample",
 61    ...                 "column": "position",
 62    ...                 "value": "peak",
 63    ...                 "categories": ["sample 1"],
 64    ...             },
 65    ...             "mark": "bar",
 66    ...             "x": {"field": "start", "type": "genomic"},
 67    ...             "xe": {"field": "end", "type": "genomic"},
 68    ...             "y": {"field": "peak", "type": "quantitative"},
 69    ...             "width": 700,
 70    ...             "height": 200,
 71    ...         }
 72    ...     ]
 73    ... }
 74    >>> Gosling(spec)  # doctest: +SKIP
 75    """
 76
 77    _esm = STATIC / "gosling.js"
 78    # ``theme`` is a Gosling theme, not a plotomics one.
 79    _plotomics_theme = False
 80
 81    def __init__(
 82        self,
 83        spec: Mapping[str, Any],
 84        *,
 85        padding: float | None = None,
 86        theme: Any | None = None,
 87        height: int = 480,
 88        **kwargs: Any,
 89    ) -> None:
 90        if not isinstance(spec, Mapping):
 91            raise ValueError("`spec` must be a mapping (a Gosling specification).")
 92        if not any(k in spec for k in _SPEC_KEYS):
 93            raise ValueError(
 94                "`spec` must contain at least one of: " + ", ".join(_SPEC_KEYS) + "."
 95            )
 96
 97        options: dict[str, Any] = {"spec": dict(spec)}
 98        if padding is not None:
 99            options["padding"] = padding
100        if theme is not None:
101            options["theme"] = theme
102
103        # Gosling is spec-driven; the shared runtime still expects a `data`
104        # payload, so empty columns/meta are supplied.
105        super().__init__(
106            data={"columns": {}, "meta": {}},
107            options=options,
108            _height=height,
109            **kwargs,
110        )

Declarative genomics figures powered by Gosling.js.

Gosling (grammar of scalable, linked, interactive nucleotide graphics) is fully config-driven: you pass a Gosling specification as a dict and data flows through the "data" blocks of the spec (tileset URLs, indexed BAM/BED/VCF/BigWig, or CSV/JSON URLs and inline values). Gosling streams and tiles large genomic datasets on the GPU via HiGlass, so there is no separate data argument.

Parameters
  • spec:: A Gosling specification as a (nested) dict. It is passed through verbatim to Gosling.js, so keys use Gosling's own camelCase names (e.g. tracks, xDomain, alignment). Must contain at least one of tracks, views, arrangement, alignment or template.
  • padding:: Optional outer padding (pixels) forwarded to Gosling's embed options. The widget keeps the default padding of 10 px around Gosling, so the views sit this padding plus 10 px in, and 10 px in with a padding of
    1. None gives Gosling 50, so the views sit 60 px in, as with Gosling's own default.
  • theme:: Optional Gosling theme: a built-in name such as "light", "dark" or "ggplot", or a Gosling theme dict. This is Gosling's own theme, not the plotomics theme that every other widget takes. Gosling draws its own tracks, so no plotomics theme field applies: background, foreground, muted, grid, axis, fontFamily, fontSize, categorical and padding are not read. Set colours and fonts in the Gosling theme or in the spec; the widget keeps the default padding of 10 px around Gosling.
  • height:: Initial widget height in CSS pixels.
Examples
>>> spec = {
...     "responsiveSize": {"width": True},
...     "tracks": [
...         {
...             "data": {
...                 "url": "https://server.gosling-lang.org/api/v1/"
...                 "tileset_info/?d=cistrome-multivec",
...                 "type": "multivec",
...                 "row": "sample",
...                 "column": "position",
...                 "value": "peak",
...                 "categories": ["sample 1"],
...             },
...             "mark": "bar",
...             "x": {"field": "start", "type": "genomic"},
...             "xe": {"field": "end", "type": "genomic"},
...             "y": {"field": "peak", "type": "quantitative"},
...             "width": 700,
...             "height": 200,
...         }
...     ]
... }
>>> Gosling(spec)  # doctest: +SKIP
Gosling( spec: Mapping[str, Any], *, padding: float | None = None, theme: typing.Any | None = None, height: int = 480, **kwargs: Any)
 81    def __init__(
 82        self,
 83        spec: Mapping[str, Any],
 84        *,
 85        padding: float | None = None,
 86        theme: Any | None = None,
 87        height: int = 480,
 88        **kwargs: Any,
 89    ) -> None:
 90        if not isinstance(spec, Mapping):
 91            raise ValueError("`spec` must be a mapping (a Gosling specification).")
 92        if not any(k in spec for k in _SPEC_KEYS):
 93            raise ValueError(
 94                "`spec` must contain at least one of: " + ", ".join(_SPEC_KEYS) + "."
 95            )
 96
 97        options: dict[str, Any] = {"spec": dict(spec)}
 98        if padding is not None:
 99            options["padding"] = padding
100        if theme is not None:
101            options["theme"] = theme
102
103        # Gosling is spec-driven; the shared runtime still expects a `data`
104        # payload, so empty columns/meta are supplied.
105        super().__init__(
106            data={"columns": {}, "meta": {}},
107            options=options,
108            _height=height,
109            **kwargs,
110        )

Public constructor

class Network(plotomics.PlotomicsWidget):
 21class Network(PlotomicsWidget):
 22    """GPU-accelerated node-link diagram for large interaction networks.
 23
 24    Nodes and edges render with WebGL (sigma v3 over a graphology graph) so tens
 25    of thousands of elements stay interactive. If node coordinates are absent, a
 26    bounded ForceAtlas2 layout positions them in the browser; otherwise the
 27    supplied ``x``/``y`` are used. Categorical node groups take the theme's
 28    palette: Okabe-Ito (colour-blind safe) for up to 8 groups, and a 20-colour
 29    palette past 8. Hovering a node highlights it and its neighbors. When the
 30    nodes have groups, a legend of the groups sits in a gutter on the right.
 31
 32    Parameters
 33    ----------
 34    nodes:
 35        A pandas ``DataFrame`` or mapping of arrays describing nodes. Must
 36        provide an ``id`` column. Optional columns: ``x``, ``y`` (precomputed
 37        coordinates), ``size`` (node radius in px), ``group`` (categorical,
 38        mapped to a palette color) and ``label`` (display name; defaults to id).
 39        A pandas ``Categorical`` group fixes the order of the legend and the
 40        colours to its categories, and keeps unused ones in the legend; other
 41        groups go in the order the nodes have them. R does the same with a
 42        factor.
 43    edges:
 44        A ``DataFrame`` or mapping with ``source`` and ``target`` columns of node
 45        ids, an optional numeric ``weight`` column and an optional ``color``
 46        column giving a per-edge color (else ``default_edge_color``). Edge
 47        width follows the absolute weight, scaled over the weights in the
 48        graph to 1.7-6 px, and the layout pulls nodes together by the absolute
 49        weight, so a negative weight (as in a correlation network) counts by
 50        its size.
 51    layout:
 52        ``"forceatlas2"`` (run a layout when coordinates are missing) or
 53        ``"precomputed"`` (require and use ``x``/``y`` from ``nodes``).
 54    iterations:
 55        Number of ForceAtlas2 iterations (bounded internally).
 56    default_node_color:
 57        Fallback node color for nodes without a group.
 58    default_edge_color:
 59        Colour of an edge with no colour of its own. ``None`` (the default)
 60        takes the theme background with a fifth of the theme foreground mixed
 61        in, so edges stay quieter than the nodes and the labels on a light and
 62        on a dark background.
 63    label_threshold:
 64        Minimum node size (px) on screen for its label to render. At the
 65        default of 4, nodes of the default size are labelled at the starting
 66        zoom, and the renderer's label grid keeps the labels from crowding.
 67        Where the letters of two labels would run into each other, the label
 68        of the smaller node is left out.
 69    default_node_size:
 70        Node radius (px) used when ``size`` is absent.
 71    directed:
 72        Draw the graph as directed, with arrowheads. When ``True``, ``A -> B``
 73        and ``B -> A`` are kept as distinct edges; when ``False`` (the default)
 74        the graph is undirected and a reciprocal pair collapses to one line.
 75    palette:
 76        Optional list of hex colors overriding the default categorical palette.
 77    show_legend:
 78        Draw a legend of the node groups, in a gutter on the right, when
 79        ``nodes`` has a ``group`` column.
 80    bounded_view:
 81        Keep pan and zoom inside the graph: zooming out stops at the view
 82        that shows all of it, a pan stops at its edges, and zooming in stops
 83        at 1/10,000 of its range. ``False`` lets the view move freely.
 84        Either way a double-click, or the reset button in the top right
 85        corner of the plot, goes back to the view of the whole graph.
 86    theme:
 87        Optional theme overrides forwarded to the JS renderer. Its
 88        ``padding`` entry is the space in px between the edge of the widget
 89        and the plot: one number for every side, or a dict with any of the
 90        keys ``top``, ``right``, ``bottom`` and ``left``, a side left out
 91        keeping the default of 10.
 92        Its ``categorical`` entry is an ordered palette, a list of colours
 93        that go to the node groups in order; colours are not matched by name.
 94        A colour given as a CSS custom property, such as
 95        ``"background": "var(--bg)"``, takes the value the page gives it when
 96        the plot draws. After the page changes the property, what the plot
 97        drew on a canvas keeps the old colour until it draws again: resize
 98        the widget or display it again.
 99    height:
100        Initial widget height in CSS pixels.
101
102    Notes
103    -----
104    Clicking a node sets ``widget.selected`` to the clicked node id (a
105    string); clicking the empty canvas sets it to ``None``. Observe it with
106    ``widget.observe(fn, names="selected")``.
107
108    Examples
109    --------
110    >>> import numpy as np, pandas as pd
111    >>> nodes = pd.DataFrame({"id": [f"N{i}" for i in range(500)],
112    ...                       "group": np.random.choice(list("ABCD"), 500)})
113    >>> src = np.random.randint(0, 500, 1500)
114    >>> tgt = np.random.randint(0, 500, 1500)
115    >>> edges = pd.DataFrame({"source": [f"N{i}" for i in src],
116    ...                       "target": [f"N{i}" for i in tgt]})
117    >>> Network(nodes, edges)  # doctest: +SKIP
118    """
119
120    _esm = STATIC / "network.js"
121
122    def __init__(
123        self,
124        nodes: Any,
125        edges: Any,
126        *,
127        layout: str = "forceatlas2",
128        iterations: int = 200,
129        default_node_color: str = "#7c8598",
130        default_edge_color: str | None = None,
131        label_threshold: float = 4.0,
132        default_node_size: float = 4.0,
133        directed: bool = False,
134        palette: list[str] | None = None,
135        show_legend: bool = True,
136        bounded_view: bool = True,
137        theme: dict | None = None,
138        height: int = 480,
139        **kwargs: Any,
140    ) -> None:
141        bounded_view = _require_flag(bounded_view, "bounded_view")
142        node_id = _column(nodes, "id")
143        if node_id is None:
144            raise ValueError("`nodes` must provide an `id` column.")
145        source = _column(edges, "source")
146        target = _column(edges, "target")
147        if source is None or target is None:
148            raise ValueError("`edges` must provide `source` and `target` columns.")
149        if layout not in ("forceatlas2", "precomputed"):
150            raise ValueError("`layout` must be 'forceatlas2' or 'precomputed'.")
151
152        # String columns go through the JSON side-channel.
153        id_list = [str(v) for v in node_id]
154        source_list = [str(v) for v in source]
155        target_list = [str(v) for v in target]
156        n_nodes = len(id_list)
157        n_edges = len(source_list)
158
159        # Structural integrity.
160        if n_nodes == 0:
161            raise ValueError("`nodes` must contain at least one row.")
162        if len(target_list) != n_edges:
163            raise ValueError(
164                "`source` and `target` must have the same length; "
165                f"got source={n_edges}, target={len(target_list)}"
166            )
167        dupes = sorted({i for i, c in Counter(id_list).items() if c > 1})
168        if dupes:
169            raise ValueError("duplicate node id(s): " + ", ".join(dupes))
170        id_set = set(id_list)
171        dangling = sorted({e for e in (*source_list, *target_list) if e not in id_set})
172        if dangling:
173            raise ValueError(
174                "edge source/target not found among node ids: " + ", ".join(dangling)
175            )
176
177        json_columns: dict[str, list] = {
178            "id": id_list,
179            "source": source_list,
180            "target": target_list,
181        }
182        edge_color = _column(edges, "color")
183        if edge_color is not None:
184            # A missing colour crosses as null, as R sends NA, and the edge
185            # takes the default colour; str() would send "None" or "nan".
186            color_list = _text_or_none(edge_color)
187            if len(color_list) != n_edges:
188                raise ValueError(
189                    "`color` must match the number of edges; "
190                    f"got color={len(color_list)}, edges={n_edges}"
191                )
192            json_columns["color"] = color_list
193
194        # Numeric columns go through the packed binary buffer. Node columns
195        # (x/y/size) and the per-edge weight legitimately differ in length, so
196        # equal-length checking is done per group here, not across the buffer.
197        numeric: dict[str, Any] = {}
198        x = _column(nodes, "x")
199        y = _column(nodes, "y")
200        if layout == "precomputed" and (x is None or y is None):
201            raise ValueError(
202                "layout='precomputed' requires `x` and `y` columns in `nodes`."
203            )
204        if x is not None and y is not None:
205            numeric["x"] = _validate_len(_to_float32(x, "x"), n_nodes, "x")
206            numeric["y"] = _validate_len(_to_float32(y, "y"), n_nodes, "y")
207        size = _column(nodes, "size")
208        if size is not None:
209            numeric["size"] = _validate_len(_to_float32(size, "size"), n_nodes, "size")
210        weight = _column(edges, "weight")
211        if weight is not None:
212            numeric["weight"] = _validate_len(
213                _to_float32(weight, "weight"), n_edges, "weight"
214            )
215
216        if numeric:
217            buffer, schema = pack_columns(numeric, equal_length=False)
218        else:
219            buffer, schema = b"", {"columns": []}
220
221        meta: dict[str, Any] = {}
222        label = _column(nodes, "label")
223        # A missing label or group stays missing (JSON null), not "nan".
224        if label is not None:
225            meta["nodeLabels"] = _text_or_none(label)
226        group = _column(nodes, "group")
227        if group is not None:
228            meta["nodeGroup"] = _text_or_none(group)
229            # A pandas Categorical states the order of its categories: the
230            # legend and the colours follow it, as they follow R's levels.
231            levels = _category_levels(group)
232            if levels is not None:
233                meta["nodeGroupLevels"] = levels
234
235        options: dict[str, Any] = {
236            "layout": layout,
237            "iterations": iterations,
238            "defaultNodeColor": default_node_color,
239            "labelThreshold": label_threshold,
240            "defaultNodeSize": default_node_size,
241            "directed": directed,
242            "showLegend": show_legend,
243            "boundedView": bounded_view,
244        }
245        if default_edge_color is not None:
246            options["defaultEdgeColor"] = str(default_edge_color)
247        if palette is not None:
248            options["palette"] = list(palette)
249        if theme is not None:
250            options["theme"] = theme
251
252        super().__init__(
253            buffer=buffer,
254            schema=schema,
255            data={"columns": json_columns, "meta": meta},
256            options=options,
257            _height=height,
258            **kwargs,
259        )

GPU-accelerated node-link diagram for large interaction networks.

Nodes and edges render with WebGL (sigma v3 over a graphology graph) so tens of thousands of elements stay interactive. If node coordinates are absent, a bounded ForceAtlas2 layout positions them in the browser; otherwise the supplied x/y are used. Categorical node groups take the theme's palette: Okabe-Ito (colour-blind safe) for up to 8 groups, and a 20-colour palette past 8. Hovering a node highlights it and its neighbors. When the nodes have groups, a legend of the groups sits in a gutter on the right.

Parameters
  • nodes:: A pandas DataFrame or mapping of arrays describing nodes. Must provide an id column. Optional columns: x, y (precomputed coordinates), size (node radius in px), group (categorical, mapped to a palette color) and label (display name; defaults to id). A pandas Categorical group fixes the order of the legend and the colours to its categories, and keeps unused ones in the legend; other groups go in the order the nodes have them. R does the same with a factor.
  • edges:: A DataFrame or mapping with source and target columns of node ids, an optional numeric weight column and an optional color column giving a per-edge color (else default_edge_color). Edge width follows the absolute weight, scaled over the weights in the graph to 1.7-6 px, and the layout pulls nodes together by the absolute weight, so a negative weight (as in a correlation network) counts by its size.
  • layout:: "forceatlas2" (run a layout when coordinates are missing) or "precomputed" (require and use x/y from nodes).
  • iterations:: Number of ForceAtlas2 iterations (bounded internally).
  • default_node_color:: Fallback node color for nodes without a group.
  • default_edge_color:: Colour of an edge with no colour of its own. None (the default) takes the theme background with a fifth of the theme foreground mixed in, so edges stay quieter than the nodes and the labels on a light and on a dark background.
  • label_threshold:: Minimum node size (px) on screen for its label to render. At the default of 4, nodes of the default size are labelled at the starting zoom, and the renderer's label grid keeps the labels from crowding. Where the letters of two labels would run into each other, the label of the smaller node is left out.
  • default_node_size:: Node radius (px) used when size is absent.
  • directed:: Draw the graph as directed, with arrowheads. When True, A -> B and B -> A are kept as distinct edges; when False (the default) the graph is undirected and a reciprocal pair collapses to one line.
  • palette:: Optional list of hex colors overriding the default categorical palette.
  • show_legend:: Draw a legend of the node groups, in a gutter on the right, when nodes has a group column.
  • bounded_view:: Keep pan and zoom inside the graph: zooming out stops at the view that shows all of it, a pan stops at its edges, and zooming in stops at 1/10,000 of its range. False lets the view move freely. Either way a double-click, or the reset button in the top right corner of the plot, goes back to the view of the whole graph.
  • theme:: Optional theme overrides forwarded to the JS renderer. Its padding entry is the space in px between the edge of the widget and the plot: one number for every side, or a dict with any of the keys top, right, bottom and left, a side left out keeping the default of 10. Its categorical entry is an ordered palette, a list of colours that go to the node groups in order; colours are not matched by name. A colour given as a CSS custom property, such as "background": "var(--bg)", takes the value the page gives it when the plot draws. After the page changes the property, what the plot drew on a canvas keeps the old colour until it draws again: resize the widget or display it again.
  • height:: Initial widget height in CSS pixels.
Notes

Clicking a node sets widget.selected to the clicked node id (a string); clicking the empty canvas sets it to None. Observe it with widget.observe(fn, names="selected").

Examples
>>> import numpy as np, pandas as pd
>>> nodes = pd.DataFrame({"id": [f"N{i}" for i in range(500)],
...                       "group": np.random.choice(list("ABCD"), 500)})
>>> src = np.random.randint(0, 500, 1500)
>>> tgt = np.random.randint(0, 500, 1500)
>>> edges = pd.DataFrame({"source": [f"N{i}" for i in src],
...                       "target": [f"N{i}" for i in tgt]})
>>> Network(nodes, edges)  # doctest: +SKIP
Network( nodes: Any, edges: Any, *, layout: str = 'forceatlas2', iterations: int = 200, default_node_color: str = '#7c8598', default_edge_color: str | None = None, label_threshold: float = 4.0, default_node_size: float = 4.0, directed: bool = False, palette: list[str] | None = None, show_legend: bool = True, bounded_view: bool = True, theme: dict | None = None, height: int = 480, **kwargs: Any)
122    def __init__(
123        self,
124        nodes: Any,
125        edges: Any,
126        *,
127        layout: str = "forceatlas2",
128        iterations: int = 200,
129        default_node_color: str = "#7c8598",
130        default_edge_color: str | None = None,
131        label_threshold: float = 4.0,
132        default_node_size: float = 4.0,
133        directed: bool = False,
134        palette: list[str] | None = None,
135        show_legend: bool = True,
136        bounded_view: bool = True,
137        theme: dict | None = None,
138        height: int = 480,
139        **kwargs: Any,
140    ) -> None:
141        bounded_view = _require_flag(bounded_view, "bounded_view")
142        node_id = _column(nodes, "id")
143        if node_id is None:
144            raise ValueError("`nodes` must provide an `id` column.")
145        source = _column(edges, "source")
146        target = _column(edges, "target")
147        if source is None or target is None:
148            raise ValueError("`edges` must provide `source` and `target` columns.")
149        if layout not in ("forceatlas2", "precomputed"):
150            raise ValueError("`layout` must be 'forceatlas2' or 'precomputed'.")
151
152        # String columns go through the JSON side-channel.
153        id_list = [str(v) for v in node_id]
154        source_list = [str(v) for v in source]
155        target_list = [str(v) for v in target]
156        n_nodes = len(id_list)
157        n_edges = len(source_list)
158
159        # Structural integrity.
160        if n_nodes == 0:
161            raise ValueError("`nodes` must contain at least one row.")
162        if len(target_list) != n_edges:
163            raise ValueError(
164                "`source` and `target` must have the same length; "
165                f"got source={n_edges}, target={len(target_list)}"
166            )
167        dupes = sorted({i for i, c in Counter(id_list).items() if c > 1})
168        if dupes:
169            raise ValueError("duplicate node id(s): " + ", ".join(dupes))
170        id_set = set(id_list)
171        dangling = sorted({e for e in (*source_list, *target_list) if e not in id_set})
172        if dangling:
173            raise ValueError(
174                "edge source/target not found among node ids: " + ", ".join(dangling)
175            )
176
177        json_columns: dict[str, list] = {
178            "id": id_list,
179            "source": source_list,
180            "target": target_list,
181        }
182        edge_color = _column(edges, "color")
183        if edge_color is not None:
184            # A missing colour crosses as null, as R sends NA, and the edge
185            # takes the default colour; str() would send "None" or "nan".
186            color_list = _text_or_none(edge_color)
187            if len(color_list) != n_edges:
188                raise ValueError(
189                    "`color` must match the number of edges; "
190                    f"got color={len(color_list)}, edges={n_edges}"
191                )
192            json_columns["color"] = color_list
193
194        # Numeric columns go through the packed binary buffer. Node columns
195        # (x/y/size) and the per-edge weight legitimately differ in length, so
196        # equal-length checking is done per group here, not across the buffer.
197        numeric: dict[str, Any] = {}
198        x = _column(nodes, "x")
199        y = _column(nodes, "y")
200        if layout == "precomputed" and (x is None or y is None):
201            raise ValueError(
202                "layout='precomputed' requires `x` and `y` columns in `nodes`."
203            )
204        if x is not None and y is not None:
205            numeric["x"] = _validate_len(_to_float32(x, "x"), n_nodes, "x")
206            numeric["y"] = _validate_len(_to_float32(y, "y"), n_nodes, "y")
207        size = _column(nodes, "size")
208        if size is not None:
209            numeric["size"] = _validate_len(_to_float32(size, "size"), n_nodes, "size")
210        weight = _column(edges, "weight")
211        if weight is not None:
212            numeric["weight"] = _validate_len(
213                _to_float32(weight, "weight"), n_edges, "weight"
214            )
215
216        if numeric:
217            buffer, schema = pack_columns(numeric, equal_length=False)
218        else:
219            buffer, schema = b"", {"columns": []}
220
221        meta: dict[str, Any] = {}
222        label = _column(nodes, "label")
223        # A missing label or group stays missing (JSON null), not "nan".
224        if label is not None:
225            meta["nodeLabels"] = _text_or_none(label)
226        group = _column(nodes, "group")
227        if group is not None:
228            meta["nodeGroup"] = _text_or_none(group)
229            # A pandas Categorical states the order of its categories: the
230            # legend and the colours follow it, as they follow R's levels.
231            levels = _category_levels(group)
232            if levels is not None:
233                meta["nodeGroupLevels"] = levels
234
235        options: dict[str, Any] = {
236            "layout": layout,
237            "iterations": iterations,
238            "defaultNodeColor": default_node_color,
239            "labelThreshold": label_threshold,
240            "defaultNodeSize": default_node_size,
241            "directed": directed,
242            "showLegend": show_legend,
243            "boundedView": bounded_view,
244        }
245        if default_edge_color is not None:
246            options["defaultEdgeColor"] = str(default_edge_color)
247        if palette is not None:
248            options["palette"] = list(palette)
249        if theme is not None:
250            options["theme"] = theme
251
252        super().__init__(
253            buffer=buffer,
254            schema=schema,
255            data={"columns": json_columns, "meta": meta},
256            options=options,
257            _height=height,
258            **kwargs,
259        )

Public constructor

class Clustermap(plotomics.PlotomicsWidget):
 25class Clustermap(PlotomicsWidget):
 26    """Hierarchically-clustered expression heatmap with dendrograms.
 27
 28    In the spirit of ``seaborn.clustermap`` / Morpheus: the matrix is drawn on
 29    a GPU/canvas data layer so large matrices stay smooth, while dendrograms,
 30    tick labels and the colorbar are crisp vector overlays. Rows and columns
 31    are agglomeratively clustered and reordered so structure appears as blocks
 32    along the diagonal. A matrix with more rows or columns than the plot has
 33    pixels is pooled for drawing: each pixel shows the mean of the cells under
 34    it, so a lone outlier row still shows, fainter the more rows share its
 35    pixel.
 36
 37    Clustering is at least ``O(n^2)`` in the number of rows/columns (it builds a
 38    full distance matrix), so clustering runs automatically only when a
 39    dimension has at most 2000 leaves. For larger matrices, precompute a leaf
 40    order (or dendrogram) elsewhere and pass it via ``row_linkage`` /
 41    ``col_linkage`` to skip clustering; the heatmap rendering itself scales to
 42    much larger matrices.
 43
 44    Parameters
 45    ----------
 46    matrix:
 47        A 2D NumPy array or a pandas ``DataFrame``. For a ``DataFrame``, the
 48        index becomes row labels and the columns become column labels. Values
 49        are packed as ``float32`` and transported row-major. A missing cell
 50        (NaN) is drawn grey, and distances between rows or columns use the
 51        cells both have, scaled up as R's ``dist()`` does. Where several rows
 52        or columns share a pixel, the pixel shows the mean of their finite
 53        cells, so it is grey only when all of them are missing.
 54    metric:
 55        Distance metric for clustering: ``"euclidean"`` or ``"correlation"``
 56        (1 - Pearson correlation).
 57    linkage:
 58        Agglomeration method: ``"average"``, ``"complete"`` or ``"ward"``.
 59        ``"ward"`` is Ward's method as scipy and R's ``ward.D2`` compute it,
 60        and it assumes the euclidean metric (a warning says so for
 61        correlation).
 62    colormap:
 63        Color ramp: sequential ``"viridis"`` or ``"ltc"`` (an earthy teal to
 64        sand to rust ramp), or diverging ``"rdbu"`` or ``"ltcdiv"`` (its
 65        counterpart, neutral cream at the midpoint), whose range is symmetric
 66        about zero. ``None`` (the default) uses ``"rdbu"`` when ``z_score`` is
 67        on, so values above and below the row mean get opposite colours, and
 68        ``"viridis"`` otherwise.
 69    z_score:
 70        Standardize each row to mean 0 / sd 1 before coloring.
 71    cluster_rows, cluster_cols:
 72        Cluster and reorder rows / columns. Ignored for an axis when a
 73        precomputed ``row_linkage`` / ``col_linkage`` is supplied.
 74    show_row_dendrogram, show_col_dendrogram:
 75        Draw the row / column dendrogram.
 76    show_labels:
 77        Draw row/column tick labels (auto-hidden when cells get too small).
 78    legend_title:
 79        Colorbar legend title.
 80    row_labels, col_labels:
 81        Explicit labels; override any inferred from a DataFrame.
 82    row_linkage, col_linkage:
 83        Optional precomputed leaf order or dendrogram to skip clustering that
 84        axis. Either a list of 0-based leaf indices, or a dict with ``order``
 85        (0-based) and ``merges`` (each ``{"left", "right", "height"}``; leaves
 86        are ``0..n-1`` and internal node ``k`` is ``n + k``).
 87    theme:
 88        Optional theme overrides forwarded to the JS renderer. Its
 89        ``padding`` entry is the space in px between the edge of the widget
 90        and the plot: one number for every side, or a dict with any of the
 91        keys ``top``, ``right``, ``bottom`` and ``left``, a side left out
 92        keeping the default of 10.
 93        A colour given as a CSS custom property, such as
 94        ``"background": "var(--bg)"``, takes the value the page gives it when
 95        the plot draws. After the page changes the property, what the plot
 96        drew on a canvas keeps the old colour until it draws again: resize
 97        the widget or display it again.
 98    height:
 99        Initial widget height in CSS pixels.
100
101    Examples
102    --------
103    >>> import numpy as np
104    >>> # Two blocks of correlated rows.
105    >>> mat = np.vstack([
106    ...     np.random.randn(20, 10) + 2,
107    ...     np.random.randn(20, 10) - 2,
108    ... ])
109    >>> Clustermap(mat, colormap="rdbu", z_score=True)  # doctest: +SKIP
110    """
111
112    _esm = STATIC / "clustermap.js"
113
114    def __init__(
115        self,
116        matrix: Any,
117        *,
118        metric: str = "euclidean",
119        linkage: str = "average",
120        colormap: Literal["viridis", "rdbu", "ltc", "ltcdiv"] | None = None,
121        z_score: bool = False,
122        cluster_rows: bool = True,
123        cluster_cols: bool = True,
124        show_row_dendrogram: bool = True,
125        show_col_dendrogram: bool = True,
126        show_labels: bool = True,
127        legend_title: str = "value",
128        row_labels: Any | None = None,
129        col_labels: Any | None = None,
130        row_linkage: Any | None = None,
131        col_linkage: Any | None = None,
132        theme: dict | None = None,
133        height: int = 560,
134        **kwargs: Any,
135    ) -> None:
136        if metric not in _METRICS:
137            raise ValueError(
138                "`metric` must be 'euclidean' or 'correlation'."
139            )
140        if linkage not in _LINKAGES:
141            raise ValueError(
142                "`linkage` must be 'average', 'complete' or 'ward'."
143            )
144        if linkage == "ward" and metric != "euclidean":
145            warnings.warn(
146                "Ward linkage assumes euclidean distances; with "
147                f"metric={metric!r} its merge heights have no clear meaning.",
148                stacklevel=2,
149            )
150        if colormap is not None:
151            _check_choice(colormap, "colormap", _COLORMAPS)
152
153        arr, inferred_rows, inferred_cols = _as_matrix(matrix)
154        if arr.ndim != 2:
155            raise ValueError("`matrix` must be 2-dimensional.")
156        nrows, ncols = arr.shape
157        if nrows == 0 or ncols == 0:
158            raise ValueError("`matrix` must contain at least one row and one column.")
159
160        if row_linkage is not None:
161            _validate_linkage(row_linkage, int(nrows), "row_linkage")
162        if col_linkage is not None:
163            _validate_linkage(col_linkage, int(ncols), "col_linkage")
164
165        # Row-major float32 buffer (C-contiguous flatten matches the JS layout).
166        try:
167            values = np.ascontiguousarray(arr, dtype=np.float32).reshape(-1)
168        except (ValueError, TypeError):
169            raise ValueError(
170                f"`matrix` must be numeric; got dtype {arr.dtype.name}"
171            ) from None
172        buffer, schema = pack_columns(
173            {"values": values}, names={"values": "matrix"}
174        )
175
176        meta: dict[str, Any] = {"nrows": int(nrows), "ncols": int(ncols)}
177        # A label list of the wrong length would make the browser drop every
178        # label without a word, so it fails here, as in Heatmap.
179        rlabels = _check_labels(
180            row_labels if row_labels is not None else inferred_rows,
181            int(nrows),
182            "row_labels",
183        )
184        clabels = _check_labels(
185            col_labels if col_labels is not None else inferred_cols,
186            int(ncols),
187            "col_labels",
188        )
189        if rlabels is not None:
190            meta["rowLabels"] = rlabels
191        if clabels is not None:
192            meta["colLabels"] = clabels
193        if row_linkage is not None:
194            meta["rowLinkage"] = row_linkage
195        if col_linkage is not None:
196            meta["colLinkage"] = col_linkage
197
198        # A None colormap lets the browser pick: "rdbu" for z-scores and
199        # "viridis" otherwise.
200        options: dict[str, Any] = {
201            "metric": metric,
202            "linkage": linkage,
203            "colormap": colormap,
204            "zScore": z_score,
205            "clusterRows": cluster_rows,
206            "clusterCols": cluster_cols,
207            "showRowDendrogram": show_row_dendrogram,
208            "showColDendrogram": show_col_dendrogram,
209            "showLabels": show_labels,
210            "legendTitle": legend_title,
211        }
212        if theme is not None:
213            options["theme"] = theme
214
215        super().__init__(
216            buffer=buffer,
217            schema=schema,
218            data={"columns": {}, "meta": meta},
219            options=options,
220            _height=height,
221            **kwargs,
222        )

Hierarchically-clustered expression heatmap with dendrograms.

In the spirit of seaborn.clustermap / Morpheus: the matrix is drawn on a GPU/canvas data layer so large matrices stay smooth, while dendrograms, tick labels and the colorbar are crisp vector overlays. Rows and columns are agglomeratively clustered and reordered so structure appears as blocks along the diagonal. A matrix with more rows or columns than the plot has pixels is pooled for drawing: each pixel shows the mean of the cells under it, so a lone outlier row still shows, fainter the more rows share its pixel.

Clustering is at least O(n^2) in the number of rows/columns (it builds a full distance matrix), so clustering runs automatically only when a dimension has at most 2000 leaves. For larger matrices, precompute a leaf order (or dendrogram) elsewhere and pass it via row_linkage / col_linkage to skip clustering; the heatmap rendering itself scales to much larger matrices.

Parameters
  • matrix:: A 2D NumPy array or a pandas DataFrame. For a DataFrame, the index becomes row labels and the columns become column labels. Values are packed as float32 and transported row-major. A missing cell (NaN) is drawn grey, and distances between rows or columns use the cells both have, scaled up as R's dist() does. Where several rows or columns share a pixel, the pixel shows the mean of their finite cells, so it is grey only when all of them are missing.
  • metric:: Distance metric for clustering: "euclidean" or "correlation" (1 - Pearson correlation).
  • linkage:: Agglomeration method: "average", "complete" or "ward". "ward" is Ward's method as scipy and R's ward.D2 compute it, and it assumes the euclidean metric (a warning says so for correlation).
  • colormap:: Color ramp: sequential "viridis" or "ltc" (an earthy teal to sand to rust ramp), or diverging "rdbu" or "ltcdiv" (its counterpart, neutral cream at the midpoint), whose range is symmetric about zero. None (the default) uses "rdbu" when z_score is on, so values above and below the row mean get opposite colours, and "viridis" otherwise.
  • z_score:: Standardize each row to mean 0 / sd 1 before coloring.
  • cluster_rows, cluster_cols:: Cluster and reorder rows / columns. Ignored for an axis when a precomputed row_linkage / col_linkage is supplied.
  • show_row_dendrogram, show_col_dendrogram:: Draw the row / column dendrogram.
  • show_labels:: Draw row/column tick labels (auto-hidden when cells get too small).
  • legend_title:: Colorbar legend title.
  • row_labels, col_labels:: Explicit labels; override any inferred from a DataFrame.
  • row_linkage, col_linkage:: Optional precomputed leaf order or dendrogram to skip clustering that axis. Either a list of 0-based leaf indices, or a dict with order (0-based) and merges (each {"left", "right", "height"}; leaves are 0..n-1 and internal node k is n + k).
  • theme:: Optional theme overrides forwarded to the JS renderer. Its padding entry is the space in px between the edge of the widget and the plot: one number for every side, or a dict with any of the keys top, right, bottom and left, a side left out keeping the default of 10. A colour given as a CSS custom property, such as "background": "var(--bg)", takes the value the page gives it when the plot draws. After the page changes the property, what the plot drew on a canvas keeps the old colour until it draws again: resize the widget or display it again.
  • height:: Initial widget height in CSS pixels.
Examples
>>> import numpy as np
>>> # Two blocks of correlated rows.
>>> mat = np.vstack([
...     np.random.randn(20, 10) + 2,
...     np.random.randn(20, 10) - 2,
... ])
>>> Clustermap(mat, colormap="rdbu", z_score=True)  # doctest: +SKIP
Clustermap( matrix: Any, *, metric: str = 'euclidean', linkage: str = 'average', colormap: Optional[Literal['viridis', 'rdbu', 'ltc', 'ltcdiv']] = None, z_score: bool = False, cluster_rows: bool = True, cluster_cols: bool = True, show_row_dendrogram: bool = True, show_col_dendrogram: bool = True, show_labels: bool = True, legend_title: str = 'value', row_labels: typing.Any | None = None, col_labels: typing.Any | None = None, row_linkage: typing.Any | None = None, col_linkage: typing.Any | None = None, theme: dict | None = None, height: int = 560, **kwargs: Any)
114    def __init__(
115        self,
116        matrix: Any,
117        *,
118        metric: str = "euclidean",
119        linkage: str = "average",
120        colormap: Literal["viridis", "rdbu", "ltc", "ltcdiv"] | None = None,
121        z_score: bool = False,
122        cluster_rows: bool = True,
123        cluster_cols: bool = True,
124        show_row_dendrogram: bool = True,
125        show_col_dendrogram: bool = True,
126        show_labels: bool = True,
127        legend_title: str = "value",
128        row_labels: Any | None = None,
129        col_labels: Any | None = None,
130        row_linkage: Any | None = None,
131        col_linkage: Any | None = None,
132        theme: dict | None = None,
133        height: int = 560,
134        **kwargs: Any,
135    ) -> None:
136        if metric not in _METRICS:
137            raise ValueError(
138                "`metric` must be 'euclidean' or 'correlation'."
139            )
140        if linkage not in _LINKAGES:
141            raise ValueError(
142                "`linkage` must be 'average', 'complete' or 'ward'."
143            )
144        if linkage == "ward" and metric != "euclidean":
145            warnings.warn(
146                "Ward linkage assumes euclidean distances; with "
147                f"metric={metric!r} its merge heights have no clear meaning.",
148                stacklevel=2,
149            )
150        if colormap is not None:
151            _check_choice(colormap, "colormap", _COLORMAPS)
152
153        arr, inferred_rows, inferred_cols = _as_matrix(matrix)
154        if arr.ndim != 2:
155            raise ValueError("`matrix` must be 2-dimensional.")
156        nrows, ncols = arr.shape
157        if nrows == 0 or ncols == 0:
158            raise ValueError("`matrix` must contain at least one row and one column.")
159
160        if row_linkage is not None:
161            _validate_linkage(row_linkage, int(nrows), "row_linkage")
162        if col_linkage is not None:
163            _validate_linkage(col_linkage, int(ncols), "col_linkage")
164
165        # Row-major float32 buffer (C-contiguous flatten matches the JS layout).
166        try:
167            values = np.ascontiguousarray(arr, dtype=np.float32).reshape(-1)
168        except (ValueError, TypeError):
169            raise ValueError(
170                f"`matrix` must be numeric; got dtype {arr.dtype.name}"
171            ) from None
172        buffer, schema = pack_columns(
173            {"values": values}, names={"values": "matrix"}
174        )
175
176        meta: dict[str, Any] = {"nrows": int(nrows), "ncols": int(ncols)}
177        # A label list of the wrong length would make the browser drop every
178        # label without a word, so it fails here, as in Heatmap.
179        rlabels = _check_labels(
180            row_labels if row_labels is not None else inferred_rows,
181            int(nrows),
182            "row_labels",
183        )
184        clabels = _check_labels(
185            col_labels if col_labels is not None else inferred_cols,
186            int(ncols),
187            "col_labels",
188        )
189        if rlabels is not None:
190            meta["rowLabels"] = rlabels
191        if clabels is not None:
192            meta["colLabels"] = clabels
193        if row_linkage is not None:
194            meta["rowLinkage"] = row_linkage
195        if col_linkage is not None:
196            meta["colLinkage"] = col_linkage
197
198        # A None colormap lets the browser pick: "rdbu" for z-scores and
199        # "viridis" otherwise.
200        options: dict[str, Any] = {
201            "metric": metric,
202            "linkage": linkage,
203            "colormap": colormap,
204            "zScore": z_score,
205            "clusterRows": cluster_rows,
206            "clusterCols": cluster_cols,
207            "showRowDendrogram": show_row_dendrogram,
208            "showColDendrogram": show_col_dendrogram,
209            "showLabels": show_labels,
210            "legendTitle": legend_title,
211        }
212        if theme is not None:
213            options["theme"] = theme
214
215        super().__init__(
216            buffer=buffer,
217            schema=schema,
218            data={"columns": {}, "meta": meta},
219            options=options,
220            _height=height,
221            **kwargs,
222        )

Public constructor

class Dotplot(plotomics.PlotomicsWidget):
 24class Dotplot(PlotomicsWidget):
 25    """Features down the rows, groups across the columns, two channels per dot.
 26
 27    Dot size is the fraction of the group expressing the gene and dot colour is
 28    the expression level. Two channels because colour alone cannot separate
 29    "high in a few cells" from "moderate in all of them", and that distinction
 30    is usually what decides whether a gene is a marker.
 31
 32    Dot area, not radius, is proportional to the percentage. Scaling radius
 33    linearly would quadruple the ink for a doubled percentage, which is the
 34    classic way a dot plot overstates its strongest cells.
 35
 36    Rows and columns are drawn in the order given. Sorting genes by the group
 37    they best mark is an analysis decision, so the component does not do it.
 38
 39    Parameters
 40    ----------
 41    data:
 42        A pandas ``DataFrame`` or mapping of arrays in long form, one row per
 43        dot, with ``gene`` and ``cluster`` key columns, a ``pct`` column
 44        (percent expressing, 0-100) driving dot size, and a ``value`` column
 45        (expression level) driving dot colour. A missing ``value``, such as
 46        the NaN of a scaled gene that is constant across groups, is drawn as
 47        an open ring and left out of the colour scale. A missing ``pct`` draws
 48        no dot.
 49    genes, clusters:
 50        Fix the row and column order. A pandas Categorical supplies it from its
 51        categories. Defaults to order of appearance.
 52    value_label, size_label:
 53        Legend titles.
 54    colormap:
 55        Sequential ramp for the colour channel: ``"viridis"``, ``"rdbu"``,
 56        ``"ltc"`` (an earthy teal to sand to rust sequential ramp) or
 57        ``"ltcdiv"`` (its diverging counterpart, neutral cream at the midpoint).
 58    max_radius:
 59        Radius in pixels of a dot at 100 percent.
 60    value_domain:
 61        ``(min, max)`` fixing the colour scale. ``None`` uses the data range.
 62        Set it when comparing two dot plots side by side.
 63    show_grid, show_legend:
 64        Toggle the gridlines and the legends.
 65    theme:
 66        Optional theme overrides forwarded to the JS renderer. Its
 67        ``padding`` entry is the space in px between the edge of the widget
 68        and the plot: one number for every side, or a dict with any of the
 69        keys ``top``, ``right``, ``bottom`` and ``left``, a side left out
 70        keeping the default of 10.
 71        A colour given as a CSS custom property, such as
 72        ``"background": "var(--bg)"``, takes the value the page gives it when
 73        the plot draws. After the page changes the property, what the plot
 74        drew on a canvas keeps the old colour until it draws again: resize
 75        the widget or display it again.
 76    height:
 77        Initial widget height in CSS pixels.
 78
 79    Examples
 80    --------
 81    >>> import pandas as pd
 82    >>> df = pd.DataFrame({
 83    ...     "gene": ["CD3D", "MS4A1", "CD3D", "MS4A1"],
 84    ...     "cluster": ["T", "T", "B", "B"],
 85    ...     "pct": [88, 4, 6, 91],
 86    ...     "value": [2.4, 0.1, 0.2, 2.7],
 87    ... })
 88    >>> Dotplot(df)  # doctest: +SKIP
 89    """
 90
 91    _esm = STATIC / "dotplot.js"
 92
 93    def __init__(
 94        self,
 95        data: Any,
 96        *,
 97        genes: list[str] | None = None,
 98        clusters: list[str] | None = None,
 99        value_label: str = "mean expression",
100        size_label: str = "% expressing",
101        colormap: Literal["viridis", "rdbu", "ltc", "ltcdiv"] = "viridis",
102        max_radius: float = 9.0,
103        value_domain: tuple[float, float] | None = None,
104        show_grid: bool = True,
105        show_legend: bool = True,
106        theme: dict | None = None,
107        height: int = 560,
108        **kwargs: Any,
109    ) -> None:
110        gene = _column(data, "gene")
111        cluster = _column(data, "cluster")
112        pct_col = _column(data, "pct")
113        value_col = _column(data, "value")
114        missing = [
115            name
116            for name, col in (
117                ("gene", gene), ("cluster", cluster),
118                ("pct", pct_col), ("value", value_col),
119            )
120            if col is None
121        ]
122        if missing:
123            raise ValueError("`data` is missing column(s): " + ", ".join(missing))
124
125        _check_choice(colormap, "colormap", ("viridis", "rdbu", "ltc", "ltcdiv"))
126        pct = _to_float32(pct_col, "pct")
127        value = _to_float32(value_col, "value")
128        if pct.size == 0:
129            raise ValueError("`data` must contain at least one row.")
130        if np.any(pct < 0) or np.any(pct > 100):
131            raise ValueError("`pct` must be a percentage in [0, 100].")
132
133        buffer, schema = pack_columns({"pct": pct, "value": value})
134        # A missing gene or cluster crosses as null, as R sends an NA.
135        json_columns: dict[str, list] = {
136            "gene": _text_or_none(gene),
137            "cluster": _text_or_none(cluster),
138        }
139
140        # A pandas Categorical is the caller stating the order they want, which
141        # for a dot plot is the point: the diagonal only appears under one.
142        if genes is None:
143            genes = _category_levels(gene)
144        if clusters is None:
145            clusters = _category_levels(cluster)
146
147        meta: dict[str, Any] = {
148            "valueLabel": value_label,
149            "sizeLabel": size_label,
150        }
151        for key, order, col in (
152            ("genes", genes, json_columns["gene"]),
153            ("clusters", clusters, json_columns["cluster"]),
154        ):
155            if order is None:
156                continue
157            order = _text_or_none(order)
158            unknown = _not_in(col, order)
159            if unknown:
160                raise ValueError(
161                    f"value(s) not present in `{key}`: " + _na_text(unknown[:5])
162                )
163            meta[key] = order
164
165        options: dict[str, Any] = {
166            "colormap": colormap,
167            "maxRadius": max_radius,
168            "showGrid": show_grid,
169            "showLegend": show_legend,
170        }
171        if value_domain is not None:
172            if len(value_domain) != 2:
173                raise ValueError("`value_domain` must be length 2.")
174            if not np.all(np.isfinite(np.asarray(value_domain, dtype=float))):
175                raise ValueError(
176                    "`value_domain` must be two finite numbers; for a column "
177                    "with missing values, use np.nanmin and np.nanmax."
178                )
179            options["valueDomain"] = [float(v) for v in value_domain]
180        if theme is not None:
181            options["theme"] = theme
182
183        super().__init__(
184            buffer=buffer,
185            schema=schema,
186            data={"columns": json_columns, "meta": meta},
187            options=options,
188            _height=height,
189            **kwargs,
190        )

Features down the rows, groups across the columns, two channels per dot.

Dot size is the fraction of the group expressing the gene and dot colour is the expression level. Two channels because colour alone cannot separate "high in a few cells" from "moderate in all of them", and that distinction is usually what decides whether a gene is a marker.

Dot area, not radius, is proportional to the percentage. Scaling radius linearly would quadruple the ink for a doubled percentage, which is the classic way a dot plot overstates its strongest cells.

Rows and columns are drawn in the order given. Sorting genes by the group they best mark is an analysis decision, so the component does not do it.

Parameters
  • data:: A pandas DataFrame or mapping of arrays in long form, one row per dot, with gene and cluster key columns, a pct column (percent expressing, 0-100) driving dot size, and a value column (expression level) driving dot colour. A missing value, such as the NaN of a scaled gene that is constant across groups, is drawn as an open ring and left out of the colour scale. A missing pct draws no dot.
  • genes, clusters:: Fix the row and column order. A pandas Categorical supplies it from its categories. Defaults to order of appearance.
  • value_label, size_label:: Legend titles.
  • colormap:: Sequential ramp for the colour channel: "viridis", "rdbu", "ltc" (an earthy teal to sand to rust sequential ramp) or "ltcdiv" (its diverging counterpart, neutral cream at the midpoint).
  • max_radius:: Radius in pixels of a dot at 100 percent.
  • value_domain:: (min, max) fixing the colour scale. None uses the data range. Set it when comparing two dot plots side by side.
  • show_grid, show_legend:: Toggle the gridlines and the legends.
  • theme:: Optional theme overrides forwarded to the JS renderer. Its padding entry is the space in px between the edge of the widget and the plot: one number for every side, or a dict with any of the keys top, right, bottom and left, a side left out keeping the default of 10. A colour given as a CSS custom property, such as "background": "var(--bg)", takes the value the page gives it when the plot draws. After the page changes the property, what the plot drew on a canvas keeps the old colour until it draws again: resize the widget or display it again.
  • height:: Initial widget height in CSS pixels.
Examples
>>> import pandas as pd
>>> df = pd.DataFrame({
...     "gene": ["CD3D", "MS4A1", "CD3D", "MS4A1"],
...     "cluster": ["T", "T", "B", "B"],
...     "pct": [88, 4, 6, 91],
...     "value": [2.4, 0.1, 0.2, 2.7],
... })
>>> Dotplot(df)  # doctest: +SKIP
Dotplot( data: Any, *, genes: list[str] | None = None, clusters: list[str] | None = None, value_label: str = 'mean expression', size_label: str = '% expressing', colormap: Literal['viridis', 'rdbu', 'ltc', 'ltcdiv'] = 'viridis', max_radius: float = 9.0, value_domain: tuple[float, float] | None = None, show_grid: bool = True, show_legend: bool = True, theme: dict | None = None, height: int = 560, **kwargs: Any)
 93    def __init__(
 94        self,
 95        data: Any,
 96        *,
 97        genes: list[str] | None = None,
 98        clusters: list[str] | None = None,
 99        value_label: str = "mean expression",
100        size_label: str = "% expressing",
101        colormap: Literal["viridis", "rdbu", "ltc", "ltcdiv"] = "viridis",
102        max_radius: float = 9.0,
103        value_domain: tuple[float, float] | None = None,
104        show_grid: bool = True,
105        show_legend: bool = True,
106        theme: dict | None = None,
107        height: int = 560,
108        **kwargs: Any,
109    ) -> None:
110        gene = _column(data, "gene")
111        cluster = _column(data, "cluster")
112        pct_col = _column(data, "pct")
113        value_col = _column(data, "value")
114        missing = [
115            name
116            for name, col in (
117                ("gene", gene), ("cluster", cluster),
118                ("pct", pct_col), ("value", value_col),
119            )
120            if col is None
121        ]
122        if missing:
123            raise ValueError("`data` is missing column(s): " + ", ".join(missing))
124
125        _check_choice(colormap, "colormap", ("viridis", "rdbu", "ltc", "ltcdiv"))
126        pct = _to_float32(pct_col, "pct")
127        value = _to_float32(value_col, "value")
128        if pct.size == 0:
129            raise ValueError("`data` must contain at least one row.")
130        if np.any(pct < 0) or np.any(pct > 100):
131            raise ValueError("`pct` must be a percentage in [0, 100].")
132
133        buffer, schema = pack_columns({"pct": pct, "value": value})
134        # A missing gene or cluster crosses as null, as R sends an NA.
135        json_columns: dict[str, list] = {
136            "gene": _text_or_none(gene),
137            "cluster": _text_or_none(cluster),
138        }
139
140        # A pandas Categorical is the caller stating the order they want, which
141        # for a dot plot is the point: the diagonal only appears under one.
142        if genes is None:
143            genes = _category_levels(gene)
144        if clusters is None:
145            clusters = _category_levels(cluster)
146
147        meta: dict[str, Any] = {
148            "valueLabel": value_label,
149            "sizeLabel": size_label,
150        }
151        for key, order, col in (
152            ("genes", genes, json_columns["gene"]),
153            ("clusters", clusters, json_columns["cluster"]),
154        ):
155            if order is None:
156                continue
157            order = _text_or_none(order)
158            unknown = _not_in(col, order)
159            if unknown:
160                raise ValueError(
161                    f"value(s) not present in `{key}`: " + _na_text(unknown[:5])
162                )
163            meta[key] = order
164
165        options: dict[str, Any] = {
166            "colormap": colormap,
167            "maxRadius": max_radius,
168            "showGrid": show_grid,
169            "showLegend": show_legend,
170        }
171        if value_domain is not None:
172            if len(value_domain) != 2:
173                raise ValueError("`value_domain` must be length 2.")
174            if not np.all(np.isfinite(np.asarray(value_domain, dtype=float))):
175                raise ValueError(
176                    "`value_domain` must be two finite numbers; for a column "
177                    "with missing values, use np.nanmin and np.nanmax."
178                )
179            options["valueDomain"] = [float(v) for v in value_domain]
180        if theme is not None:
181            options["theme"] = theme
182
183        super().__init__(
184            buffer=buffer,
185            schema=schema,
186            data={"columns": json_columns, "meta": meta},
187            options=options,
188            _height=height,
189            **kwargs,
190        )

Public constructor

class HiC(plotomics.PlotomicsWidget):
 18class HiC(PlotomicsWidget):
 19    """GPU-accelerated Hi-C chromatin contact map.
 20
 21    The contact matrix is normalized to an 8-bit texture and drawn as one WebGL
 22    quad, with the colormap applied in the fragment shader, so pan/zoom stays
 23    smooth on very large matrices. A precomputed level-of-detail pyramid keeps
 24    interaction fast when zoomed out. Genomic coordinate ticks and the colorbar
 25    are crisp vector overlays. No tile server is required.
 26
 27    Parameters
 28    ----------
 29    matrix:
 30        Either a 2-D square array of contact counts (dense), as a NumPy array
 31        or a nested list of rows, or a COO-like triplet of ``(i, j, v)`` for
 32        the sparse form. A triplet may be given as a tuple ``(i, j, v)``, a
 33        mapping with keys ``i``/``j``/``v`` (e.g. a DataFrame), or via the
 34        ``i``, ``j``, ``v`` keyword arguments. A list of three sequences is also
 35        read as a triplet, unless it is a 3x3 nested list, which is read as a
 36        dense matrix; pass a tuple or the keywords for a three-contact triplet.
 37    n:
 38        Number of bins per axis. Required for the sparse form when it cannot be
 39        inferred from ``max(i, j) + 1``; ignored for a dense matrix.
 40    bin_size:
 41        Genomic bin size in base pairs, a positive number, used to label axes
 42        in bp/kb/Mb. ``None`` labels axes by bin index.
 43    chrom:
 44        Optional chromosome name shown as the axis title.
 45    colormap:
 46        Colormap for intensity: sequential ``"viridis"`` (default) or ``"ltc"``
 47        (an earthy teal to sand to rust ramp), or diverging ``"rdbu"`` or
 48        ``"ltcdiv"`` (its counterpart, neutral cream at the midpoint).
 49    transform:
 50        Intensity transform, ``"log"`` (default) or ``"linear"``.
 51    vmax:
 52        Upper clip of the intensity scale: a finite number greater than
 53        ``vmin``, and greater than 0 with the log transform. ``None``
 54        auto-picks a high percentile.
 55    vmax_percentile:
 56        Percentile in (0, 1] used for the auto ``vmax`` when ``vmax`` is
 57        ``None``. ``None`` uses the component default.
 58    vmin:
 59        Lower clip of the intensity scale, a finite number. ``None`` uses 0.
 60        With the log transform, or when ``vmin`` is 0 or more, values at or
 61        below it are drawn as background. With the linear transform and a
 62        negative ``vmin`` (for example observed/expected log2 ratios), values
 63        below it take the lowest color.
 64    symmetric:
 65        Mirror sparse ``i``/``j``/``v`` entries across the diagonal: ``True``
 66        or ``False``.
 67    label:
 68        Axis title (overrides ``chrom`` when set).
 69    theme:
 70        Optional theme overrides forwarded to the JS renderer. Its
 71        ``padding`` entry is the space in px between the edge of the widget
 72        and the plot: one number for every side, or a dict with any of the
 73        keys ``top``, ``right``, ``bottom`` and ``left``, a side left out
 74        keeping the default of 10.
 75        A colour given as a CSS custom property, such as
 76        ``"background": "var(--bg)"``, takes the value the page gives it when
 77        the plot draws. After the page changes the property, what the plot
 78        drew on a canvas keeps the old colour until it draws again: resize
 79        the widget or display it again.
 80    height:
 81        Initial widget height in CSS pixels.
 82
 83    Examples
 84    --------
 85    >>> import numpy as np
 86    >>> n = 256
 87    >>> d = np.abs(np.subtract.outer(np.arange(n), np.arange(n)))
 88    >>> m = 1000 / (d + 1) ** 1.2 + np.random.rand(n, n)
 89    >>> m = (m + m.T) / 2  # symmetrize
 90    >>> HiC(m, bin_size=10_000, chrom="chr1")  # doctest: +SKIP
 91
 92    >>> # sparse COO form
 93    >>> HiC((np.array([0, 1]), np.array([1, 2]), np.array([5.0, 3.0])), n=3)  # doctest: +SKIP
 94    """
 95
 96    _esm = STATIC / "hic.js"
 97
 98    def __init__(
 99        self,
100        matrix: Any = None,
101        *,
102        i: Any = None,
103        j: Any = None,
104        v: Any = None,
105        n: int | None = None,
106        bin_size: float | None = None,
107        chrom: str | None = None,
108        colormap: Literal["viridis", "rdbu", "ltc", "ltcdiv"] = "viridis",
109        transform: str = "log",
110        vmax: float | None = None,
111        vmax_percentile: float | None = None,
112        vmin: float | None = 0.0,
113        symmetric: bool = True,
114        label: str | None = None,
115        theme: dict | None = None,
116        height: int = 480,
117        **kwargs: Any,
118    ) -> None:
119        if transform not in ("log", "linear"):
120            raise ValueError("`transform` must be 'log' or 'linear'.")
121        _check_choice(colormap, "colormap", _COLORMAPS)
122        bin_size = _number(
123            bin_size, "bin_size", "a single positive number", lambda v: v > 0
124        )
125        vmin = _number(vmin, "vmin")
126        vmax = _number(vmax, "vmax")
127        vmax_percentile = _number(
128            vmax_percentile, "vmax_percentile", "in (0, 1]", lambda v: 0 < v <= 1
129        )
130        # A vmax at or below the bottom of the scale leaves every cell
131        # background.
132        if vmax is not None:
133            if vmax <= (0.0 if vmin is None else vmin):
134                raise ValueError("`vmax` must be greater than `vmin`.")
135            if transform == "log" and vmax <= 0:
136                raise ValueError(
137                    "`vmax` must be greater than 0 with the log transform."
138                )
139        if isinstance(symmetric, np.ndarray) and symmetric.ndim == 0:
140            symmetric = symmetric.item()
141        if not isinstance(symmetric, (bool, np.bool_)):
142            raise ValueError("`symmetric` must be a single true or false value.")
143
144        columns: dict[str, Any] = {}
145
146        # Resolve the sparse triplet from any of the accepted shapes.
147        if i is None and j is None and v is None and matrix is not None:
148            i, j, v = _extract_triplet(matrix)
149
150        if i is not None and j is not None and v is not None:
151            # A contact with no row or no column index has no cell. Read as
152            # whole numbers, None stopped as "`i` must be numeric" and NaN
153            # became -2147483648. R stops with the same message.
154            for name, values in (("i", i), ("j", j)):
155                bad = int(
156                    np.count_nonzero(~np.isfinite(_numeric(values, name, np.float64)))
157                )
158                if bad:
159                    raise ValueError(
160                        f"`{name}` has {bad} missing or infinite value(s); "
161                        "every contact needs an `i` and a `j` index."
162                    )
163            i_arr = _numeric(i, "i", np.int32)
164            j_arr = _numeric(j, "j", np.int32)
165            v_arr = _numeric(v, "v", np.float32)
166            # Empty triplet: fail clearly instead of building an n=0 matrix.
167            if i_arr.size == 0:
168                raise ValueError(
169                    "sparse `i`/`j`/`v` triplet is empty; provide at least one "
170                    "contact."
171                )
172            if not (i_arr.size == j_arr.size == v_arr.size):
173                raise ValueError(
174                    "`i`, `j` and `v` must have the same length; "
175                    f"got i={i_arr.size}, j={j_arr.size}, v={v_arr.size}"
176                )
177            if n is None:
178                n = int(max(int(i_arr.max()), int(j_arr.max())) + 1)
179            n = int(n)
180            if n <= 0:
181                raise ValueError("`n` must be a positive number of bins.")
182            if int(i_arr.min()) < 0 or int(j_arr.min()) < 0 or \
183                    int(i_arr.max()) >= n or int(j_arr.max()) >= n:
184                raise ValueError(
185                    f"sparse indices `i`/`j` must be in [0, {n}); got "
186                    f"i in [{int(i_arr.min())}, {int(i_arr.max())}], "
187                    f"j in [{int(j_arr.min())}, {int(j_arr.max())}]"
188                )
189            columns = {"i": i_arr, "j": j_arr, "v": v_arr}
190        elif matrix is not None:
191            arr = _numeric(matrix, "matrix", np.float32)
192            if arr.ndim != 2 or arr.shape[0] != arr.shape[1]:
193                raise ValueError("`matrix` must be a square 2-D array.")
194            n = int(arr.shape[0])
195            if n == 0:
196                raise ValueError("`matrix` must contain at least one row and one column.")
197            # Row-major (C order) flatten to match the JS `values` contract.
198            columns = {"values": np.ascontiguousarray(arr).reshape(-1)}
199        else:
200            raise ValueError(
201                "Provide a dense `matrix` or a sparse triplet (i, j, v)."
202            )
203
204        buffer, schema = pack_columns(columns, names={"values": "matrix"})
205
206        meta: dict[str, Any] = {"n": int(n)}
207        if bin_size is not None:
208            meta["binSize"] = bin_size
209        if chrom is not None:
210            meta["chrom"] = str(chrom)
211
212        options: dict[str, Any] = {
213            "colormap": colormap,
214            "transform": transform,
215            "symmetric": bool(symmetric),
216        }
217        if vmin is not None:
218            options["vmin"] = vmin
219        # `vmax=None` means auto; only send it when the user fixed it.
220        if vmax is not None:
221            options["vmax"] = vmax
222        if vmax_percentile is not None:
223            options["vmaxPercentile"] = vmax_percentile
224        if label is not None:
225            options["label"] = str(label)
226        if theme is not None:
227            options["theme"] = theme
228
229        super().__init__(
230            buffer=buffer,
231            schema=schema,
232            data={"columns": {}, "meta": meta},
233            options=options,
234            _height=height,
235            **kwargs,
236        )

GPU-accelerated Hi-C chromatin contact map.

The contact matrix is normalized to an 8-bit texture and drawn as one WebGL quad, with the colormap applied in the fragment shader, so pan/zoom stays smooth on very large matrices. A precomputed level-of-detail pyramid keeps interaction fast when zoomed out. Genomic coordinate ticks and the colorbar are crisp vector overlays. No tile server is required.

Parameters
  • matrix:: Either a 2-D square array of contact counts (dense), as a NumPy array or a nested list of rows, or a COO-like triplet of (i, j, v) for the sparse form. A triplet may be given as a tuple (i, j, v), a mapping with keys i/j/v (e.g. a DataFrame), or via the i, j, v keyword arguments. A list of three sequences is also read as a triplet, unless it is a 3x3 nested list, which is read as a dense matrix; pass a tuple or the keywords for a three-contact triplet.
  • n:: Number of bins per axis. Required for the sparse form when it cannot be inferred from max(i, j) + 1; ignored for a dense matrix.
  • bin_size:: Genomic bin size in base pairs, a positive number, used to label axes in bp/kb/Mb. None labels axes by bin index.
  • chrom:: Optional chromosome name shown as the axis title.
  • colormap:: Colormap for intensity: sequential "viridis" (default) or "ltc" (an earthy teal to sand to rust ramp), or diverging "rdbu" or "ltcdiv" (its counterpart, neutral cream at the midpoint).
  • transform:: Intensity transform, "log" (default) or "linear".
  • vmax:: Upper clip of the intensity scale: a finite number greater than vmin, and greater than 0 with the log transform. None auto-picks a high percentile.
  • vmax_percentile:: Percentile in (0, 1] used for the auto vmax when vmax is None. None uses the component default.
  • vmin:: Lower clip of the intensity scale, a finite number. None uses 0. With the log transform, or when vmin is 0 or more, values at or below it are drawn as background. With the linear transform and a negative vmin (for example observed/expected log2 ratios), values below it take the lowest color.
  • symmetric:: Mirror sparse i/j/v entries across the diagonal: True or False.
  • label:: Axis title (overrides chrom when set).
  • theme:: Optional theme overrides forwarded to the JS renderer. Its padding entry is the space in px between the edge of the widget and the plot: one number for every side, or a dict with any of the keys top, right, bottom and left, a side left out keeping the default of 10. A colour given as a CSS custom property, such as "background": "var(--bg)", takes the value the page gives it when the plot draws. After the page changes the property, what the plot drew on a canvas keeps the old colour until it draws again: resize the widget or display it again.
  • height:: Initial widget height in CSS pixels.
Examples
>>> import numpy as np
>>> n = 256
>>> d = np.abs(np.subtract.outer(np.arange(n), np.arange(n)))
>>> m = 1000 / (d + 1) ** 1.2 + np.random.rand(n, n)
>>> m = (m + m.T) / 2  # symmetrize
>>> HiC(m, bin_size=10_000, chrom="chr1")  # doctest: +SKIP
>>> # sparse COO form
>>> HiC((np.array([0, 1]), np.array([1, 2]), np.array([5.0, 3.0])), n=3)  # doctest: +SKIP
HiC( matrix: Any = None, *, i: Any = None, j: Any = None, v: Any = None, n: int | None = None, bin_size: float | None = None, chrom: str | None = None, colormap: Literal['viridis', 'rdbu', 'ltc', 'ltcdiv'] = 'viridis', transform: str = 'log', vmax: float | None = None, vmax_percentile: float | None = None, vmin: float | None = 0.0, symmetric: bool = True, label: str | None = None, theme: dict | None = None, height: int = 480, **kwargs: Any)
 98    def __init__(
 99        self,
100        matrix: Any = None,
101        *,
102        i: Any = None,
103        j: Any = None,
104        v: Any = None,
105        n: int | None = None,
106        bin_size: float | None = None,
107        chrom: str | None = None,
108        colormap: Literal["viridis", "rdbu", "ltc", "ltcdiv"] = "viridis",
109        transform: str = "log",
110        vmax: float | None = None,
111        vmax_percentile: float | None = None,
112        vmin: float | None = 0.0,
113        symmetric: bool = True,
114        label: str | None = None,
115        theme: dict | None = None,
116        height: int = 480,
117        **kwargs: Any,
118    ) -> None:
119        if transform not in ("log", "linear"):
120            raise ValueError("`transform` must be 'log' or 'linear'.")
121        _check_choice(colormap, "colormap", _COLORMAPS)
122        bin_size = _number(
123            bin_size, "bin_size", "a single positive number", lambda v: v > 0
124        )
125        vmin = _number(vmin, "vmin")
126        vmax = _number(vmax, "vmax")
127        vmax_percentile = _number(
128            vmax_percentile, "vmax_percentile", "in (0, 1]", lambda v: 0 < v <= 1
129        )
130        # A vmax at or below the bottom of the scale leaves every cell
131        # background.
132        if vmax is not None:
133            if vmax <= (0.0 if vmin is None else vmin):
134                raise ValueError("`vmax` must be greater than `vmin`.")
135            if transform == "log" and vmax <= 0:
136                raise ValueError(
137                    "`vmax` must be greater than 0 with the log transform."
138                )
139        if isinstance(symmetric, np.ndarray) and symmetric.ndim == 0:
140            symmetric = symmetric.item()
141        if not isinstance(symmetric, (bool, np.bool_)):
142            raise ValueError("`symmetric` must be a single true or false value.")
143
144        columns: dict[str, Any] = {}
145
146        # Resolve the sparse triplet from any of the accepted shapes.
147        if i is None and j is None and v is None and matrix is not None:
148            i, j, v = _extract_triplet(matrix)
149
150        if i is not None and j is not None and v is not None:
151            # A contact with no row or no column index has no cell. Read as
152            # whole numbers, None stopped as "`i` must be numeric" and NaN
153            # became -2147483648. R stops with the same message.
154            for name, values in (("i", i), ("j", j)):
155                bad = int(
156                    np.count_nonzero(~np.isfinite(_numeric(values, name, np.float64)))
157                )
158                if bad:
159                    raise ValueError(
160                        f"`{name}` has {bad} missing or infinite value(s); "
161                        "every contact needs an `i` and a `j` index."
162                    )
163            i_arr = _numeric(i, "i", np.int32)
164            j_arr = _numeric(j, "j", np.int32)
165            v_arr = _numeric(v, "v", np.float32)
166            # Empty triplet: fail clearly instead of building an n=0 matrix.
167            if i_arr.size == 0:
168                raise ValueError(
169                    "sparse `i`/`j`/`v` triplet is empty; provide at least one "
170                    "contact."
171                )
172            if not (i_arr.size == j_arr.size == v_arr.size):
173                raise ValueError(
174                    "`i`, `j` and `v` must have the same length; "
175                    f"got i={i_arr.size}, j={j_arr.size}, v={v_arr.size}"
176                )
177            if n is None:
178                n = int(max(int(i_arr.max()), int(j_arr.max())) + 1)
179            n = int(n)
180            if n <= 0:
181                raise ValueError("`n` must be a positive number of bins.")
182            if int(i_arr.min()) < 0 or int(j_arr.min()) < 0 or \
183                    int(i_arr.max()) >= n or int(j_arr.max()) >= n:
184                raise ValueError(
185                    f"sparse indices `i`/`j` must be in [0, {n}); got "
186                    f"i in [{int(i_arr.min())}, {int(i_arr.max())}], "
187                    f"j in [{int(j_arr.min())}, {int(j_arr.max())}]"
188                )
189            columns = {"i": i_arr, "j": j_arr, "v": v_arr}
190        elif matrix is not None:
191            arr = _numeric(matrix, "matrix", np.float32)
192            if arr.ndim != 2 or arr.shape[0] != arr.shape[1]:
193                raise ValueError("`matrix` must be a square 2-D array.")
194            n = int(arr.shape[0])
195            if n == 0:
196                raise ValueError("`matrix` must contain at least one row and one column.")
197            # Row-major (C order) flatten to match the JS `values` contract.
198            columns = {"values": np.ascontiguousarray(arr).reshape(-1)}
199        else:
200            raise ValueError(
201                "Provide a dense `matrix` or a sparse triplet (i, j, v)."
202            )
203
204        buffer, schema = pack_columns(columns, names={"values": "matrix"})
205
206        meta: dict[str, Any] = {"n": int(n)}
207        if bin_size is not None:
208            meta["binSize"] = bin_size
209        if chrom is not None:
210            meta["chrom"] = str(chrom)
211
212        options: dict[str, Any] = {
213            "colormap": colormap,
214            "transform": transform,
215            "symmetric": bool(symmetric),
216        }
217        if vmin is not None:
218            options["vmin"] = vmin
219        # `vmax=None` means auto; only send it when the user fixed it.
220        if vmax is not None:
221            options["vmax"] = vmax
222        if vmax_percentile is not None:
223            options["vmaxPercentile"] = vmax_percentile
224        if label is not None:
225            options["label"] = str(label)
226        if theme is not None:
227            options["theme"] = theme
228
229        super().__init__(
230            buffer=buffer,
231            schema=schema,
232            data={"columns": {}, "meta": meta},
233            options=options,
234            _height=height,
235            **kwargs,
236        )

Public constructor

class IGV(plotomics.PlotomicsWidget):
11class IGV(PlotomicsWidget):
12    """Embeddable interactive genome browser powered by igv.js.
13
14    Unlike the other plotomics widgets this one is *config-driven*: igv.js streams
15    and tiles remote indexed files (BAM/CRAM, bigWig, VCF, BED, ...) itself, so
16    data flows through the browser configuration as URLs rather than as columns.
17
18    Supply either a full igv.js ``config`` or the convenience arguments
19    ``genome``, ``locus`` and ``tracks``, which are assembled into a config when
20    ``config`` is ``None``. A later change to ``options["locus"]`` or
21    ``options["tracks"]`` applies to the live browser in both cases.
22
23    Parameters
24    ----------
25    genome:
26        Genome identifier understood by igv.js (e.g. ``"hg38"``, ``"hg19"``,
27        ``"mm10"``). Used when ``config`` is ``None``. ``None`` sends no
28        genome, so igv.js starts with no reference loaded, as ``genome: null``
29        does in JavaScript; pass a ``config`` with a ``reference`` for an
30        assembly igv.js does not know.
31    locus:
32        Optional initial locus, e.g. ``"chr8:127,736,588-127,739,371"``, or a
33        gene symbol.
34    tracks:
35        A sequence of igv.js track configuration dicts (each with at least a
36        ``url``). Used when ``config`` is ``None``. Tracks are additive: a
37        track already shown is not loaded again, a changed track loads as a
38        new one, and a track left out stays shown.
39    config:
40        Optional full igv.js browser configuration dict. When supplied it is
41        passed through as-is and ``genome``, ``locus`` and ``tracks`` are not
42        sent.
43    height:
44        Initial widget height in CSS pixels.
45
46    Examples
47    --------
48    >>> IGV(genome="hg38")  # doctest: +SKIP
49    >>> IGV(  # doctest: +SKIP
50    ...     genome="hg38",
51    ...     locus="chr8:127,736,588-127,739,371",
52    ...     tracks=[{
53    ...         "name": "CTCF",
54    ...         "url": "https://www.encodeproject.org/files/ENCFF356YES/@@download/ENCFF356YES.bigWig",
55    ...         "format": "bigWig",
56    ...     }],
57    ... )
58    """
59
60    _esm = STATIC / "igv.js"
61
62    def __init__(
63        self,
64        *,
65        genome: str | None = "hg38",
66        locus: str | None = None,
67        tracks: Sequence[Mapping[str, Any]] | None = None,
68        config: Mapping[str, Any] | None = None,
69        height: int = 480,
70        **kwargs: Any,
71    ) -> None:
72        options: dict[str, Any] = {}
73        if config is not None:
74            options["config"] = dict(config)
75        else:
76            # None crosses as null, so the browser's "hg38" default does not
77            # take its place.
78            options["genome"] = genome
79            if locus is not None:
80                options["locus"] = locus
81            if tracks:
82                options["tracks"] = [dict(t) for t in tracks]
83
84        # igv streams via config URLs, so there are no data columns.
85        super().__init__(
86            data={"columns": {}, "meta": {}},
87            options=options,
88            _height=height,
89            **kwargs,
90        )

Embeddable interactive genome browser powered by igv.js.

Unlike the other plotomics widgets this one is config-driven: igv.js streams and tiles remote indexed files (BAM/CRAM, bigWig, VCF, BED, ...) itself, so data flows through the browser configuration as URLs rather than as columns.

Supply either a full igv.js config or the convenience arguments genome, locus and tracks, which are assembled into a config when config is None. A later change to options["locus"] or options["tracks"] applies to the live browser in both cases.

Parameters
  • genome:: Genome identifier understood by igv.js (e.g. "hg38", "hg19", "mm10"). Used when config is None. None sends no genome, so igv.js starts with no reference loaded, as genome: null does in JavaScript; pass a config with a reference for an assembly igv.js does not know.
  • locus:: Optional initial locus, e.g. "chr8:127,736,588-127,739,371", or a gene symbol.
  • tracks:: A sequence of igv.js track configuration dicts (each with at least a url). Used when config is None. Tracks are additive: a track already shown is not loaded again, a changed track loads as a new one, and a track left out stays shown.
  • config:: Optional full igv.js browser configuration dict. When supplied it is passed through as-is and genome, locus and tracks are not sent.
  • height:: Initial widget height in CSS pixels.
Examples
>>> IGV(genome="hg38")  # doctest: +SKIP
>>> IGV(  # doctest: +SKIP
...     genome="hg38",
...     locus="chr8:127,736,588-127,739,371",
...     tracks=[{
...         "name": "CTCF",
...         "url": "https://www.encodeproject.org/files/ENCFF356YES/@@download/ENCFF356YES.bigWig",
...         "format": "bigWig",
...     }],
... )
IGV( *, genome: str | None = 'hg38', locus: str | None = None, tracks: Optional[Sequence[Mapping[str, Any]]] = None, config: Optional[Mapping[str, Any]] = None, height: int = 480, **kwargs: Any)
62    def __init__(
63        self,
64        *,
65        genome: str | None = "hg38",
66        locus: str | None = None,
67        tracks: Sequence[Mapping[str, Any]] | None = None,
68        config: Mapping[str, Any] | None = None,
69        height: int = 480,
70        **kwargs: Any,
71    ) -> None:
72        options: dict[str, Any] = {}
73        if config is not None:
74            options["config"] = dict(config)
75        else:
76            # None crosses as null, so the browser's "hg38" default does not
77            # take its place.
78            options["genome"] = genome
79            if locus is not None:
80                options["locus"] = locus
81            if tracks:
82                options["tracks"] = [dict(t) for t in tracks]
83
84        # igv streams via config URLs, so there are no data columns.
85        super().__init__(
86            data={"columns": {}, "meta": {}},
87            options=options,
88            _height=height,
89            **kwargs,
90        )

Public constructor

class Km(plotomics.PlotomicsWidget):
 23class Km(PlotomicsWidget):
 24    """Kaplan-Meier survival curves with a number-at-risk table.
 25
 26    A right-continuous step curve per stratum, censoring ticks, an optional
 27    pointwise confidence band, and the number-at-risk table underneath. The
 28    table is on by default because a survival curve without one hides how much
 29    of its tail rests on a handful of patients, which is where readers
 30    over-read it.
 31
 32    The widget draws, it does not estimate. Pass what your fit produced, from
 33    ``lifelines``, ``scikit-survival`` or anywhere else, so a figure rendered
 34    here and the same figure rendered by your library cannot disagree about
 35    where a curve steps.
 36
 37    Parameters
 38    ----------
 39    data:
 40        A pandas ``DataFrame`` or mapping of arrays with numeric ``time`` and
 41        ``surv`` columns and optional ``lower``, ``upper`` and ``group``
 42        columns. Within a stratum, rows must be in ascending time order. A
 43        row with a missing ``time`` or ``surv`` (None or NaN) is left out
 44        with a warning, as in R, so the step before it runs on to the next
 45        row. An infinite ``time`` is not drawn, and a missing or infinite
 46        ``lower`` or ``upper`` leaves a gap in the band; both warn, as in R.
 47    groups:
 48        Fixes the stratum order and colour assignment. Defaults to order of
 49        appearance, or to a pandas Categorical's categories.
 50    group_colors:
 51        One hex colour per stratum. ``None`` uses the categorical palette.
 52    censor:
 53        Optional mapping with ``time`` and ``surv`` arrays, and an optional
 54        ``group`` array, marking censoring ticks. R's ``km(censor =)`` takes
 55        the same columns. A tick with a missing or infinite ``time`` or
 56        ``surv`` has no place on the plot and is left out with a warning, as
 57        in R.
 58    risk_times:
 59        Times for the at-risk table, also used as the x-axis ticks.
 60    risk_counts:
 61        Array shaped (strata, len(risk_times)) of the number still at risk.
 62    p_label:
 63        Optional annotation drawn inside the panel, e.g. ``"log-rank p =
 64        0.02"``. Not computed here: pass what your test returned.
 65    show_ci, show_censors, show_risk_table, show_legend:
 66        Toggle the confidence band, censoring ticks, at-risk table and legend.
 67    y_from_zero:
 68        Start the y axis at zero. Opt-out rather than automatic: zooming y
 69        exaggerates separation between curves.
 70    line_width:
 71        Curve stroke width in pixels.
 72    x_label, y_label:
 73        Axis titles.
 74    theme:
 75        Optional theme overrides forwarded to the JS renderer. Its
 76        ``padding`` entry is the space in px between the edge of the widget
 77        and the plot: one number for every side, or a dict with any of the
 78        keys ``top``, ``right``, ``bottom`` and ``left``, a side left out
 79        keeping the default of 10.
 80        Its ``categorical`` entry is an ordered palette, a list of colours
 81        that go to the strata in order; colours are not matched by name.
 82        A colour given as a CSS custom property, such as
 83        ``"background": "var(--bg)"``, takes the value the page gives it when
 84        the plot draws. After the page changes the property, what the plot
 85        drew on a canvas keeps the old colour until it draws again: resize
 86        the widget or display it again.
 87    height:
 88        Initial widget height in CSS pixels.
 89
 90    Examples
 91    --------
 92    >>> import pandas as pd
 93    >>> df = pd.DataFrame({
 94    ...     "time": [0, 5, 12, 0, 7, 15],
 95    ...     "surv": [1, 0.9, 0.7, 1, 0.8, 0.5],
 96    ...     "group": ["treated"] * 3 + ["control"] * 3,
 97    ... })
 98    >>> Km(df)  # doctest: +SKIP
 99    """
100
101    _esm = STATIC / "km.js"
102
103    def __init__(
104        self,
105        data: Any,
106        *,
107        groups: list[str] | None = None,
108        group_colors: list[str] | None = None,
109        censor: Any = None,
110        risk_times: Any = None,
111        risk_counts: Any = None,
112        p_label: str | None = None,
113        show_ci: bool = True,
114        show_censors: bool = True,
115        show_risk_table: bool = True,
116        show_legend: bool = True,
117        y_from_zero: bool = True,
118        line_width: float = 2.0,
119        x_label: str = "time",
120        y_label: str = "overall survival",
121        theme: dict | None = None,
122        height: int = 520,
123        **kwargs: Any,
124    ) -> None:
125        t = _column(data, "time")
126        s = _column(data, "surv")
127        if t is None or s is None:
128            raise ValueError("`data` must provide `time` and `surv` columns.")
129
130        time = _to_float32(t, "time")
131        surv = _to_float32(s, "surv")
132        if time.size == 0:
133            raise ValueError("`data` must contain at least one row.")
134
135        numeric: dict[str, Any] = {"time": time, "surv": surv}
136        for name in ("lower", "upper"):
137            col = _column(data, name)
138            if col is not None:
139                numeric[name] = _to_float32(col, name)
140        grp_col = _column(data, "group")
141        # A missing group crosses as null (no curve), never as a group "nan".
142        grp = _text_or_none(grp_col) if grp_col is not None else None
143
144        # Every column has one value per row. This is checked before any row
145        # is left out, so a short column is never paired with the wrong rows.
146        sizes = {k: int(v.size) for k, v in numeric.items()}
147        if grp is not None:
148            sizes["group"] = len(grp)
149        if len(set(sizes.values())) > 1:
150            detail = ", ".join(f"{k}={n}" for k, n in sizes.items())
151            raise ValueError(
152                f"columns must all have the same length; got {detail}"
153            )
154
155        # A row with no time or no estimate has no place on the curve. Drawn,
156        # it would join its neighbours with a slope; left out, the step
157        # before it runs on to the next row. R leaves it out with the same
158        # warning.
159        keep = ~(np.isnan(time) | np.isnan(surv))
160        if not keep.all():
161            warnings.warn(
162                f"Left out {int(keep.size - keep.sum())} row(s) with a "
163                "missing `time` or `surv`.",
164                stacklevel=2,
165            )
166            if not keep.any():
167                raise ValueError("`data` must contain at least one row.")
168            numeric = {k: v[keep] for k, v in numeric.items()}
169            if grp is not None:
170                grp = [g for g, k in zip(grp, keep) if k]
171        # An infinite time has no place on the axis, and the browser leaves
172        # the row out. An infinite surv fails the check below. R words both
173        # the same way.
174        n_inf = int(np.count_nonzero(np.isinf(numeric["time"])))
175        if n_inf:
176            warnings.warn(
177                f"`time` has {n_inf} infinite value(s); those rows are not "
178                "drawn.",
179                stacklevel=2,
180            )
181        surv = numeric["surv"]
182        if np.any(surv < 0) or np.any(surv > 1):
183            raise ValueError("`surv` must be a probability in [0, 1].")
184        # A missing or infinite bound leaves a gap in the band, with the
185        # warning R gives.
186        for name in ("lower", "upper"):
187            if name not in numeric:
188                continue
189            n_gap = int(np.count_nonzero(~np.isfinite(numeric[name])))
190            if n_gap:
191                warnings.warn(
192                    f"`{name}` has {n_gap} value(s) that are missing (NA or "
193                    "NaN) or infinite; the confidence band has a gap there.",
194                    stacklevel=2,
195                )
196        buffer, schema = pack_columns(
197            numeric, quiet=("time", "surv", "lower", "upper")
198        )
199
200        json_columns: dict[str, list] = {}
201        if grp is not None:
202            json_columns["group"] = grp
203
204        meta: dict[str, Any] = {}
205        if groups is None and grp_col is not None:
206            # A pandas Categorical is the caller stating the stratum order.
207            cats = _category_levels(grp_col)
208            if cats is not None:
209                groups = cats
210            else:
211                seen: list[str] = []
212                for g in grp:
213                    if g is not None and g not in seen:
214                        seen.append(g)
215                groups = seen
216        if groups is not None:
217            groups = [str(g) for g in groups]
218            unknown = sorted({g for g in grp or [] if g is not None} - set(groups))
219            if unknown:
220                raise ValueError(
221                    "stratum/strata not present in `groups`: " + ", ".join(unknown)
222                )
223            meta["groups"] = groups
224        # A single curve has one stratum, so its colour is sent too.
225        if group_colors is not None:
226            n_strata = 1 if groups is None else len(groups)
227            if len(group_colors) != n_strata:
228                raise ValueError("`group_colors` must have one entry per stratum.")
229            meta["groupColors"] = [str(c) for c in group_colors]
230
231        if censor is not None:
232            ct = _column(censor, "time")
233            cs = _column(censor, "surv")
234            if ct is None or cs is None:
235                # R stops too; leaving the ticks out would hide the mistake.
236                raise ValueError(
237                    "`censor` must provide `time` and `surv` columns."
238                )
239            ct_arr = _to_float64(ct, "time")
240            cs_arr = _to_float64(cs, "surv")
241            cg = _column(censor, "group")
242            # A tick with no group is left out, like its curve.
243            cg_list = _text_or_none(cg) if cg is not None else None
244            lengths = {"time": int(ct_arr.size), "surv": int(cs_arr.size)}
245            if cg_list is not None:
246                lengths["group"] = len(cg_list)
247            if len(set(lengths.values())) > 1:
248                detail = ", ".join(f"{k}={n}" for k, n in lengths.items())
249                raise ValueError(
250                    f"`censor` columns must all have the same length; got {detail}"
251                )
252            # A tick with no time or no survival has no place on the plot;
253            # sent, NaN made the widget data invalid JSON. R leaves it out
254            # with the same warning.
255            keep = np.isfinite(ct_arr) & np.isfinite(cs_arr)
256            if not keep.all():
257                warnings.warn(
258                    f"Left out {int(keep.size - keep.sum())} censor mark(s) "
259                    "with a missing or infinite `time` or `surv`.",
260                    stacklevel=2,
261                )
262            if keep.any():
263                meta["censorTime"] = [float(v) for v in ct_arr[keep]]
264                meta["censorSurv"] = [float(v) for v in cs_arr[keep]]
265                if cg_list is not None:
266                    meta["censorGroup"] = [
267                        g for g, k in zip(cg_list, keep) if k
268                    ]
269
270        if risk_times is not None:
271            times = [float(v) for v in risk_times]
272            meta["riskTimes"] = times
273            if risk_counts is not None:
274                counts = np.atleast_2d(np.asarray(risk_counts))
275                if counts.shape[1] != len(times):
276                    raise ValueError(
277                        "`risk_counts` must have one column per `risk_times` entry."
278                    )
279                if groups is not None and counts.shape[0] != len(groups):
280                    raise ValueError(
281                        "`risk_counts` must have one row per stratum."
282                    )
283                # A DataFrame indexed by stratum is put in `groups` order, as
284                # R does with a matrix that has row names.
285                index = getattr(risk_counts, "index", None)
286                if (
287                    groups is not None
288                    and hasattr(risk_counts, "iloc")
289                    and type(index).__name__ != "RangeIndex"
290                ):
291                    labels = [str(v) for v in index]
292                    if len(set(labels)) == len(labels) and set(labels) == set(groups):
293                        counts = counts[[labels.index(g) for g in groups]]
294                # Row-major: the component indexes it as group * ntimes + j.
295                meta["riskCounts"] = [int(v) for v in counts.reshape(-1)]
296
297        if p_label is not None:
298            meta["pLabel"] = str(p_label)
299
300        options: dict[str, Any] = {
301            "showCI": show_ci,
302            "showCensors": show_censors,
303            "showRiskTable": show_risk_table,
304            "showLegend": show_legend,
305            "yFromZero": y_from_zero,
306            "lineWidth": line_width,
307            "xLabel": x_label,
308            "yLabel": y_label,
309        }
310        if theme is not None:
311            options["theme"] = theme
312
313        super().__init__(
314            buffer=buffer,
315            schema=schema,
316            data={"columns": json_columns, "meta": meta},
317            options=options,
318            _height=height,
319            **kwargs,
320        )

Kaplan-Meier survival curves with a number-at-risk table.

A right-continuous step curve per stratum, censoring ticks, an optional pointwise confidence band, and the number-at-risk table underneath. The table is on by default because a survival curve without one hides how much of its tail rests on a handful of patients, which is where readers over-read it.

The widget draws, it does not estimate. Pass what your fit produced, from lifelines, scikit-survival or anywhere else, so a figure rendered here and the same figure rendered by your library cannot disagree about where a curve steps.

Parameters
  • data:: A pandas DataFrame or mapping of arrays with numeric time and surv columns and optional lower, upper and group columns. Within a stratum, rows must be in ascending time order. A row with a missing time or surv (None or NaN) is left out with a warning, as in R, so the step before it runs on to the next row. An infinite time is not drawn, and a missing or infinite lower or upper leaves a gap in the band; both warn, as in R.
  • groups:: Fixes the stratum order and colour assignment. Defaults to order of appearance, or to a pandas Categorical's categories.
  • group_colors:: One hex colour per stratum. None uses the categorical palette.
  • censor:: Optional mapping with time and surv arrays, and an optional group array, marking censoring ticks. R's km(censor =) takes the same columns. A tick with a missing or infinite time or surv has no place on the plot and is left out with a warning, as in R.
  • risk_times:: Times for the at-risk table, also used as the x-axis ticks.
  • risk_counts:: Array shaped (strata, len(risk_times)) of the number still at risk.
  • p_label:: Optional annotation drawn inside the panel, e.g. "log-rank p = 0.02". Not computed here: pass what your test returned.
  • show_ci, show_censors, show_risk_table, show_legend:: Toggle the confidence band, censoring ticks, at-risk table and legend.
  • y_from_zero:: Start the y axis at zero. Opt-out rather than automatic: zooming y exaggerates separation between curves.
  • line_width:: Curve stroke width in pixels.
  • x_label, y_label:: Axis titles.
  • theme:: Optional theme overrides forwarded to the JS renderer. Its padding entry is the space in px between the edge of the widget and the plot: one number for every side, or a dict with any of the keys top, right, bottom and left, a side left out keeping the default of 10. Its categorical entry is an ordered palette, a list of colours that go to the strata in order; colours are not matched by name. A colour given as a CSS custom property, such as "background": "var(--bg)", takes the value the page gives it when the plot draws. After the page changes the property, what the plot drew on a canvas keeps the old colour until it draws again: resize the widget or display it again.
  • height:: Initial widget height in CSS pixels.
Examples
>>> import pandas as pd
>>> df = pd.DataFrame({
...     "time": [0, 5, 12, 0, 7, 15],
...     "surv": [1, 0.9, 0.7, 1, 0.8, 0.5],
...     "group": ["treated"] * 3 + ["control"] * 3,
... })
>>> Km(df)  # doctest: +SKIP
Km( data: Any, *, groups: list[str] | None = None, group_colors: list[str] | None = None, censor: Any = None, risk_times: Any = None, risk_counts: Any = None, p_label: str | None = None, show_ci: bool = True, show_censors: bool = True, show_risk_table: bool = True, show_legend: bool = True, y_from_zero: bool = True, line_width: float = 2.0, x_label: str = 'time', y_label: str = 'overall survival', theme: dict | None = None, height: int = 520, **kwargs: Any)
103    def __init__(
104        self,
105        data: Any,
106        *,
107        groups: list[str] | None = None,
108        group_colors: list[str] | None = None,
109        censor: Any = None,
110        risk_times: Any = None,
111        risk_counts: Any = None,
112        p_label: str | None = None,
113        show_ci: bool = True,
114        show_censors: bool = True,
115        show_risk_table: bool = True,
116        show_legend: bool = True,
117        y_from_zero: bool = True,
118        line_width: float = 2.0,
119        x_label: str = "time",
120        y_label: str = "overall survival",
121        theme: dict | None = None,
122        height: int = 520,
123        **kwargs: Any,
124    ) -> None:
125        t = _column(data, "time")
126        s = _column(data, "surv")
127        if t is None or s is None:
128            raise ValueError("`data` must provide `time` and `surv` columns.")
129
130        time = _to_float32(t, "time")
131        surv = _to_float32(s, "surv")
132        if time.size == 0:
133            raise ValueError("`data` must contain at least one row.")
134
135        numeric: dict[str, Any] = {"time": time, "surv": surv}
136        for name in ("lower", "upper"):
137            col = _column(data, name)
138            if col is not None:
139                numeric[name] = _to_float32(col, name)
140        grp_col = _column(data, "group")
141        # A missing group crosses as null (no curve), never as a group "nan".
142        grp = _text_or_none(grp_col) if grp_col is not None else None
143
144        # Every column has one value per row. This is checked before any row
145        # is left out, so a short column is never paired with the wrong rows.
146        sizes = {k: int(v.size) for k, v in numeric.items()}
147        if grp is not None:
148            sizes["group"] = len(grp)
149        if len(set(sizes.values())) > 1:
150            detail = ", ".join(f"{k}={n}" for k, n in sizes.items())
151            raise ValueError(
152                f"columns must all have the same length; got {detail}"
153            )
154
155        # A row with no time or no estimate has no place on the curve. Drawn,
156        # it would join its neighbours with a slope; left out, the step
157        # before it runs on to the next row. R leaves it out with the same
158        # warning.
159        keep = ~(np.isnan(time) | np.isnan(surv))
160        if not keep.all():
161            warnings.warn(
162                f"Left out {int(keep.size - keep.sum())} row(s) with a "
163                "missing `time` or `surv`.",
164                stacklevel=2,
165            )
166            if not keep.any():
167                raise ValueError("`data` must contain at least one row.")
168            numeric = {k: v[keep] for k, v in numeric.items()}
169            if grp is not None:
170                grp = [g for g, k in zip(grp, keep) if k]
171        # An infinite time has no place on the axis, and the browser leaves
172        # the row out. An infinite surv fails the check below. R words both
173        # the same way.
174        n_inf = int(np.count_nonzero(np.isinf(numeric["time"])))
175        if n_inf:
176            warnings.warn(
177                f"`time` has {n_inf} infinite value(s); those rows are not "
178                "drawn.",
179                stacklevel=2,
180            )
181        surv = numeric["surv"]
182        if np.any(surv < 0) or np.any(surv > 1):
183            raise ValueError("`surv` must be a probability in [0, 1].")
184        # A missing or infinite bound leaves a gap in the band, with the
185        # warning R gives.
186        for name in ("lower", "upper"):
187            if name not in numeric:
188                continue
189            n_gap = int(np.count_nonzero(~np.isfinite(numeric[name])))
190            if n_gap:
191                warnings.warn(
192                    f"`{name}` has {n_gap} value(s) that are missing (NA or "
193                    "NaN) or infinite; the confidence band has a gap there.",
194                    stacklevel=2,
195                )
196        buffer, schema = pack_columns(
197            numeric, quiet=("time", "surv", "lower", "upper")
198        )
199
200        json_columns: dict[str, list] = {}
201        if grp is not None:
202            json_columns["group"] = grp
203
204        meta: dict[str, Any] = {}
205        if groups is None and grp_col is not None:
206            # A pandas Categorical is the caller stating the stratum order.
207            cats = _category_levels(grp_col)
208            if cats is not None:
209                groups = cats
210            else:
211                seen: list[str] = []
212                for g in grp:
213                    if g is not None and g not in seen:
214                        seen.append(g)
215                groups = seen
216        if groups is not None:
217            groups = [str(g) for g in groups]
218            unknown = sorted({g for g in grp or [] if g is not None} - set(groups))
219            if unknown:
220                raise ValueError(
221                    "stratum/strata not present in `groups`: " + ", ".join(unknown)
222                )
223            meta["groups"] = groups
224        # A single curve has one stratum, so its colour is sent too.
225        if group_colors is not None:
226            n_strata = 1 if groups is None else len(groups)
227            if len(group_colors) != n_strata:
228                raise ValueError("`group_colors` must have one entry per stratum.")
229            meta["groupColors"] = [str(c) for c in group_colors]
230
231        if censor is not None:
232            ct = _column(censor, "time")
233            cs = _column(censor, "surv")
234            if ct is None or cs is None:
235                # R stops too; leaving the ticks out would hide the mistake.
236                raise ValueError(
237                    "`censor` must provide `time` and `surv` columns."
238                )
239            ct_arr = _to_float64(ct, "time")
240            cs_arr = _to_float64(cs, "surv")
241            cg = _column(censor, "group")
242            # A tick with no group is left out, like its curve.
243            cg_list = _text_or_none(cg) if cg is not None else None
244            lengths = {"time": int(ct_arr.size), "surv": int(cs_arr.size)}
245            if cg_list is not None:
246                lengths["group"] = len(cg_list)
247            if len(set(lengths.values())) > 1:
248                detail = ", ".join(f"{k}={n}" for k, n in lengths.items())
249                raise ValueError(
250                    f"`censor` columns must all have the same length; got {detail}"
251                )
252            # A tick with no time or no survival has no place on the plot;
253            # sent, NaN made the widget data invalid JSON. R leaves it out
254            # with the same warning.
255            keep = np.isfinite(ct_arr) & np.isfinite(cs_arr)
256            if not keep.all():
257                warnings.warn(
258                    f"Left out {int(keep.size - keep.sum())} censor mark(s) "
259                    "with a missing or infinite `time` or `surv`.",
260                    stacklevel=2,
261                )
262            if keep.any():
263                meta["censorTime"] = [float(v) for v in ct_arr[keep]]
264                meta["censorSurv"] = [float(v) for v in cs_arr[keep]]
265                if cg_list is not None:
266                    meta["censorGroup"] = [
267                        g for g, k in zip(cg_list, keep) if k
268                    ]
269
270        if risk_times is not None:
271            times = [float(v) for v in risk_times]
272            meta["riskTimes"] = times
273            if risk_counts is not None:
274                counts = np.atleast_2d(np.asarray(risk_counts))
275                if counts.shape[1] != len(times):
276                    raise ValueError(
277                        "`risk_counts` must have one column per `risk_times` entry."
278                    )
279                if groups is not None and counts.shape[0] != len(groups):
280                    raise ValueError(
281                        "`risk_counts` must have one row per stratum."
282                    )
283                # A DataFrame indexed by stratum is put in `groups` order, as
284                # R does with a matrix that has row names.
285                index = getattr(risk_counts, "index", None)
286                if (
287                    groups is not None
288                    and hasattr(risk_counts, "iloc")
289                    and type(index).__name__ != "RangeIndex"
290                ):
291                    labels = [str(v) for v in index]
292                    if len(set(labels)) == len(labels) and set(labels) == set(groups):
293                        counts = counts[[labels.index(g) for g in groups]]
294                # Row-major: the component indexes it as group * ntimes + j.
295                meta["riskCounts"] = [int(v) for v in counts.reshape(-1)]
296
297        if p_label is not None:
298            meta["pLabel"] = str(p_label)
299
300        options: dict[str, Any] = {
301            "showCI": show_ci,
302            "showCensors": show_censors,
303            "showRiskTable": show_risk_table,
304            "showLegend": show_legend,
305            "yFromZero": y_from_zero,
306            "lineWidth": line_width,
307            "xLabel": x_label,
308            "yLabel": y_label,
309        }
310        if theme is not None:
311            options["theme"] = theme
312
313        super().__init__(
314            buffer=buffer,
315            schema=schema,
316            data={"columns": json_columns, "meta": meta},
317            options=options,
318            _height=height,
319            **kwargs,
320        )

Public constructor

class Lollipop(plotomics.PlotomicsWidget):
 64class Lollipop(PlotomicsWidget):
 65    """Variants along a protein, drawn over its domain architecture.
 66
 67    A backbone spanning the sequence with domain rectangles on it, mutation
 68    stems whose head area is proportional to recurrence, and an optional
 69    post-translational modification track below. Variants at one residue
 70    stack on one stem, most recurrent at the bottom, so the top of a stem is
 71    the residue's total. Hotspots inside a functional
 72    domain read very differently from truncating variants scattered across one,
 73    which is what this figure exists to show.
 74
 75    Stems and domains are canvas-drawn so a protein with thousands of variants
 76    stays responsive; labels, axis and legend are a vector overlay.
 77
 78    Parameters
 79    ----------
 80    data:
 81        A pandas ``DataFrame`` or mapping of arrays with ``position``
 82        (amino-acid position, 1-based) and ``count`` (recurrence, zero or
 83        more; a variant with a missing count is not drawn). Optional
 84        ``class`` and ``label`` columns drive the colour and the text labels.
 85    length:
 86        Protein length in residues.
 87    gene, uniprot:
 88        Identifiers shown on the axis title.
 89    domains:
 90        Optional domain rectangles with ``name``, ``start`` and ``end``: a
 91        pandas or polars ``DataFrame`` with those columns, as R takes a data
 92        frame, or a list of mappings with those keys. A domain whose name is
 93        missing (``None``, NaN or pandas NA) is drawn with no name.
 94    ptms:
 95        Optional modification sites with ``position`` and ``type``, as a
 96        ``DataFrame`` or a list of mappings, as for ``domains``.
 97    classes:
 98        Fixes the legend order and colour assignment. Defaults to the classes
 99        present, most frequent first.
100    class_colors, domain_colors:
101        Hex colours. ``None`` gives the classes the categorical palette of the
102        theme. The domains never take that palette: ``None`` gives them a
103        muted palette of their own that the default class colours do not
104        use, ``#9F95C3``, ``#B2C28C``, ``#84B2C0``, ``#AD9967``,
105        ``#B6BAD4``, ``#CE9B79``, ``#7EA3D4`` and ``#7DAB88``, repeated past
106        the eighth domain. Each domain name is dark or light, whichever reads
107        on its fill.
108    label_top_n:
109        Label the n most recurrent variants. Which stems get a label is
110        resolved here and sent to the browser, so a redraw, an export and any
111        static counterpart all label the same ones. ``0`` labels none and
112        ``math.inf`` labels all, as ``Inf`` does in R.
113    show_ptms, show_domains, show_legend:
114        Toggle the surrounding tracks.
115    min_head_radius, max_head_radius:
116        Stem head radius range in pixels. Head *area* is proportional to
117        recurrence, so these bound the mapping rather than setting a size:
118        raise ``max_head_radius`` when one hotspot dwarfs the rest and you want
119        the difference to read at a glance.
120    y_label:
121        Axis title for the recurrence axis. It also names the count in the
122        tooltip: "12 samples" with the default, and "frequency: 0.3" for
123        ``y_label="frequency"``.
124    backbone_color, stem_color:
125        Hex colors for the protein backbone rectangle and the mutation stems.
126    theme:
127        Optional theme overrides forwarded to the JS renderer. Its
128        ``categorical`` palette colours the variant classes only, not the
129        domains; see ``domain_colors``. Its ``padding`` entry is the space in
130        px between the edge of the widget and the plot: one number for every
131        side, or a dict with any of the keys ``top``, ``right``, ``bottom`` and
132        ``left``, a side left out keeping the default of 10.
133        A colour given as a CSS custom property, such as
134        ``"background": "var(--bg)"``, takes the value the page gives it when
135        the plot draws. After the page changes the property, what the plot
136        drew on a canvas keeps the old colour until it draws again: resize
137        the widget or display it again.
138    height:
139        Initial widget height in CSS pixels.
140
141    Examples
142    --------
143    >>> import pandas as pd
144    >>> v = pd.DataFrame({
145    ...     "position": [175, 248, 273],
146    ...     "count": [21, 15, 13],
147    ...     "class": ["Missense"] * 3,
148    ...     "label": ["R175H", "R248Q", "R273H"],
149    ... })
150    >>> Lollipop(v, length=393, gene="TP53", uniprot="P04637")  # doctest: +SKIP
151    """
152
153    _esm = STATIC / "lollipop.js"
154
155    def __init__(
156        self,
157        data: Any,
158        *,
159        length: int,
160        gene: str | None = None,
161        uniprot: str | None = None,
162        domains: Any = None,
163        ptms: Any = None,
164        classes: list[str] | None = None,
165        class_colors: list[str] | None = None,
166        domain_colors: list[str] | None = None,
167        label_top_n: int | float = 12,
168        show_ptms: bool = True,
169        show_domains: bool = True,
170        show_legend: bool = True,
171        min_head_radius: float = 3,
172        max_head_radius: float = 11,
173        y_label: str = "samples",
174        backbone_color: str = "#E6DCC8",
175        stem_color: str = "#93a1b8",
176        theme: dict | None = None,
177        height: int = 440,
178        **kwargs: Any,
179    ) -> None:
180        pos = _column(data, "position")
181        cnt = _column(data, "count")
182        if pos is None or cnt is None:
183            raise ValueError("`data` must provide `position` and `count` columns.")
184        # numbers.Real covers numpy scalars, such as the np.int64 a pandas
185        # lookup returns.
186        if (
187            isinstance(length, bool)
188            or not isinstance(length, Real)
189            or not math.isfinite(length)
190            or length < 1
191        ):
192            raise ValueError("`length` must be a positive protein length.")
193
194        position = _to_float32(pos, "position")
195        count = _to_float32(cnt, "count")
196        if position.size == 0:
197            raise ValueError("`data` must contain at least one row.")
198        if position.size != count.size:
199            raise ValueError("`position` and `count` must be the same length.")
200        if np.any(position < 1) or np.any(position > length):
201            raise ValueError("`position` must fall within 1..length.")
202        if np.any(count < 0):
203            raise ValueError("`count` must be zero or more.")
204
205        cls_col = _column(data, "class")
206        lab_col = _column(data, "label")
207        # A missing class is None. R leaves NA out of the classes it counts
208        # and then stops on it, so Python does the same below.
209        cls = _text_or_none(cls_col) if cls_col is not None else None
210        # A missing label crosses as null, so the browser draws no text for it.
211        lab = _text_or_none(lab_col) if lab_col is not None else None
212
213        if classes is None and cls is not None:
214            # Most frequent first, ties by name in code point order, as R
215            # orders them.
216            counted = Counter(c for c in cls if c is not None)
217            classes = sorted(counted, key=lambda c: (-counted[c], c))
218        if classes is not None:
219            # A missing class given in `classes` stays None, as R keeps NA.
220            classes = _text_or_none(classes)
221            unknown = _not_in(cls or [], classes)
222            if unknown:
223                raise ValueError(
224                    "class(es) not present in `classes`: " + _na_text(unknown)
225                )
226            if class_colors is not None and len(class_colors) != len(classes):
227                raise ValueError("`class_colors` must have one entry per class.")
228
229        buffer, schema = pack_columns({"position": position, "count": count})
230
231        json_columns: dict[str, list] = {}
232        if cls is not None:
233            json_columns["class"] = cls
234        if lab is not None:
235            json_columns["label"] = lab
236
237        meta: dict[str, Any] = {"length": float(length)}
238        if gene is not None:
239            meta["gene"] = str(gene)
240        if uniprot is not None:
241            meta["uniprot"] = str(uniprot)
242        if classes is not None:
243            meta["classes"] = classes
244        if class_colors is not None:
245            meta["classColors"] = [str(c) for c in class_colors]
246        domain_rows = (
247            []
248            if domains is None
249            else _rows(domains, ("name", "start", "end"), "domains")
250        )
251        if domain_rows:
252            # A missing name crosses as null, as R sends NA, so the browser
253            # draws no name for it, where str() would write "None".
254            names = _text_or_none([d["name"] for d in domain_rows])
255            meta["domains"] = [
256                {
257                    "name": names[i],
258                    "start": float(d["start"]),
259                    "end": float(d["end"]),
260                }
261                for i, d in enumerate(domain_rows)
262            ]
263            if domain_colors is not None:
264                meta["domainColors"] = [str(c) for c in domain_colors]
265        ptm_rows = [] if ptms is None else _rows(ptms, ("position", "type"), "ptms")
266        if ptm_rows:
267            types = _text_or_none([p["type"] for p in ptm_rows])
268            meta["ptms"] = [
269                {"position": float(p["position"]), "type": types[i]}
270                for i, p in enumerate(ptm_rows)
271            ]
272
273        # Resolve the labelled stems once, here, so the renderer does not
274        # pick on its own. With label_top_n = 0 the list is sent empty: the
275        # browser labels the top 12 when it gets no list at all.
276        if lab is not None:
277            # min() takes math.inf down to the number of variants, and max()
278            # takes -math.inf up to none, before int() sees either.
279            n_top = int(max(0, min(label_top_n, count.size)))
280            top = np.argsort(-count, kind="stable")[:n_top]
281            meta["labelIndex"] = sorted(int(i) for i in top)
282
283        options: dict[str, Any] = {
284            "showPtms": show_ptms,
285            "showDomains": show_domains,
286            "showLegend": show_legend,
287            "minHeadRadius": min_head_radius,
288            "maxHeadRadius": max_head_radius,
289            "yLabel": y_label,
290            "backboneColor": backbone_color,
291            "stemColor": stem_color,
292        }
293        if theme is not None:
294            options["theme"] = theme
295
296        super().__init__(
297            buffer=buffer,
298            schema=schema,
299            data={"columns": json_columns, "meta": meta},
300            options=options,
301            _height=height,
302            **kwargs,
303        )

Variants along a protein, drawn over its domain architecture.

A backbone spanning the sequence with domain rectangles on it, mutation stems whose head area is proportional to recurrence, and an optional post-translational modification track below. Variants at one residue stack on one stem, most recurrent at the bottom, so the top of a stem is the residue's total. Hotspots inside a functional domain read very differently from truncating variants scattered across one, which is what this figure exists to show.

Stems and domains are canvas-drawn so a protein with thousands of variants stays responsive; labels, axis and legend are a vector overlay.

Parameters
  • data:: A pandas DataFrame or mapping of arrays with position (amino-acid position, 1-based) and count (recurrence, zero or more; a variant with a missing count is not drawn). Optional class and label columns drive the colour and the text labels.
  • length:: Protein length in residues.
  • gene, uniprot:: Identifiers shown on the axis title.
  • domains:: Optional domain rectangles with name, start and end: a pandas or polars DataFrame with those columns, as R takes a data frame, or a list of mappings with those keys. A domain whose name is missing (None, NaN or pandas NA) is drawn with no name.
  • ptms:: Optional modification sites with position and type, as a DataFrame or a list of mappings, as for domains.
  • classes:: Fixes the legend order and colour assignment. Defaults to the classes present, most frequent first.
  • class_colors, domain_colors:: Hex colours. None gives the classes the categorical palette of the theme. The domains never take that palette: None gives them a muted palette of their own that the default class colours do not use, #9F95C3, #B2C28C, #84B2C0, #AD9967, #B6BAD4, #CE9B79, #7EA3D4 and #7DAB88, repeated past the eighth domain. Each domain name is dark or light, whichever reads on its fill.
  • label_top_n:: Label the n most recurrent variants. Which stems get a label is resolved here and sent to the browser, so a redraw, an export and any static counterpart all label the same ones. 0 labels none and math.inf labels all, as Inf does in R.
  • show_ptms, show_domains, show_legend:: Toggle the surrounding tracks.
  • min_head_radius, max_head_radius:: Stem head radius range in pixels. Head area is proportional to recurrence, so these bound the mapping rather than setting a size: raise max_head_radius when one hotspot dwarfs the rest and you want the difference to read at a glance.
  • y_label:: Axis title for the recurrence axis. It also names the count in the tooltip: "12 samples" with the default, and "frequency: 0.3" for y_label="frequency".
  • backbone_color, stem_color:: Hex colors for the protein backbone rectangle and the mutation stems.
  • theme:: Optional theme overrides forwarded to the JS renderer. Its categorical palette colours the variant classes only, not the domains; see domain_colors. Its padding entry is the space in px between the edge of the widget and the plot: one number for every side, or a dict with any of the keys top, right, bottom and left, a side left out keeping the default of 10. A colour given as a CSS custom property, such as "background": "var(--bg)", takes the value the page gives it when the plot draws. After the page changes the property, what the plot drew on a canvas keeps the old colour until it draws again: resize the widget or display it again.
  • height:: Initial widget height in CSS pixels.
Examples
>>> import pandas as pd
>>> v = pd.DataFrame({
...     "position": [175, 248, 273],
...     "count": [21, 15, 13],
...     "class": ["Missense"] * 3,
...     "label": ["R175H", "R248Q", "R273H"],
... })
>>> Lollipop(v, length=393, gene="TP53", uniprot="P04637")  # doctest: +SKIP
Lollipop( data: Any, *, length: int, gene: str | None = None, uniprot: str | None = None, domains: Any = None, ptms: Any = None, classes: list[str] | None = None, class_colors: list[str] | None = None, domain_colors: list[str] | None = None, label_top_n: int | float = 12, show_ptms: bool = True, show_domains: bool = True, show_legend: bool = True, min_head_radius: float = 3, max_head_radius: float = 11, y_label: str = 'samples', backbone_color: str = '#E6DCC8', stem_color: str = '#93a1b8', theme: dict | None = None, height: int = 440, **kwargs: Any)
155    def __init__(
156        self,
157        data: Any,
158        *,
159        length: int,
160        gene: str | None = None,
161        uniprot: str | None = None,
162        domains: Any = None,
163        ptms: Any = None,
164        classes: list[str] | None = None,
165        class_colors: list[str] | None = None,
166        domain_colors: list[str] | None = None,
167        label_top_n: int | float = 12,
168        show_ptms: bool = True,
169        show_domains: bool = True,
170        show_legend: bool = True,
171        min_head_radius: float = 3,
172        max_head_radius: float = 11,
173        y_label: str = "samples",
174        backbone_color: str = "#E6DCC8",
175        stem_color: str = "#93a1b8",
176        theme: dict | None = None,
177        height: int = 440,
178        **kwargs: Any,
179    ) -> None:
180        pos = _column(data, "position")
181        cnt = _column(data, "count")
182        if pos is None or cnt is None:
183            raise ValueError("`data` must provide `position` and `count` columns.")
184        # numbers.Real covers numpy scalars, such as the np.int64 a pandas
185        # lookup returns.
186        if (
187            isinstance(length, bool)
188            or not isinstance(length, Real)
189            or not math.isfinite(length)
190            or length < 1
191        ):
192            raise ValueError("`length` must be a positive protein length.")
193
194        position = _to_float32(pos, "position")
195        count = _to_float32(cnt, "count")
196        if position.size == 0:
197            raise ValueError("`data` must contain at least one row.")
198        if position.size != count.size:
199            raise ValueError("`position` and `count` must be the same length.")
200        if np.any(position < 1) or np.any(position > length):
201            raise ValueError("`position` must fall within 1..length.")
202        if np.any(count < 0):
203            raise ValueError("`count` must be zero or more.")
204
205        cls_col = _column(data, "class")
206        lab_col = _column(data, "label")
207        # A missing class is None. R leaves NA out of the classes it counts
208        # and then stops on it, so Python does the same below.
209        cls = _text_or_none(cls_col) if cls_col is not None else None
210        # A missing label crosses as null, so the browser draws no text for it.
211        lab = _text_or_none(lab_col) if lab_col is not None else None
212
213        if classes is None and cls is not None:
214            # Most frequent first, ties by name in code point order, as R
215            # orders them.
216            counted = Counter(c for c in cls if c is not None)
217            classes = sorted(counted, key=lambda c: (-counted[c], c))
218        if classes is not None:
219            # A missing class given in `classes` stays None, as R keeps NA.
220            classes = _text_or_none(classes)
221            unknown = _not_in(cls or [], classes)
222            if unknown:
223                raise ValueError(
224                    "class(es) not present in `classes`: " + _na_text(unknown)
225                )
226            if class_colors is not None and len(class_colors) != len(classes):
227                raise ValueError("`class_colors` must have one entry per class.")
228
229        buffer, schema = pack_columns({"position": position, "count": count})
230
231        json_columns: dict[str, list] = {}
232        if cls is not None:
233            json_columns["class"] = cls
234        if lab is not None:
235            json_columns["label"] = lab
236
237        meta: dict[str, Any] = {"length": float(length)}
238        if gene is not None:
239            meta["gene"] = str(gene)
240        if uniprot is not None:
241            meta["uniprot"] = str(uniprot)
242        if classes is not None:
243            meta["classes"] = classes
244        if class_colors is not None:
245            meta["classColors"] = [str(c) for c in class_colors]
246        domain_rows = (
247            []
248            if domains is None
249            else _rows(domains, ("name", "start", "end"), "domains")
250        )
251        if domain_rows:
252            # A missing name crosses as null, as R sends NA, so the browser
253            # draws no name for it, where str() would write "None".
254            names = _text_or_none([d["name"] for d in domain_rows])
255            meta["domains"] = [
256                {
257                    "name": names[i],
258                    "start": float(d["start"]),
259                    "end": float(d["end"]),
260                }
261                for i, d in enumerate(domain_rows)
262            ]
263            if domain_colors is not None:
264                meta["domainColors"] = [str(c) for c in domain_colors]
265        ptm_rows = [] if ptms is None else _rows(ptms, ("position", "type"), "ptms")
266        if ptm_rows:
267            types = _text_or_none([p["type"] for p in ptm_rows])
268            meta["ptms"] = [
269                {"position": float(p["position"]), "type": types[i]}
270                for i, p in enumerate(ptm_rows)
271            ]
272
273        # Resolve the labelled stems once, here, so the renderer does not
274        # pick on its own. With label_top_n = 0 the list is sent empty: the
275        # browser labels the top 12 when it gets no list at all.
276        if lab is not None:
277            # min() takes math.inf down to the number of variants, and max()
278            # takes -math.inf up to none, before int() sees either.
279            n_top = int(max(0, min(label_top_n, count.size)))
280            top = np.argsort(-count, kind="stable")[:n_top]
281            meta["labelIndex"] = sorted(int(i) for i in top)
282
283        options: dict[str, Any] = {
284            "showPtms": show_ptms,
285            "showDomains": show_domains,
286            "showLegend": show_legend,
287            "minHeadRadius": min_head_radius,
288            "maxHeadRadius": max_head_radius,
289            "yLabel": y_label,
290            "backboneColor": backbone_color,
291            "stemColor": stem_color,
292        }
293        if theme is not None:
294            options["theme"] = theme
295
296        super().__init__(
297            buffer=buffer,
298            schema=schema,
299            data={"columns": json_columns, "meta": meta},
300            options=options,
301            _height=height,
302            **kwargs,
303        )

Public constructor

class Oncoplot(plotomics.PlotomicsWidget):
 70class Oncoplot(PlotomicsWidget):
 71    """The cohort alteration landscape.
 72
 73    A gene x sample grid of categorical alteration classes, with a per-sample
 74    burden barplot above, a per-gene frequency barplot to the right, and
 75    optional clinical annotation strips below. The grid renders on a canvas, so
 76    cohort-scale matrices (hundreds of genes by thousands of samples) stay
 77    interactive; labels and the legend are a crisp SVG overlay.
 78
 79    The component renders rows and columns in exactly the order it is given.
 80    Ordering is the caller's decision, and re-deriving it in the browser would
 81    let two renderings of the same data disagree. Pass ``genes``/``samples`` to
 82    override the default :func:`memo_sort` order.
 83
 84    Parameters
 85    ----------
 86    data:
 87        A pandas ``DataFrame`` or mapping of arrays of *altered pairs only*,
 88        with columns ``gene``, ``sample`` and ``class``. Unaltered pairs are
 89        simply absent; the full grid is reconstructed from ``genes`` and
 90        ``samples``. A row with a missing gene or sample is left out before
 91        anything is counted, as in R, so it adds no sample column, gene row
 92        or class.
 93    genes, samples:
 94        Explicit row / column order. Defaults to the memo-sorted order of the
 95        genes and samples present in the data. Given ``genes`` keep their order
 96        and the samples are sorted by it. The frequency bars divide by the
 97        number of samples shown, so pass ``samples`` to count unaltered
 98        samples of the cohort too.
 99    classes:
100        Alteration classes, fixing both legend order and colour assignment.
101        Defaults to the classes present, most frequent first, equal counts by
102        name, as in R. A missing class stops with an error, as in R, unless
103        ``classes`` holds None too: then it is a class of its own, sent as
104        null. A gene and sample with two or more different classes is drawn
105        as ``"Multi-hit"``, in dark grey, which is added to the classes when
106        it occurs.
107    class_colors:
108        One hex colour per entry of ``classes``. ``None`` uses the component's
109        categorical palette.
110    burden:
111        One value per sample for the top barplot. Defaults to the number of
112        altered genes per sample.
113    annotations:
114        Optional clinical strips, each a mapping with ``name``, ``values`` and
115        optional ``colors``. ``values`` keyed by sample (a dict, or a pandas
116        Series whose index names samples) are matched to the columns by name.
117        A plain list, or a Series indexed by row number, is read in the order
118        of ``samples``, so it needs ``samples``. The levels of a strip, in
119        legend order, are the categories of a pandas Categorical, unused ones
120        included, and otherwise the distinct values in code point order, as
121        in R. ``colors`` as a dict, or a pandas Series whose index names
122        levels, gives each level the colour under its name, whatever the
123        order, and every level needs one. A list of ``colors``, or a Series
124        whose index names no level, goes to the levels in that order.
125    show_burden, show_frequency, show_annotations, show_legend:
126        Toggle the surrounding panels.
127    empty_color:
128        Fill for a gene x sample cell with no alteration.
129    burden_color, frequency_color:
130        Hex fills for the per-sample burden bars above the grid and the per-gene
131        frequency bars to its right.
132    x_label, burden_label:
133        Axis titles for the sample axis and the burden barplot.
134    cell_gap_x, cell_gap_y:
135        Gap between cells as a fraction of cell size. Set both to ``0`` for a
136        solid block, which is what you want once a cohort is wide enough that
137        the gaps eat more pixels than the cells.
138    theme:
139        Optional theme overrides forwarded to the JS renderer. Its
140        ``padding`` entry is the space in px between the edge of the widget
141        and the plot: one number for every side, or a dict with any of the
142        keys ``top``, ``right``, ``bottom`` and ``left``, a side left out
143        keeping the default of 10.
144        Its ``categorical`` entry is an ordered palette, a list of colours
145        that go to the alteration classes in order; colours are not matched by
146        name.
147        A colour given as a CSS custom property, such as
148        ``"background": "var(--bg)"``, takes the value the page gives it when
149        the plot draws. After the page changes the property, what the plot
150        drew on a canvas keeps the old colour until it draws again: resize
151        the widget or display it again.
152    height:
153        Initial widget height in CSS pixels.
154
155    Examples
156    --------
157    >>> import pandas as pd
158    >>> alt = pd.DataFrame({
159    ...     "gene": ["TP53", "TP53", "PIK3CA", "PIK3CA", "GATA3"],
160    ...     "sample": ["S1", "S2", "S2", "S3", "S1"],
161    ...     "class": ["Missense", "Truncating", "Missense", "Amplification",
162    ...               "Missense"],
163    ... })
164    >>> Oncoplot(alt)  # doctest: +SKIP
165    """
166
167    _esm = STATIC / "oncoplot.js"
168
169    def __init__(
170        self,
171        data: Any,
172        *,
173        genes: list[str] | None = None,
174        samples: list[str] | None = None,
175        classes: list[str] | None = None,
176        class_colors: list[str] | None = None,
177        burden: Any = None,
178        annotations: list[dict[str, Any]] | None = None,
179        show_burden: bool = True,
180        show_frequency: bool = True,
181        show_annotations: bool = True,
182        show_legend: bool = True,
183        empty_color: str = "#EFE9DC",
184        burden_color: str = "#0E7175",
185        frequency_color: str = "#ED773C",
186        x_label: str = "samples",
187        burden_label: str = "alterations",
188        cell_gap_x: float = 0.12,
189        cell_gap_y: float = 0.16,
190        theme: dict | None = None,
191        height: int = 560,
192        **kwargs: Any,
193    ) -> None:
194        g_col = _column(data, "gene")
195        s_col = _column(data, "sample")
196        c_col = _column(data, "class")
197        if g_col is None or s_col is None or c_col is None:
198            raise ValueError(
199                "`data` must provide `gene`, `sample` and `class` columns."
200            )
201        # A missing gene, sample or class is None, never the text "nan".
202        alt_gene = _text_or_none(g_col)
203        alt_sample = _text_or_none(s_col)
204        alt_class = _text_or_none(c_col)
205        if not alt_gene:
206            raise ValueError("`data` must contain at least one row.")
207        # A row with no gene or no sample names no cell. It is left out before
208        # anything is counted, as in R, so it adds no column, row, class or
209        # Multi-hit.
210        rows = [
211            (g, s_, c)
212            for g, s_, c in zip(alt_gene, alt_sample, alt_class)
213            if g is not None and s_ is not None
214        ]
215        if not rows:
216            raise ValueError("`data` must contain at least one row.")
217        alt_gene = [g for g, _, _ in rows]
218        alt_sample = [s_ for _, s_, _ in rows]
219        alt_class = [c for _, _, c in rows]
220
221        if classes is None:
222            # Most frequent first, equal counts by name in code point order,
223            # as R orders them. A missing class is not counted; it stops
224            # below, as in R, unless the given classes hold None.
225            counted = Counter(c for c in alt_class if c is not None)
226            classes = sorted(counted, key=lambda c: (-counted[c], c))
227        # A missing class given in `classes` stays None, as R keeps NA.
228        classes = _text_or_none(classes)
229        unknown = _not_in(alt_class, classes)
230        if unknown:
231            raise ValueError(
232                "class(es) not present in `classes`: " + _na_text(unknown)
233            )
234        if class_colors is not None and len(class_colors) != len(classes):
235            raise ValueError("`class_colors` must have one entry per class.")
236
237        # A gene and sample with two or more different classes is one cell,
238        # drawn as "Multi-hit"; otherwise the last row would win silently.
239        by_pair: dict[tuple[str, str], set[str]] = {}
240        for g, s_, c in zip(alt_gene, alt_sample, alt_class):
241            by_pair.setdefault((g, s_), set()).add(c)
242        multi = {k for k, v in by_pair.items() if len(v) > 1}
243        if multi:
244            if MULTI_HIT not in classes:
245                classes = [*classes, MULTI_HIT]
246                if class_colors is not None:
247                    class_colors = [*class_colors, MULTI_HIT_COLOR]
248            alt_class = [
249                MULTI_HIT if (g, s_) in multi else c
250                for g, s_, c in zip(alt_gene, alt_sample, alt_class)
251            ]
252
253        present_genes = sorted(set(alt_gene))
254        present_samples = sorted(set(alt_sample))
255        genes_in = list(genes) if genes is not None else present_genes
256        samples_in = list(samples) if samples is not None else present_samples
257        if genes is None or samples is None:
258            # Given genes keep their order, and the samples follow it.
259            sorted_genes, sorted_samples = memo_sort(
260                genes_in, samples_in, alt_gene, alt_sample,
261                sort_genes=genes is None,
262            )
263            genes_in = list(genes) if genes is not None else sorted_genes
264            samples_in = list(samples) if samples is not None else sorted_samples
265
266        nrows, ncols = len(genes_in), len(samples_in)
267        if nrows == 0 or ncols == 0:
268            raise ValueError("`data` must contain at least one row.")
269
270        gi = {g: i for i, g in enumerate(genes_in)}
271        si = {s: i for i, s in enumerate(samples_in)}
272        ci = {c: i + 1 for i, c in enumerate(classes)}
273
274        # Row-major codes: 0 is unaltered, k is classes[k - 1].
275        codes = np.zeros(nrows * ncols, dtype=np.float32)
276        for g, s, c in zip(alt_gene, alt_sample, alt_class):
277            r, col = gi.get(g), si.get(s)
278            if r is None or col is None:
279                continue
280            codes[r * ncols + col] = ci[c]
281
282        grid = codes.reshape(nrows, ncols) > 0
283        freq = np.round(100.0 * grid.sum(axis=1) / ncols, 1).astype(np.float32)
284        if burden is None:
285            tmb = grid.sum(axis=0).astype(np.float32)
286        else:
287            tmb = _to_float32(burden, "burden")
288            if tmb.size != ncols:
289                raise ValueError("`burden` must have one value per sample.")
290
291        # Three different lengths on purpose: the grid is nrows * ncols, the
292        # burden is one per sample and the frequency one per gene. The schema
293        # carries each column's own length and offset, so they share a buffer.
294        buffer, schema = pack_columns(
295            {"codes": codes, "tmb": tmb, "freq": freq},
296            equal_length=False,
297            names={"tmb": "burden"},
298        )
299
300        meta: dict[str, Any] = {
301            "nrows": nrows,
302            "ncols": ncols,
303            "genes": genes_in,
304            "samples": samples_in,
305            "classes": classes,
306        }
307        if class_colors is not None:
308            meta["classColors"] = [str(c) for c in class_colors]
309        if annotations:
310            meta["annotations"] = [
311                _annotation(a, samples_in, samples is not None)
312                for a in annotations
313            ]
314
315        options: dict[str, Any] = {
316            "showBurden": show_burden,
317            "showFrequency": show_frequency,
318            "showAnnotations": show_annotations,
319            "showLegend": show_legend,
320            "emptyColor": empty_color,
321            "burdenColor": burden_color,
322            "frequencyColor": frequency_color,
323            "xLabel": x_label,
324            "burdenLabel": burden_label,
325            "cellGapX": cell_gap_x,
326            "cellGapY": cell_gap_y,
327        }
328        if theme is not None:
329            options["theme"] = theme
330
331        super().__init__(
332            buffer=buffer,
333            schema=schema,
334            data={"columns": {}, "meta": meta},
335            options=options,
336            _height=height,
337            **kwargs,
338        )

The cohort alteration landscape.

A gene x sample grid of categorical alteration classes, with a per-sample burden barplot above, a per-gene frequency barplot to the right, and optional clinical annotation strips below. The grid renders on a canvas, so cohort-scale matrices (hundreds of genes by thousands of samples) stay interactive; labels and the legend are a crisp SVG overlay.

The component renders rows and columns in exactly the order it is given. Ordering is the caller's decision, and re-deriving it in the browser would let two renderings of the same data disagree. Pass genes/samples to override the default memo_sort() order.

Parameters
  • data:: A pandas DataFrame or mapping of arrays of altered pairs only, with columns gene, sample and class. Unaltered pairs are simply absent; the full grid is reconstructed from genes and samples. A row with a missing gene or sample is left out before anything is counted, as in R, so it adds no sample column, gene row or class.
  • genes, samples:: Explicit row / column order. Defaults to the memo-sorted order of the genes and samples present in the data. Given genes keep their order and the samples are sorted by it. The frequency bars divide by the number of samples shown, so pass samples to count unaltered samples of the cohort too.
  • classes:: Alteration classes, fixing both legend order and colour assignment. Defaults to the classes present, most frequent first, equal counts by name, as in R. A missing class stops with an error, as in R, unless classes holds None too: then it is a class of its own, sent as null. A gene and sample with two or more different classes is drawn as "Multi-hit", in dark grey, which is added to the classes when it occurs.
  • class_colors:: One hex colour per entry of classes. None uses the component's categorical palette.
  • burden:: One value per sample for the top barplot. Defaults to the number of altered genes per sample.
  • annotations:: Optional clinical strips, each a mapping with name, values and optional colors. values keyed by sample (a dict, or a pandas Series whose index names samples) are matched to the columns by name. A plain list, or a Series indexed by row number, is read in the order of samples, so it needs samples. The levels of a strip, in legend order, are the categories of a pandas Categorical, unused ones included, and otherwise the distinct values in code point order, as in R. colors as a dict, or a pandas Series whose index names levels, gives each level the colour under its name, whatever the order, and every level needs one. A list of colors, or a Series whose index names no level, goes to the levels in that order.
  • show_burden, show_frequency, show_annotations, show_legend:: Toggle the surrounding panels.
  • empty_color:: Fill for a gene x sample cell with no alteration.
  • burden_color, frequency_color:: Hex fills for the per-sample burden bars above the grid and the per-gene frequency bars to its right.
  • x_label, burden_label:: Axis titles for the sample axis and the burden barplot.
  • cell_gap_x, cell_gap_y:: Gap between cells as a fraction of cell size. Set both to 0 for a solid block, which is what you want once a cohort is wide enough that the gaps eat more pixels than the cells.
  • theme:: Optional theme overrides forwarded to the JS renderer. Its padding entry is the space in px between the edge of the widget and the plot: one number for every side, or a dict with any of the keys top, right, bottom and left, a side left out keeping the default of 10. Its categorical entry is an ordered palette, a list of colours that go to the alteration classes in order; colours are not matched by name. A colour given as a CSS custom property, such as "background": "var(--bg)", takes the value the page gives it when the plot draws. After the page changes the property, what the plot drew on a canvas keeps the old colour until it draws again: resize the widget or display it again.
  • height:: Initial widget height in CSS pixels.
Examples
>>> import pandas as pd
>>> alt = pd.DataFrame({
...     "gene": ["TP53", "TP53", "PIK3CA", "PIK3CA", "GATA3"],
...     "sample": ["S1", "S2", "S2", "S3", "S1"],
...     "class": ["Missense", "Truncating", "Missense", "Amplification",
...               "Missense"],
... })
>>> Oncoplot(alt)  # doctest: +SKIP
Oncoplot( data: Any, *, genes: list[str] | None = None, samples: list[str] | None = None, classes: list[str] | None = None, class_colors: list[str] | None = None, burden: Any = None, annotations: list[dict[str, typing.Any]] | None = None, show_burden: bool = True, show_frequency: bool = True, show_annotations: bool = True, show_legend: bool = True, empty_color: str = '#EFE9DC', burden_color: str = '#0E7175', frequency_color: str = '#ED773C', x_label: str = 'samples', burden_label: str = 'alterations', cell_gap_x: float = 0.12, cell_gap_y: float = 0.16, theme: dict | None = None, height: int = 560, **kwargs: Any)
169    def __init__(
170        self,
171        data: Any,
172        *,
173        genes: list[str] | None = None,
174        samples: list[str] | None = None,
175        classes: list[str] | None = None,
176        class_colors: list[str] | None = None,
177        burden: Any = None,
178        annotations: list[dict[str, Any]] | None = None,
179        show_burden: bool = True,
180        show_frequency: bool = True,
181        show_annotations: bool = True,
182        show_legend: bool = True,
183        empty_color: str = "#EFE9DC",
184        burden_color: str = "#0E7175",
185        frequency_color: str = "#ED773C",
186        x_label: str = "samples",
187        burden_label: str = "alterations",
188        cell_gap_x: float = 0.12,
189        cell_gap_y: float = 0.16,
190        theme: dict | None = None,
191        height: int = 560,
192        **kwargs: Any,
193    ) -> None:
194        g_col = _column(data, "gene")
195        s_col = _column(data, "sample")
196        c_col = _column(data, "class")
197        if g_col is None or s_col is None or c_col is None:
198            raise ValueError(
199                "`data` must provide `gene`, `sample` and `class` columns."
200            )
201        # A missing gene, sample or class is None, never the text "nan".
202        alt_gene = _text_or_none(g_col)
203        alt_sample = _text_or_none(s_col)
204        alt_class = _text_or_none(c_col)
205        if not alt_gene:
206            raise ValueError("`data` must contain at least one row.")
207        # A row with no gene or no sample names no cell. It is left out before
208        # anything is counted, as in R, so it adds no column, row, class or
209        # Multi-hit.
210        rows = [
211            (g, s_, c)
212            for g, s_, c in zip(alt_gene, alt_sample, alt_class)
213            if g is not None and s_ is not None
214        ]
215        if not rows:
216            raise ValueError("`data` must contain at least one row.")
217        alt_gene = [g for g, _, _ in rows]
218        alt_sample = [s_ for _, s_, _ in rows]
219        alt_class = [c for _, _, c in rows]
220
221        if classes is None:
222            # Most frequent first, equal counts by name in code point order,
223            # as R orders them. A missing class is not counted; it stops
224            # below, as in R, unless the given classes hold None.
225            counted = Counter(c for c in alt_class if c is not None)
226            classes = sorted(counted, key=lambda c: (-counted[c], c))
227        # A missing class given in `classes` stays None, as R keeps NA.
228        classes = _text_or_none(classes)
229        unknown = _not_in(alt_class, classes)
230        if unknown:
231            raise ValueError(
232                "class(es) not present in `classes`: " + _na_text(unknown)
233            )
234        if class_colors is not None and len(class_colors) != len(classes):
235            raise ValueError("`class_colors` must have one entry per class.")
236
237        # A gene and sample with two or more different classes is one cell,
238        # drawn as "Multi-hit"; otherwise the last row would win silently.
239        by_pair: dict[tuple[str, str], set[str]] = {}
240        for g, s_, c in zip(alt_gene, alt_sample, alt_class):
241            by_pair.setdefault((g, s_), set()).add(c)
242        multi = {k for k, v in by_pair.items() if len(v) > 1}
243        if multi:
244            if MULTI_HIT not in classes:
245                classes = [*classes, MULTI_HIT]
246                if class_colors is not None:
247                    class_colors = [*class_colors, MULTI_HIT_COLOR]
248            alt_class = [
249                MULTI_HIT if (g, s_) in multi else c
250                for g, s_, c in zip(alt_gene, alt_sample, alt_class)
251            ]
252
253        present_genes = sorted(set(alt_gene))
254        present_samples = sorted(set(alt_sample))
255        genes_in = list(genes) if genes is not None else present_genes
256        samples_in = list(samples) if samples is not None else present_samples
257        if genes is None or samples is None:
258            # Given genes keep their order, and the samples follow it.
259            sorted_genes, sorted_samples = memo_sort(
260                genes_in, samples_in, alt_gene, alt_sample,
261                sort_genes=genes is None,
262            )
263            genes_in = list(genes) if genes is not None else sorted_genes
264            samples_in = list(samples) if samples is not None else sorted_samples
265
266        nrows, ncols = len(genes_in), len(samples_in)
267        if nrows == 0 or ncols == 0:
268            raise ValueError("`data` must contain at least one row.")
269
270        gi = {g: i for i, g in enumerate(genes_in)}
271        si = {s: i for i, s in enumerate(samples_in)}
272        ci = {c: i + 1 for i, c in enumerate(classes)}
273
274        # Row-major codes: 0 is unaltered, k is classes[k - 1].
275        codes = np.zeros(nrows * ncols, dtype=np.float32)
276        for g, s, c in zip(alt_gene, alt_sample, alt_class):
277            r, col = gi.get(g), si.get(s)
278            if r is None or col is None:
279                continue
280            codes[r * ncols + col] = ci[c]
281
282        grid = codes.reshape(nrows, ncols) > 0
283        freq = np.round(100.0 * grid.sum(axis=1) / ncols, 1).astype(np.float32)
284        if burden is None:
285            tmb = grid.sum(axis=0).astype(np.float32)
286        else:
287            tmb = _to_float32(burden, "burden")
288            if tmb.size != ncols:
289                raise ValueError("`burden` must have one value per sample.")
290
291        # Three different lengths on purpose: the grid is nrows * ncols, the
292        # burden is one per sample and the frequency one per gene. The schema
293        # carries each column's own length and offset, so they share a buffer.
294        buffer, schema = pack_columns(
295            {"codes": codes, "tmb": tmb, "freq": freq},
296            equal_length=False,
297            names={"tmb": "burden"},
298        )
299
300        meta: dict[str, Any] = {
301            "nrows": nrows,
302            "ncols": ncols,
303            "genes": genes_in,
304            "samples": samples_in,
305            "classes": classes,
306        }
307        if class_colors is not None:
308            meta["classColors"] = [str(c) for c in class_colors]
309        if annotations:
310            meta["annotations"] = [
311                _annotation(a, samples_in, samples is not None)
312                for a in annotations
313            ]
314
315        options: dict[str, Any] = {
316            "showBurden": show_burden,
317            "showFrequency": show_frequency,
318            "showAnnotations": show_annotations,
319            "showLegend": show_legend,
320            "emptyColor": empty_color,
321            "burdenColor": burden_color,
322            "frequencyColor": frequency_color,
323            "xLabel": x_label,
324            "burdenLabel": burden_label,
325            "cellGapX": cell_gap_x,
326            "cellGapY": cell_gap_y,
327        }
328        if theme is not None:
329            options["theme"] = theme
330
331        super().__init__(
332            buffer=buffer,
333            schema=schema,
334            data={"columns": {}, "meta": meta},
335            options=options,
336            _height=height,
337            **kwargs,
338        )

Public constructor

class Profile(plotomics.PlotomicsWidget):
 22class Profile(PlotomicsWidget):
 23    """An ordered bar profile whose categories collapse into coloured blocks.
 24
 25    Built for the 96-context mutational signature plot, where the bars are the
 26    trinucleotide contexts and the six blocks are the substitution classes, a
 27    layout conventional enough that readers parse it without a legend. It
 28    generalises to any ordered categorical profile that groups into runs, hence
 29    the generic name.
 30
 31    Bars are canvas-drawn, so a few thousand bins (a binned copy-number
 32    profile, a coverage track) work as well as 96 contexts.
 33
 34    Bars are drawn in the order given. For SBS96 that order is part of the
 35    convention, so the component does not sort.
 36
 37    In R this plot is ``bioprofile()``, with the alias
 38    ``profile_plotomics()``. A function named ``profile()`` would mask the
 39    ``stats::profile()`` generic, which profiles a fitted model's
 40    likelihood, when the R package is attached. Python has no such clash,
 41    so the class keeps the name ``Profile``.
 42
 43    Parameters
 44    ----------
 45    data:
 46        A pandas ``DataFrame`` or mapping of arrays with a numeric ``value``
 47        column. Optional ``group`` (category per bar, whose contiguous runs
 48        become the header blocks) and ``label`` (per-bar tick label) columns.
 49    groups:
 50        Fixes the group order and colour assignment. Defaults to order of
 51        appearance. A missing group (None or NaN) crosses as null and, as in
 52        R, is a group of its own, drawn as an unnamed block.
 53    group_colors:
 54        One hex colour per group. ``None`` uses the categorical palette.
 55    title:
 56        Optional title drawn above the header band.
 57    bar_width:
 58        Fraction of each slot the bar occupies, in ``(0, 1]``.
 59    as_fraction:
 60        ``True`` to show each value as a share of the total, in place of
 61        the raw count. Every finite value must then be 0 or more.
 62    show_header, show_bar_labels:
 63        Toggle the header band and the tick labels.
 64    y_label:
 65        Axis label.
 66    theme:
 67        Optional theme overrides forwarded to the JS renderer. Its
 68        ``padding`` entry is the space in px between the edge of the widget
 69        and the plot: one number for every side, or a dict with any of the
 70        keys ``top``, ``right``, ``bottom`` and ``left``, a side left out
 71        keeping the default of 10.
 72        Its ``categorical`` entry is an ordered palette, a list of colours
 73        that go to the groups in order; colours are not matched by name.
 74        A colour given as a CSS custom property, such as
 75        ``"background": "var(--bg)"``, takes the value the page gives it when
 76        the plot draws. After the page changes the property, what the plot
 77        drew on a canvas keeps the old colour until it draws again: resize
 78        the widget or display it again.
 79    height:
 80        Initial widget height in CSS pixels.
 81
 82    Examples
 83    --------
 84    >>> import pandas as pd
 85    >>> df = pd.DataFrame({
 86    ...     "value": [3, 5, 2, 8],
 87    ...     "group": ["C>A", "C>A", "C>T", "C>T"],
 88    ...     "label": ["ACA", "ACC", "TCA", "TCT"],
 89    ... })
 90    >>> Profile(df)  # doctest: +SKIP
 91    """
 92
 93    _esm = STATIC / "profile.js"
 94
 95    def __init__(
 96        self,
 97        data: Any,
 98        *,
 99        groups: list[str] | None = None,
100        group_colors: list[str] | None = None,
101        title: str | None = None,
102        bar_width: float = 0.62,
103        as_fraction: bool = False,
104        show_header: bool = True,
105        show_bar_labels: bool = True,
106        y_label: str = "mutations",
107        theme: dict | None = None,
108        height: int = 380,
109        **kwargs: Any,
110    ) -> None:
111        val = _column(data, "value")
112        if val is None:
113            raise ValueError("`data` must provide a `value` column.")
114        if not 0 < bar_width <= 1:
115            raise ValueError("`bar_width` must be in (0, 1].")
116        # One True or False, so the check below and the plot read it alike.
117        if not isinstance(as_fraction, (bool, np.bool_)):
118            raise ValueError(
119                "`as_fraction` must be a single true or false value."
120            )
121        as_fraction = bool(as_fraction)
122        value = _to_float32(val, "value")
123        if value.size == 0:
124            raise ValueError("`data` must contain at least one row.")
125        # Shares of a total with negative values are not defined. The sign
126        # is read before the float32 rounding, which turns a value such as
127        # -1e-50 into -0, so R and Python stop on the same values.
128        if as_fraction:
129            try:
130                exact = np.asarray(val, dtype=np.float64)
131            except (TypeError, ValueError):
132                exact = value.astype(np.float64)
133            finite = exact[np.isfinite(exact)]
134            negative = int(np.count_nonzero(finite < 0))
135            if negative:
136                raise ValueError(
137                    "`as_fraction` needs every `value` to be 0 or more; "
138                    f"found {negative} negative value(s)."
139                )
140
141        buffer, schema = pack_columns({"value": value})
142
143        json_columns: dict[str, list] = {}
144        grp_col = _column(data, "group")
145        grp = _text_or_none(grp_col) if grp_col is not None else None
146        if grp is not None:
147            json_columns["group"] = grp
148        lab_col = _column(data, "label")
149        if lab_col is not None:
150            json_columns["label"] = _text_or_none(lab_col)
151
152        meta: dict[str, Any] = {}
153        if groups is None and grp is not None:
154            seen: list[str] = []
155            for g in grp:
156                if g not in seen:
157                    seen.append(g)
158            groups = seen
159        if groups is not None:
160            groups = _text_or_none(groups)
161            unknown = _not_in(grp or [], groups)
162            if unknown:
163                raise ValueError(
164                    "group(s) not present in `groups`: " + _na_text(unknown)
165                )
166            meta["groups"] = groups
167            if group_colors is not None:
168                if len(group_colors) != len(groups):
169                    raise ValueError(
170                        "`group_colors` must have one entry per group."
171                    )
172                meta["groupColors"] = [str(c) for c in group_colors]
173        if title is not None:
174            meta["title"] = str(title)
175
176        options: dict[str, Any] = {
177            "barWidth": bar_width,
178            "asFraction": as_fraction,
179            "showHeader": show_header,
180            "showBarLabels": show_bar_labels,
181            "yLabel": y_label,
182        }
183        if theme is not None:
184            options["theme"] = theme
185
186        super().__init__(
187            buffer=buffer,
188            schema=schema,
189            data={"columns": json_columns, "meta": meta},
190            options=options,
191            _height=height,
192            **kwargs,
193        )

An ordered bar profile whose categories collapse into coloured blocks.

Built for the 96-context mutational signature plot, where the bars are the trinucleotide contexts and the six blocks are the substitution classes, a layout conventional enough that readers parse it without a legend. It generalises to any ordered categorical profile that groups into runs, hence the generic name.

Bars are canvas-drawn, so a few thousand bins (a binned copy-number profile, a coverage track) work as well as 96 contexts.

Bars are drawn in the order given. For SBS96 that order is part of the convention, so the component does not sort.

In R this plot is bioprofile(), with the alias profile_plotomics(). A function named profile() would mask the stats::profile() generic, which profiles a fitted model's likelihood, when the R package is attached. Python has no such clash, so the class keeps the name Profile.

Parameters
  • data:: A pandas DataFrame or mapping of arrays with a numeric value column. Optional group (category per bar, whose contiguous runs become the header blocks) and label (per-bar tick label) columns.
  • groups:: Fixes the group order and colour assignment. Defaults to order of appearance. A missing group (None or NaN) crosses as null and, as in R, is a group of its own, drawn as an unnamed block.
  • group_colors:: One hex colour per group. None uses the categorical palette.
  • title:: Optional title drawn above the header band.
  • bar_width:: Fraction of each slot the bar occupies, in (0, 1].
  • as_fraction:: True to show each value as a share of the total, in place of the raw count. Every finite value must then be 0 or more.
  • show_header, show_bar_labels:: Toggle the header band and the tick labels.
  • y_label:: Axis label.
  • theme:: Optional theme overrides forwarded to the JS renderer. Its padding entry is the space in px between the edge of the widget and the plot: one number for every side, or a dict with any of the keys top, right, bottom and left, a side left out keeping the default of 10. Its categorical entry is an ordered palette, a list of colours that go to the groups in order; colours are not matched by name. A colour given as a CSS custom property, such as "background": "var(--bg)", takes the value the page gives it when the plot draws. After the page changes the property, what the plot drew on a canvas keeps the old colour until it draws again: resize the widget or display it again.
  • height:: Initial widget height in CSS pixels.
Examples
>>> import pandas as pd
>>> df = pd.DataFrame({
...     "value": [3, 5, 2, 8],
...     "group": ["C>A", "C>A", "C>T", "C>T"],
...     "label": ["ACA", "ACC", "TCA", "TCT"],
... })
>>> Profile(df)  # doctest: +SKIP
Profile( data: Any, *, groups: list[str] | None = None, group_colors: list[str] | None = None, title: str | None = None, bar_width: float = 0.62, as_fraction: bool = False, show_header: bool = True, show_bar_labels: bool = True, y_label: str = 'mutations', theme: dict | None = None, height: int = 380, **kwargs: Any)
 95    def __init__(
 96        self,
 97        data: Any,
 98        *,
 99        groups: list[str] | None = None,
100        group_colors: list[str] | None = None,
101        title: str | None = None,
102        bar_width: float = 0.62,
103        as_fraction: bool = False,
104        show_header: bool = True,
105        show_bar_labels: bool = True,
106        y_label: str = "mutations",
107        theme: dict | None = None,
108        height: int = 380,
109        **kwargs: Any,
110    ) -> None:
111        val = _column(data, "value")
112        if val is None:
113            raise ValueError("`data` must provide a `value` column.")
114        if not 0 < bar_width <= 1:
115            raise ValueError("`bar_width` must be in (0, 1].")
116        # One True or False, so the check below and the plot read it alike.
117        if not isinstance(as_fraction, (bool, np.bool_)):
118            raise ValueError(
119                "`as_fraction` must be a single true or false value."
120            )
121        as_fraction = bool(as_fraction)
122        value = _to_float32(val, "value")
123        if value.size == 0:
124            raise ValueError("`data` must contain at least one row.")
125        # Shares of a total with negative values are not defined. The sign
126        # is read before the float32 rounding, which turns a value such as
127        # -1e-50 into -0, so R and Python stop on the same values.
128        if as_fraction:
129            try:
130                exact = np.asarray(val, dtype=np.float64)
131            except (TypeError, ValueError):
132                exact = value.astype(np.float64)
133            finite = exact[np.isfinite(exact)]
134            negative = int(np.count_nonzero(finite < 0))
135            if negative:
136                raise ValueError(
137                    "`as_fraction` needs every `value` to be 0 or more; "
138                    f"found {negative} negative value(s)."
139                )
140
141        buffer, schema = pack_columns({"value": value})
142
143        json_columns: dict[str, list] = {}
144        grp_col = _column(data, "group")
145        grp = _text_or_none(grp_col) if grp_col is not None else None
146        if grp is not None:
147            json_columns["group"] = grp
148        lab_col = _column(data, "label")
149        if lab_col is not None:
150            json_columns["label"] = _text_or_none(lab_col)
151
152        meta: dict[str, Any] = {}
153        if groups is None and grp is not None:
154            seen: list[str] = []
155            for g in grp:
156                if g not in seen:
157                    seen.append(g)
158            groups = seen
159        if groups is not None:
160            groups = _text_or_none(groups)
161            unknown = _not_in(grp or [], groups)
162            if unknown:
163                raise ValueError(
164                    "group(s) not present in `groups`: " + _na_text(unknown)
165                )
166            meta["groups"] = groups
167            if group_colors is not None:
168                if len(group_colors) != len(groups):
169                    raise ValueError(
170                        "`group_colors` must have one entry per group."
171                    )
172                meta["groupColors"] = [str(c) for c in group_colors]
173        if title is not None:
174            meta["title"] = str(title)
175
176        options: dict[str, Any] = {
177            "barWidth": bar_width,
178            "asFraction": as_fraction,
179            "showHeader": show_header,
180            "showBarLabels": show_bar_labels,
181            "yLabel": y_label,
182        }
183        if theme is not None:
184            options["theme"] = theme
185
186        super().__init__(
187            buffer=buffer,
188            schema=schema,
189            data={"columns": json_columns, "meta": meta},
190            options=options,
191            _height=height,
192            **kwargs,
193        )

Public constructor

class Spatial(plotomics.PlotomicsWidget):
 26class Spatial(PlotomicsWidget):
 27    """Measurements plotted at their real coordinates, over the histology.
 28
 29    This is the layout of a spatial transcriptomics experiment: capture spots
 30    on the slide, drawn on top of the H&E section they came from. For a spatial
 31    assay the tissue *is* the axis, and a cluster tracing the edge of an
 32    invasive front says something an embedding cannot.
 33
 34    The image and the spots share one "contain" fit, computed once, so
 35    histology and overlay cannot drift apart on resize, full-screen, or a
 36    high-DPI display.
 37
 38    ``color`` may be strings (categorical, discrete legend) or numbers
 39    (continuous, sequential ramp with a colourbar), which is what lets one view
 40    toggle between colouring by cluster and by a gene's expression. The
 41    legend sits in a gutter right of the image, so it never covers the tissue.
 42
 43    Scale
 44    -----
 45    Spots are drawn one at a time on a 2-D canvas, which suits a Visium-scale
 46    slide of a few thousand spots. This is **not** a renderer for Xenium or
 47    CosMx-scale single-cell output: a million cells will not stay interactive
 48    here. For that many points use :class:`~plotomics.Embedding`, which draws on
 49    the GPU via regl-scatterplot, and accept that it has no image underlay.
 50    Plotting both a histology image and a million single cells is not something
 51    this package currently does.
 52
 53    Parameters
 54    ----------
 55    data:
 56        A pandas ``DataFrame`` or mapping of arrays with numeric ``x`` and
 57        ``y`` columns giving spot centres **in image pixel coordinates**.
 58        Optional ``color`` and ``label`` columns. A missing ``color`` is drawn
 59        grey and keyed "NA", and a spot with a missing ``x`` or ``y`` is not
 60        drawn.
 61    image:
 62        URL or path of the tissue image, as the browser will fetch it.
 63    img_width, img_height:
 64        Natural size of that image in pixels.
 65    spot_diameter:
 66        Spot diameter in image pixels. ``None`` (the default) takes the
 67        median distance from a spot to its nearest neighbour, so neighbouring
 68        spots touch.
 69    levels, colors:
 70        Fix the categorical order and colours. ``None`` takes the categories
 71        of a pandas ``Categorical`` color, else the distinct values (text in
 72        natural order, "2" before "10"; numbers by value), and the theme
 73        palette. With ``levels`` given, ``colors`` needs one entry per level;
 74        without, at least one per level.
 75    color_mode:
 76        ``"auto"``, ``"categorical"`` or ``"continuous"``.
 77    colormap:
 78        Sequential ramp for continuous colouring: ``"viridis"``, ``"rdbu"``,
 79        ``"ltc"`` (an earthy teal to sand to rust sequential ramp) or
 80        ``"ltcdiv"`` (its diverging counterpart, neutral cream at the midpoint).
 81    spot_scale:
 82        Multiplier on the spot diameter; 1 draws true size.
 83    spot_opacity, image_opacity:
 84        Opacities in ``[0, 1]``. Lower the spot opacity to read the histology
 85        underneath.
 86    show_image, show_legend:
 87        Toggle the underlay and the legend.
 88    theme:
 89        Optional theme overrides forwarded to the JS renderer. Its
 90        ``padding`` entry is the space in px between the edge of the widget
 91        and the plot: one number for every side, or a dict with any of the
 92        keys ``top``, ``right``, ``bottom`` and ``left``, a side left out
 93        keeping the default of 10.
 94        Its ``categorical`` entry is an ordered palette, a list of colours
 95        that go to the categories in order; colours are not matched by name.
 96        A colour given as a CSS custom property, such as
 97        ``"background": "var(--bg)"``, takes the value the page gives it when
 98        the plot draws. After the page changes the property, what the plot
 99        drew on a canvas keeps the old colour until it draws again: resize
100        the widget or display it again.
101    height:
102        Initial widget height in CSS pixels.
103
104    Examples
105    --------
106    The image here is a drawn stand-in, built as a data URI so the example
107    needs no file. A real slide passes the path or URL of its image.
108
109    >>> import pandas as pd
110    >>> from urllib.parse import quote
111    >>> svg = (
112    ...     "<svg xmlns='http://www.w3.org/2000/svg' width='300' height='300'>"
113    ...     "<rect width='300' height='300' fill='#F4ECF0'/>"
114    ...     "<ellipse cx='150' cy='130' rx='115' ry='95' fill='#D9A9C4'/>"
115    ...     "</svg>"
116    ... )
117    >>> tissue = "data:image/svg+xml," + quote(svg, safe="")
118    >>> df = pd.DataFrame({
119    ...     "x": [100, 150, 200], "y": [120, 160, 90],
120    ...     "color": ["Cluster 1", "Cluster 2", "Cluster 1"],
121    ... })
122    >>> w = Spatial(df, image=tissue, img_width=300, img_height=300,
123    ...             spot_diameter=8)
124    >>> w  # doctest: +SKIP
125    """
126
127    _esm = STATIC / "spatial.js"
128
129    def __init__(
130        self,
131        data: Any,
132        *,
133        image: str,
134        img_width: float,
135        img_height: float,
136        spot_diameter: float | None = None,
137        levels: list[str] | None = None,
138        colors: list[str] | None = None,
139        color_mode: str = "auto",
140        colormap: Literal["viridis", "rdbu", "ltc", "ltcdiv"] = "viridis",
141        spot_scale: float = 1.0,
142        spot_opacity: float = 0.85,
143        image_opacity: float = 1.0,
144        show_image: bool = True,
145        show_legend: bool = True,
146        theme: dict | None = None,
147        height: int = 560,
148        **kwargs: Any,
149    ) -> None:
150        xc = _column(data, "x")
151        yc = _column(data, "y")
152        if xc is None or yc is None:
153            raise ValueError("`data` must provide `x` and `y` columns.")
154        if not image:
155            raise ValueError("`image` must be a URL or path the browser can fetch.")
156        if img_width <= 0 or img_height <= 0:
157            raise ValueError("`img_width` and `img_height` must be positive.")
158        diameter = None if spot_diameter is None else _spot_diameter(spot_diameter)
159        _check_choice(colormap, "colormap", ("viridis", "rdbu", "ltc", "ltcdiv"))
160        if color_mode not in ("auto", "categorical", "continuous"):
161            raise ValueError(
162                "`color_mode` must be 'auto', 'categorical' or 'continuous'."
163            )
164        levels_given = levels is not None
165        if levels_given and colors is not None and len(levels) != len(colors):
166            raise ValueError("`colors` must have one entry per level.")
167
168        x = _to_float32(xc, "x")
169        y = _to_float32(yc, "y")
170        if x.size == 0:
171            raise ValueError("`data` must contain at least one row.")
172        if x.size != y.size:
173            raise ValueError("`x` and `y` must be the same length.")
174
175        packed: dict[str, np.ndarray] = {"x": x, "y": y}
176        json_columns: dict[str, list] = {}
177
178        col = _column(data, "color")
179        if col is not None:
180            # A pandas Categorical states the level order.
181            cats = _category_levels(col)
182            if levels is None and cats is not None:
183                levels = cats
184            values = _numeric_values(col)
185            # Numeric colours ride the binary transport; categorical ones are
186            # strings and travel as JSON, a missing value as null. Numbers
187            # read as categories travel as JSON too, at full precision, so
188            # 0.1 matches the level "0.1" as it does from R.
189            if values is not None and color_mode != "categorical":
190                packed["color"] = values
191            elif values is not None:
192                exact = _numeric_values(col, np.float64)
193                json_columns["color"] = [
194                    None if np.isnan(v) else float(v) for v in exact
195                ]
196            else:
197                json_columns["color"] = _text_or_none(col)
198            if not levels_given and colors is not None and values is None:
199                present = (
200                    levels
201                    if levels is not None
202                    else {v for v in json_columns["color"] if v is not None}
203                )
204                if len(colors) < len(present):
205                    raise ValueError(
206                        "`colors` must have one entry per level: "
207                        f"{len(present)} levels, {len(colors)} colours."
208                    )
209        lab = _column(data, "label")
210        if lab is not None:
211            json_columns["label"] = _text_or_none(lab)
212
213        buffer, schema = pack_columns(packed)
214
215        meta: dict[str, Any] = {
216            "image": str(image),
217            "imgWidth": float(img_width),
218            "imgHeight": float(img_height),
219        }
220        # Left out when not given, so the browser derives it from the spacing.
221        if diameter is not None:
222            meta["spotDiameter"] = diameter
223        if levels is not None:
224            meta["levels"] = [str(v) for v in levels]
225        if colors is not None:
226            meta["colors"] = [str(c) for c in colors]
227
228        options: dict[str, Any] = {
229            "colorMode": color_mode,
230            "colormap": colormap,
231            "spotScale": spot_scale,
232            "spotOpacity": spot_opacity,
233            "imageOpacity": image_opacity,
234            "showImage": show_image,
235            "showLegend": show_legend,
236        }
237        if theme is not None:
238            options["theme"] = theme
239
240        super().__init__(
241            buffer=buffer,
242            schema=schema,
243            data={"columns": json_columns, "meta": meta},
244            options=options,
245            _height=height,
246            **kwargs,
247        )

Measurements plotted at their real coordinates, over the histology.

This is the layout of a spatial transcriptomics experiment: capture spots on the slide, drawn on top of the H&E section they came from. For a spatial assay the tissue is the axis, and a cluster tracing the edge of an invasive front says something an embedding cannot.

The image and the spots share one "contain" fit, computed once, so histology and overlay cannot drift apart on resize, full-screen, or a high-DPI display.

color may be strings (categorical, discrete legend) or numbers (continuous, sequential ramp with a colourbar), which is what lets one view toggle between colouring by cluster and by a gene's expression. The legend sits in a gutter right of the image, so it never covers the tissue.

Scale

Spots are drawn one at a time on a 2-D canvas, which suits a Visium-scale slide of a few thousand spots. This is not a renderer for Xenium or CosMx-scale single-cell output: a million cells will not stay interactive here. For that many points use ~plotomics.Embedding, which draws on the GPU via regl-scatterplot, and accept that it has no image underlay. Plotting both a histology image and a million single cells is not something this package currently does.

Parameters
  • data:: A pandas DataFrame or mapping of arrays with numeric x and y columns giving spot centres in image pixel coordinates. Optional color and label columns. A missing color is drawn grey and keyed "NA", and a spot with a missing x or y is not drawn.
  • image:: URL or path of the tissue image, as the browser will fetch it.
  • img_width, img_height:: Natural size of that image in pixels.
  • spot_diameter:: Spot diameter in image pixels. None (the default) takes the median distance from a spot to its nearest neighbour, so neighbouring spots touch.
  • levels, colors:: Fix the categorical order and colours. None takes the categories of a pandas Categorical color, else the distinct values (text in natural order, "2" before "10"; numbers by value), and the theme palette. With levels given, colors needs one entry per level; without, at least one per level.
  • color_mode:: "auto", "categorical" or "continuous".
  • colormap:: Sequential ramp for continuous colouring: "viridis", "rdbu", "ltc" (an earthy teal to sand to rust sequential ramp) or "ltcdiv" (its diverging counterpart, neutral cream at the midpoint).
  • spot_scale:: Multiplier on the spot diameter; 1 draws true size.
  • spot_opacity, image_opacity:: Opacities in [0, 1]. Lower the spot opacity to read the histology underneath.
  • show_image, show_legend:: Toggle the underlay and the legend.
  • theme:: Optional theme overrides forwarded to the JS renderer. Its padding entry is the space in px between the edge of the widget and the plot: one number for every side, or a dict with any of the keys top, right, bottom and left, a side left out keeping the default of 10. Its categorical entry is an ordered palette, a list of colours that go to the categories in order; colours are not matched by name. A colour given as a CSS custom property, such as "background": "var(--bg)", takes the value the page gives it when the plot draws. After the page changes the property, what the plot drew on a canvas keeps the old colour until it draws again: resize the widget or display it again.
  • height:: Initial widget height in CSS pixels.
Examples

The image here is a drawn stand-in, built as a data URI so the example needs no file. A real slide passes the path or URL of its image.

>>> import pandas as pd
>>> from urllib.parse import quote
>>> svg = (
...     "<svg xmlns='http://www.w3.org/2000/svg' width='300' height='300'>"
...     "<rect width='300' height='300' fill='#F4ECF0'/>"
...     "<ellipse cx='150' cy='130' rx='115' ry='95' fill='#D9A9C4'/>"
...     "</svg>"
... )
>>> tissue = "data:image/svg+xml," + quote(svg, safe="")
>>> df = pd.DataFrame({
...     "x": [100, 150, 200], "y": [120, 160, 90],
...     "color": ["Cluster 1", "Cluster 2", "Cluster 1"],
... })
>>> w = Spatial(df, image=tissue, img_width=300, img_height=300,
...             spot_diameter=8)
>>> w  # doctest: +SKIP
Spatial( data: Any, *, image: str, img_width: float, img_height: float, spot_diameter: float | None = None, levels: list[str] | None = None, colors: list[str] | None = None, color_mode: str = 'auto', colormap: Literal['viridis', 'rdbu', 'ltc', 'ltcdiv'] = 'viridis', spot_scale: float = 1.0, spot_opacity: float = 0.85, image_opacity: float = 1.0, show_image: bool = True, show_legend: bool = True, theme: dict | None = None, height: int = 560, **kwargs: Any)
129    def __init__(
130        self,
131        data: Any,
132        *,
133        image: str,
134        img_width: float,
135        img_height: float,
136        spot_diameter: float | None = None,
137        levels: list[str] | None = None,
138        colors: list[str] | None = None,
139        color_mode: str = "auto",
140        colormap: Literal["viridis", "rdbu", "ltc", "ltcdiv"] = "viridis",
141        spot_scale: float = 1.0,
142        spot_opacity: float = 0.85,
143        image_opacity: float = 1.0,
144        show_image: bool = True,
145        show_legend: bool = True,
146        theme: dict | None = None,
147        height: int = 560,
148        **kwargs: Any,
149    ) -> None:
150        xc = _column(data, "x")
151        yc = _column(data, "y")
152        if xc is None or yc is None:
153            raise ValueError("`data` must provide `x` and `y` columns.")
154        if not image:
155            raise ValueError("`image` must be a URL or path the browser can fetch.")
156        if img_width <= 0 or img_height <= 0:
157            raise ValueError("`img_width` and `img_height` must be positive.")
158        diameter = None if spot_diameter is None else _spot_diameter(spot_diameter)
159        _check_choice(colormap, "colormap", ("viridis", "rdbu", "ltc", "ltcdiv"))
160        if color_mode not in ("auto", "categorical", "continuous"):
161            raise ValueError(
162                "`color_mode` must be 'auto', 'categorical' or 'continuous'."
163            )
164        levels_given = levels is not None
165        if levels_given and colors is not None and len(levels) != len(colors):
166            raise ValueError("`colors` must have one entry per level.")
167
168        x = _to_float32(xc, "x")
169        y = _to_float32(yc, "y")
170        if x.size == 0:
171            raise ValueError("`data` must contain at least one row.")
172        if x.size != y.size:
173            raise ValueError("`x` and `y` must be the same length.")
174
175        packed: dict[str, np.ndarray] = {"x": x, "y": y}
176        json_columns: dict[str, list] = {}
177
178        col = _column(data, "color")
179        if col is not None:
180            # A pandas Categorical states the level order.
181            cats = _category_levels(col)
182            if levels is None and cats is not None:
183                levels = cats
184            values = _numeric_values(col)
185            # Numeric colours ride the binary transport; categorical ones are
186            # strings and travel as JSON, a missing value as null. Numbers
187            # read as categories travel as JSON too, at full precision, so
188            # 0.1 matches the level "0.1" as it does from R.
189            if values is not None and color_mode != "categorical":
190                packed["color"] = values
191            elif values is not None:
192                exact = _numeric_values(col, np.float64)
193                json_columns["color"] = [
194                    None if np.isnan(v) else float(v) for v in exact
195                ]
196            else:
197                json_columns["color"] = _text_or_none(col)
198            if not levels_given and colors is not None and values is None:
199                present = (
200                    levels
201                    if levels is not None
202                    else {v for v in json_columns["color"] if v is not None}
203                )
204                if len(colors) < len(present):
205                    raise ValueError(
206                        "`colors` must have one entry per level: "
207                        f"{len(present)} levels, {len(colors)} colours."
208                    )
209        lab = _column(data, "label")
210        if lab is not None:
211            json_columns["label"] = _text_or_none(lab)
212
213        buffer, schema = pack_columns(packed)
214
215        meta: dict[str, Any] = {
216            "image": str(image),
217            "imgWidth": float(img_width),
218            "imgHeight": float(img_height),
219        }
220        # Left out when not given, so the browser derives it from the spacing.
221        if diameter is not None:
222            meta["spotDiameter"] = diameter
223        if levels is not None:
224            meta["levels"] = [str(v) for v in levels]
225        if colors is not None:
226            meta["colors"] = [str(c) for c in colors]
227
228        options: dict[str, Any] = {
229            "colorMode": color_mode,
230            "colormap": colormap,
231            "spotScale": spot_scale,
232            "spotOpacity": spot_opacity,
233            "imageOpacity": image_opacity,
234            "showImage": show_image,
235            "showLegend": show_legend,
236        }
237        if theme is not None:
238            options["theme"] = theme
239
240        super().__init__(
241            buffer=buffer,
242            schema=schema,
243            data={"columns": json_columns, "meta": meta},
244            options=options,
245            _height=height,
246            **kwargs,
247        )

Public constructor

class Treemap(plotomics.PlotomicsWidget):
 24class Treemap(PlotomicsWidget):
 25    """Hierarchical treemap of gene-set / pathway composition.
 26
 27    The hierarchy is built from a flat edge list with ``d3-hierarchy``
 28    (``stratify`` + ``treemap``); tiles are rendered on a canvas so thousands of
 29    leaves stay interactive, while tile labels and a drill-down breadcrumb are
 30    drawn as a crisp SVG overlay.
 31
 32    Parameters
 33    ----------
 34    data:
 35        A pandas ``DataFrame`` or a mapping of arrays describing a tree as an
 36        edge list. Required columns: ``id`` (unique node id) and ``parent``
 37        (id of the parent; the root's parent is ``None``/``NaN``/``""``). A
 38        numeric ``value`` column supplies leaf weights. A group's size is the
 39        sum of its leaves; a value given on an internal node is ignored.
 40        Without a ``value`` column every leaf weighs 1, so tiles show leaf
 41        counts. An optional ``label`` column supplies display names. Top-level
 42        groups are named in a header strip when their tile has room.
 43    tile:
 44        Tiling algorithm, ``"squarify"`` (golden-ratio rectangles) or
 45        ``"binary"`` (balanced binary partition).
 46    padding_inner:
 47        Padding between sibling tiles, in pixels.
 48    color_by:
 49        Color leaves by ``"parent"`` (top-level ancestor, categorical) or by
 50        ``"value"`` (a ramp).
 51    colormap:
 52        Ramp used when ``color_by="value"``: ``"viridis"``, ``"rdbu"``,
 53        ``"ltc"`` (an earthy teal to sand to rust sequential ramp) or
 54        ``"ltcdiv"`` (its diverging counterpart, neutral cream at the
 55        midpoint). The ramp runs from the smallest leaf value in view to
 56        the largest, so a diverging ramp has its midpoint halfway between
 57        the two.
 58    label_min_size:
 59        Minimum tile side (px) before a label is drawn, at the default font
 60        size. It grows with ``theme["fontSize"]``.
 61    theme:
 62        Optional theme overrides forwarded to the JS renderer. Its
 63        ``padding`` entry is the space in px between the edge of the widget
 64        and the plot: one number for every side, or a dict with any of the
 65        keys ``top``, ``right``, ``bottom`` and ``left``, a side left out
 66        keeping the default of 10.
 67        Its ``categorical`` entry is an ordered palette, a list of colours
 68        that go to the top-level branches in order; colours are not matched by
 69        name.
 70        A colour given as a CSS custom property, such as
 71        ``"background": "var(--bg)"``, takes the value the page gives it when
 72        the plot draws. After the page changes the property, what the plot
 73        drew on a canvas keeps the old colour until it draws again: resize
 74        the widget or display it again.
 75    height:
 76        Initial widget height in CSS pixels.
 77
 78    Examples
 79    --------
 80    >>> import pandas as pd
 81    >>> df = pd.DataFrame({
 82    ...     "id": ["root", "P1", "P2", "g1", "g2", "g3"],
 83    ...     "parent": [None, "root", "root", "P1", "P1", "P2"],
 84    ...     "value": [0, 0, 0, 3, 5, 2],
 85    ...     "label": ["All", "Pathway 1", "Pathway 2", "Gene 1", "Gene 2", "Gene 3"],
 86    ... })
 87    >>> Treemap(df)  # doctest: +SKIP
 88    """
 89
 90    _esm = STATIC / "treemap.js"
 91
 92    def __init__(
 93        self,
 94        data: Any,
 95        *,
 96        tile: str = "squarify",
 97        padding_inner: float = 1.0,
 98        color_by: str = "parent",
 99        colormap: Literal["viridis", "rdbu", "ltc", "ltcdiv"] = "viridis",
100        label_min_size: float = 32.0,
101        theme: dict | None = None,
102        height: int = 480,
103        **kwargs: Any,
104    ) -> None:
105        ids = _column(data, "id")
106        parents = _column(data, "parent")
107        if ids is None or parents is None:
108            raise ValueError("`data` must provide `id` and `parent` columns.")
109        if tile not in ("squarify", "binary"):
110            raise ValueError("`tile` must be 'squarify' or 'binary'.")
111        if color_by not in ("parent", "value"):
112            raise ValueError("`color_by` must be 'parent' or 'value'.")
113        _check_choice(colormap, "colormap", _COLORMAPS)
114
115        # String columns travel as JSON. Missing / NaN parents mark the root and
116        # are normalized to empty strings (the JS side treats "" / "NA" as root).
117        id_list = [_id_str(v) for v in ids]
118        id_set_all = set(id_list)
119        parent_list = [_parent_str(v, id_set_all) for v in parents]
120        n = len(id_list)
121
122        # Structural integrity: exactly one root, unique ids, no orphan parents.
123        if n == 0:
124            raise ValueError("`data` must contain at least one row.")
125        dupes = sorted({i for i, c in Counter(id_list).items() if c > 1})
126        if dupes:
127            raise ValueError("duplicate node id(s): " + ", ".join(dupes))
128        roots = [i for i, p in zip(id_list, parent_list) if p == ""]
129        if len(roots) != 1:
130            raise ValueError("treemap requires exactly one root")
131        id_set = set(id_list)
132        missing = sorted({p for p in parent_list if p != "" and p not in id_set})
133        if missing:
134            raise ValueError("parent(s) not found among ids: " + ", ".join(missing))
135        # Every node must reach the root by following parents; a self-parent or a
136        # cycle disjoint from the root passes the checks above but crashes
137        # d3.stratify in the browser.
138        parent_of = dict(zip(id_list, parent_list))
139        good: set[str] = set()
140        for start in id_list:
141            seen: set[str] = set()
142            cur = start
143            while cur != "" and cur not in good:
144                if cur in seen:
145                    raise ValueError(
146                        f"treemap has a cycle in the parent chain (at '{cur}')"
147                    )
148                seen.add(cur)
149                cur = parent_of.get(cur, "")
150            good |= seen
151
152        json_columns: dict[str, list] = {"id": id_list, "parent": parent_list}
153
154        # Numeric leaf weights travel via the binary transport (float32 for
155        # consistency with every other component's packed columns).
156        # Without a value column the browser weighs every leaf as 1.
157        value = _column(data, "value")
158        if value is not None:
159            value_arr = _to_float32(value, "value")
160            if value_arr.size != n:
161                raise ValueError(
162                    f"`value` has {value_arr.size} entries; expected {n}."
163                )
164            buffer, schema = pack_columns({"value": value_arr})
165        else:
166            buffer, schema = b"", {"columns": []}
167
168        meta: dict[str, Any] = {}
169        label = _column(data, "label")
170        if label is not None:
171            # A missing label crosses as null, as R sends an NA, and the
172            # browser shows the id in its place.
173            meta["labels"] = _text_or_none(label)
174
175        options: dict[str, Any] = {
176            "tile": tile,
177            "paddingInner": padding_inner,
178            "colorBy": color_by,
179            "colormap": colormap,
180            "labelMinSize": label_min_size,
181        }
182        if theme is not None:
183            options["theme"] = theme
184
185        super().__init__(
186            buffer=buffer,
187            schema=schema,
188            data={"columns": json_columns, "meta": meta},
189            options=options,
190            _height=height,
191            **kwargs,
192        )

Hierarchical treemap of gene-set / pathway composition.

The hierarchy is built from a flat edge list with d3-hierarchy (stratify + treemap); tiles are rendered on a canvas so thousands of leaves stay interactive, while tile labels and a drill-down breadcrumb are drawn as a crisp SVG overlay.

Parameters
  • data:: A pandas DataFrame or a mapping of arrays describing a tree as an edge list. Required columns: id (unique node id) and parent (id of the parent; the root's parent is None/NaN/""). A numeric value column supplies leaf weights. A group's size is the sum of its leaves; a value given on an internal node is ignored. Without a value column every leaf weighs 1, so tiles show leaf counts. An optional label column supplies display names. Top-level groups are named in a header strip when their tile has room.
  • tile:: Tiling algorithm, "squarify" (golden-ratio rectangles) or "binary" (balanced binary partition).
  • padding_inner:: Padding between sibling tiles, in pixels.
  • color_by:: Color leaves by "parent" (top-level ancestor, categorical) or by "value" (a ramp).
  • colormap:: Ramp used when color_by="value": "viridis", "rdbu", "ltc" (an earthy teal to sand to rust sequential ramp) or "ltcdiv" (its diverging counterpart, neutral cream at the midpoint). The ramp runs from the smallest leaf value in view to the largest, so a diverging ramp has its midpoint halfway between the two.
  • label_min_size:: Minimum tile side (px) before a label is drawn, at the default font size. It grows with theme["fontSize"].
  • theme:: Optional theme overrides forwarded to the JS renderer. Its padding entry is the space in px between the edge of the widget and the plot: one number for every side, or a dict with any of the keys top, right, bottom and left, a side left out keeping the default of 10. Its categorical entry is an ordered palette, a list of colours that go to the top-level branches in order; colours are not matched by name. A colour given as a CSS custom property, such as "background": "var(--bg)", takes the value the page gives it when the plot draws. After the page changes the property, what the plot drew on a canvas keeps the old colour until it draws again: resize the widget or display it again.
  • height:: Initial widget height in CSS pixels.
Examples
>>> import pandas as pd
>>> df = pd.DataFrame({
...     "id": ["root", "P1", "P2", "g1", "g2", "g3"],
...     "parent": [None, "root", "root", "P1", "P1", "P2"],
...     "value": [0, 0, 0, 3, 5, 2],
...     "label": ["All", "Pathway 1", "Pathway 2", "Gene 1", "Gene 2", "Gene 3"],
... })
>>> Treemap(df)  # doctest: +SKIP
Treemap( data: Any, *, tile: str = 'squarify', padding_inner: float = 1.0, color_by: str = 'parent', colormap: Literal['viridis', 'rdbu', 'ltc', 'ltcdiv'] = 'viridis', label_min_size: float = 32.0, theme: dict | None = None, height: int = 480, **kwargs: Any)
 92    def __init__(
 93        self,
 94        data: Any,
 95        *,
 96        tile: str = "squarify",
 97        padding_inner: float = 1.0,
 98        color_by: str = "parent",
 99        colormap: Literal["viridis", "rdbu", "ltc", "ltcdiv"] = "viridis",
100        label_min_size: float = 32.0,
101        theme: dict | None = None,
102        height: int = 480,
103        **kwargs: Any,
104    ) -> None:
105        ids = _column(data, "id")
106        parents = _column(data, "parent")
107        if ids is None or parents is None:
108            raise ValueError("`data` must provide `id` and `parent` columns.")
109        if tile not in ("squarify", "binary"):
110            raise ValueError("`tile` must be 'squarify' or 'binary'.")
111        if color_by not in ("parent", "value"):
112            raise ValueError("`color_by` must be 'parent' or 'value'.")
113        _check_choice(colormap, "colormap", _COLORMAPS)
114
115        # String columns travel as JSON. Missing / NaN parents mark the root and
116        # are normalized to empty strings (the JS side treats "" / "NA" as root).
117        id_list = [_id_str(v) for v in ids]
118        id_set_all = set(id_list)
119        parent_list = [_parent_str(v, id_set_all) for v in parents]
120        n = len(id_list)
121
122        # Structural integrity: exactly one root, unique ids, no orphan parents.
123        if n == 0:
124            raise ValueError("`data` must contain at least one row.")
125        dupes = sorted({i for i, c in Counter(id_list).items() if c > 1})
126        if dupes:
127            raise ValueError("duplicate node id(s): " + ", ".join(dupes))
128        roots = [i for i, p in zip(id_list, parent_list) if p == ""]
129        if len(roots) != 1:
130            raise ValueError("treemap requires exactly one root")
131        id_set = set(id_list)
132        missing = sorted({p for p in parent_list if p != "" and p not in id_set})
133        if missing:
134            raise ValueError("parent(s) not found among ids: " + ", ".join(missing))
135        # Every node must reach the root by following parents; a self-parent or a
136        # cycle disjoint from the root passes the checks above but crashes
137        # d3.stratify in the browser.
138        parent_of = dict(zip(id_list, parent_list))
139        good: set[str] = set()
140        for start in id_list:
141            seen: set[str] = set()
142            cur = start
143            while cur != "" and cur not in good:
144                if cur in seen:
145                    raise ValueError(
146                        f"treemap has a cycle in the parent chain (at '{cur}')"
147                    )
148                seen.add(cur)
149                cur = parent_of.get(cur, "")
150            good |= seen
151
152        json_columns: dict[str, list] = {"id": id_list, "parent": parent_list}
153
154        # Numeric leaf weights travel via the binary transport (float32 for
155        # consistency with every other component's packed columns).
156        # Without a value column the browser weighs every leaf as 1.
157        value = _column(data, "value")
158        if value is not None:
159            value_arr = _to_float32(value, "value")
160            if value_arr.size != n:
161                raise ValueError(
162                    f"`value` has {value_arr.size} entries; expected {n}."
163                )
164            buffer, schema = pack_columns({"value": value_arr})
165        else:
166            buffer, schema = b"", {"columns": []}
167
168        meta: dict[str, Any] = {}
169        label = _column(data, "label")
170        if label is not None:
171            # A missing label crosses as null, as R sends an NA, and the
172            # browser shows the id in its place.
173            meta["labels"] = _text_or_none(label)
174
175        options: dict[str, Any] = {
176            "tile": tile,
177            "paddingInner": padding_inner,
178            "colorBy": color_by,
179            "colormap": colormap,
180            "labelMinSize": label_min_size,
181        }
182        if theme is not None:
183            options["theme"] = theme
184
185        super().__init__(
186            buffer=buffer,
187            schema=schema,
188            data={"columns": json_columns, "meta": meta},
189            options=options,
190            _height=height,
191            **kwargs,
192        )

Public constructor

class Upset(plotomics.PlotomicsWidget):
 21class Upset(PlotomicsWidget):
 22    """Set intersections as a bar chart over a membership matrix.
 23
 24    Venn diagrams stop being readable at four sets and stop being drawable at
 25    five. UpSet replaces the areas with an explicit matrix, so it scales to
 26    dozens of sets and stays exact.
 27
 28    Intersections are **exclusive**: a column counts the elements in precisely
 29    that combination of sets and no others. That is what makes the columns sum
 30    to the union rather than double-counting, and it is why a small ``A + B``
 31    bar next to large ``A`` and ``B`` bars is evidence of mutual exclusivity
 32    rather than an artefact.
 33
 34    Parameters
 35    ----------
 36    data:
 37        A pandas ``DataFrame`` or mapping with a numeric ``size`` column, one
 38        row per intersection, in the order to draw them.
 39    sets:
 40        Set names, top to bottom.
 41    membership:
 42        Boolean or 0/1 array shaped (intersections, sets).
 43    set_sizes:
 44        Per-set totals for the left-hand bars.
 45    total:
 46        Universe size, shown in the corner.
 47    bar_fraction:
 48        Fraction of the height given to the intersection bars.
 49    show_set_sizes:
 50        Draw the per-set total bars.
 51    dot_radius:
 52        Matrix dot radius in pixels.
 53    bar_color, empty_dot_color:
 54        Fills for the bars and filled dots, and for dots not in the
 55        intersection. ``None`` uses the theme.
 56    y_label:
 57        Axis label for the intersection bars.
 58    theme:
 59        Optional theme overrides forwarded to the JS renderer. Its
 60        ``padding`` entry is the space in px between the edge of the widget
 61        and the plot: one number for every side, or a dict with any of the
 62        keys ``top``, ``right``, ``bottom`` and ``left``, a side left out
 63        keeping the default of 10.
 64        A colour given as a CSS custom property, such as
 65        ``"background": "var(--bg)"``, takes the value the page gives it when
 66        the plot draws. After the page changes the property, what the plot
 67        drew on a canvas keeps the old colour until it draws again: resize
 68        the widget or display it again.
 69    height:
 70        Initial widget height in CSS pixels.
 71
 72    Examples
 73    --------
 74    >>> import numpy as np, pandas as pd
 75    >>> m = np.array([[1, 0], [0, 1], [1, 1]])
 76    >>> Upset(pd.DataFrame({"size": [40, 25, 12]}), sets=["A", "B"],
 77    ...       membership=m)  # doctest: +SKIP
 78    """
 79
 80    _esm = STATIC / "upset.js"
 81
 82    def __init__(
 83        self,
 84        data: Any,
 85        *,
 86        sets: list[str],
 87        membership: Any,
 88        set_sizes: Any = None,
 89        total: float | None = None,
 90        bar_fraction: float = 0.55,
 91        show_set_sizes: bool = True,
 92        dot_radius: float = 5.0,
 93        bar_color: str | None = None,
 94        empty_dot_color: str | None = None,
 95        y_label: str = "intersection size",
 96        theme: dict | None = None,
 97        height: int = 520,
 98        **kwargs: Any,
 99    ) -> None:
100        col = _column(data, "size")
101        if col is None:
102            raise ValueError("`data` must provide a `size` column.")
103        # float64, so a count past 2**24 arrives exact, as it does from R.
104        size = _to_float64(col, "size")
105        if size.size == 0:
106            raise ValueError("`data` must contain at least one row.")
107
108        names = [str(s) for s in sets]
109        if not names:
110            raise ValueError("`sets` must name at least one set.")
111
112        m = np.atleast_2d(np.asarray(membership)).astype(int)
113        if m.shape[0] != size.size:
114            raise ValueError("`membership` must have one row per intersection.")
115        if m.shape[1] != len(names):
116            raise ValueError("`membership` must have one column per set.")
117
118        buffer, schema = pack_columns({"size": size})
119
120        meta: dict[str, Any] = {
121            "sets": names,
122            # Row-major: the component indexes it as intersection * nSets + set.
123            "membership": [int(v) for v in m.reshape(-1)],
124        }
125        if set_sizes is not None:
126            sizes = [float(v) for v in np.asarray(set_sizes).reshape(-1)]
127            if len(sizes) != len(names):
128                raise ValueError("`set_sizes` must have one entry per set.")
129            meta["setSizes"] = sizes
130        if total is not None:
131            meta["total"] = float(total)
132
133        options: dict[str, Any] = {
134            "barFraction": bar_fraction,
135            "showSetSizes": show_set_sizes,
136            "dotRadius": dot_radius,
137            "yLabel": y_label,
138        }
139        if bar_color is not None:
140            options["barColor"] = str(bar_color)
141        if empty_dot_color is not None:
142            options["emptyDotColor"] = str(empty_dot_color)
143        if theme is not None:
144            options["theme"] = theme
145
146        super().__init__(
147            buffer=buffer,
148            schema=schema,
149            data={"columns": {}, "meta": meta},
150            options=options,
151            _height=height,
152            **kwargs,
153        )

Set intersections as a bar chart over a membership matrix.

Venn diagrams stop being readable at four sets and stop being drawable at five. UpSet replaces the areas with an explicit matrix, so it scales to dozens of sets and stays exact.

Intersections are exclusive: a column counts the elements in precisely that combination of sets and no others. That is what makes the columns sum to the union rather than double-counting, and it is why a small A + B bar next to large A and B bars is evidence of mutual exclusivity rather than an artefact.

Parameters
  • data:: A pandas DataFrame or mapping with a numeric size column, one row per intersection, in the order to draw them.
  • sets:: Set names, top to bottom.
  • membership:: Boolean or 0/1 array shaped (intersections, sets).
  • set_sizes:: Per-set totals for the left-hand bars.
  • total:: Universe size, shown in the corner.
  • bar_fraction:: Fraction of the height given to the intersection bars.
  • show_set_sizes:: Draw the per-set total bars.
  • dot_radius:: Matrix dot radius in pixels.
  • bar_color, empty_dot_color:: Fills for the bars and filled dots, and for dots not in the intersection. None uses the theme.
  • y_label:: Axis label for the intersection bars.
  • theme:: Optional theme overrides forwarded to the JS renderer. Its padding entry is the space in px between the edge of the widget and the plot: one number for every side, or a dict with any of the keys top, right, bottom and left, a side left out keeping the default of 10. A colour given as a CSS custom property, such as "background": "var(--bg)", takes the value the page gives it when the plot draws. After the page changes the property, what the plot drew on a canvas keeps the old colour until it draws again: resize the widget or display it again.
  • height:: Initial widget height in CSS pixels.
Examples
>>> import numpy as np, pandas as pd
>>> m = np.array([[1, 0], [0, 1], [1, 1]])
>>> Upset(pd.DataFrame({"size": [40, 25, 12]}), sets=["A", "B"],
...       membership=m)  # doctest: +SKIP
Upset( data: Any, *, sets: list[str], membership: Any, set_sizes: Any = None, total: float | None = None, bar_fraction: float = 0.55, show_set_sizes: bool = True, dot_radius: float = 5.0, bar_color: str | None = None, empty_dot_color: str | None = None, y_label: str = 'intersection size', theme: dict | None = None, height: int = 520, **kwargs: Any)
 82    def __init__(
 83        self,
 84        data: Any,
 85        *,
 86        sets: list[str],
 87        membership: Any,
 88        set_sizes: Any = None,
 89        total: float | None = None,
 90        bar_fraction: float = 0.55,
 91        show_set_sizes: bool = True,
 92        dot_radius: float = 5.0,
 93        bar_color: str | None = None,
 94        empty_dot_color: str | None = None,
 95        y_label: str = "intersection size",
 96        theme: dict | None = None,
 97        height: int = 520,
 98        **kwargs: Any,
 99    ) -> None:
100        col = _column(data, "size")
101        if col is None:
102            raise ValueError("`data` must provide a `size` column.")
103        # float64, so a count past 2**24 arrives exact, as it does from R.
104        size = _to_float64(col, "size")
105        if size.size == 0:
106            raise ValueError("`data` must contain at least one row.")
107
108        names = [str(s) for s in sets]
109        if not names:
110            raise ValueError("`sets` must name at least one set.")
111
112        m = np.atleast_2d(np.asarray(membership)).astype(int)
113        if m.shape[0] != size.size:
114            raise ValueError("`membership` must have one row per intersection.")
115        if m.shape[1] != len(names):
116            raise ValueError("`membership` must have one column per set.")
117
118        buffer, schema = pack_columns({"size": size})
119
120        meta: dict[str, Any] = {
121            "sets": names,
122            # Row-major: the component indexes it as intersection * nSets + set.
123            "membership": [int(v) for v in m.reshape(-1)],
124        }
125        if set_sizes is not None:
126            sizes = [float(v) for v in np.asarray(set_sizes).reshape(-1)]
127            if len(sizes) != len(names):
128                raise ValueError("`set_sizes` must have one entry per set.")
129            meta["setSizes"] = sizes
130        if total is not None:
131            meta["total"] = float(total)
132
133        options: dict[str, Any] = {
134            "barFraction": bar_fraction,
135            "showSetSizes": show_set_sizes,
136            "dotRadius": dot_radius,
137            "yLabel": y_label,
138        }
139        if bar_color is not None:
140            options["barColor"] = str(bar_color)
141        if empty_dot_color is not None:
142            options["emptyDotColor"] = str(empty_dot_color)
143        if theme is not None:
144            options["theme"] = theme
145
146        super().__init__(
147            buffer=buffer,
148            schema=schema,
149            data={"columns": {}, "meta": meta},
150            options=options,
151            _height=height,
152            **kwargs,
153        )

Public constructor

class Violin(plotomics.PlotomicsWidget):
 27class Violin(PlotomicsWidget):
 28    """One row per feature, one violin per group.
 29
 30    A box plot hides bimodality, which in single-cell data is usually the whole
 31    story: a gene expressed in half a cluster and silent in the other half has
 32    the same median as one expressed weakly everywhere. The violin shows the
 33    shape, and stacking rows on a shared x lets a marker panel be read down the
 34    page.
 35
 36    The widget draws densities, it does not estimate them. Each violin arrives
 37    as a vector of density values on a shared grid, because kernel bandwidth
 38    choice changes what the figure claims and belongs with the data. It also
 39    keeps the payload proportional to the grid rather than to the cell count.
 40
 41    Parameters
 42    ----------
 43    data:
 44        A pandas ``DataFrame`` or mapping with ``feature`` and ``group`` key
 45        columns, one row per violin, in the order to draw them.
 46    grid:
 47        The shared evaluation grid, ascending.
 48    grids:
 49        Optional array shaped (features, len(grid)) giving each feature its own
 50        y range. Without it every row shares ``grid``, which lets one highly
 51        expressed feature compress the rest into flat lines.
 52    density:
 53        Array shaped (violins, len(grid)) of density values.
 54        :func:`violin_density` computes them from raw values the way R
 55        does.
 56    median:
 57        Optional per-violin median, drawn as a tick.
 58    features, groups:
 59        Fix the row and column order. A pandas Categorical supplies it from its
 60        categories.
 61    group_colors:
 62        One hex colour per group. ``None`` uses the categorical palette.
 63    violin_width:
 64        Fraction of a cell's width the widest violin fills, in (0, 1]. When
 65        rows are short next to the column width (many features, or a short
 66        or wide widget), ``violin_aspect`` can make it fill less.
 67    violin_aspect:
 68        The largest width of the widest violin, as a multiple of its row
 69        height. A violin much wider than its row is tall reads as a flat
 70        band. The cap never makes a violin narrower than four times the
 71        label text size (44 px at the default font size), so with many
 72        features the violins stay visible; nor wider than ``violin_width``
 73        of its cell. ``None`` turns the cap off.
 74    scale_per_violin:
 75        Scale each violin to its own maximum rather than the row's. Per-row is
 76        the default so groups stay comparable within a feature.
 77    show_median, show_feature_labels:
 78        Toggle the median tick and the row labels.
 79    show_value_axis:
 80        Draw each row's value axis on the right, with the highest value of
 81        its grid and, on rows tall enough for two labels, the lowest.
 82    theme:
 83        Optional theme overrides forwarded to the JS renderer. Its
 84        ``padding`` entry is the space in px between the edge of the widget
 85        and the plot: one number for every side, or a dict with any of the
 86        keys ``top``, ``right``, ``bottom`` and ``left``, a side left out
 87        keeping the default of 10.
 88        Its ``categorical`` entry is an ordered palette, a list of colours
 89        that go to the groups in order; colours are not matched by name.
 90        A colour given as a CSS custom property, such as
 91        ``"background": "var(--bg)"``, takes the value the page gives it when
 92        the plot draws. After the page changes the property, what the plot
 93        drew on a canvas keeps the old colour until it draws again: resize
 94        the widget or display it again.
 95    height:
 96        Initial widget height in CSS pixels.
 97    """
 98
 99    _esm = STATIC / "violin.js"
100
101    def __init__(
102        self,
103        data: Any,
104        *,
105        grid: Any,
106        density: Any,
107        grids: Any = None,
108        median: Any = None,
109        features: list[str] | None = None,
110        groups: list[str] | None = None,
111        group_colors: list[str] | None = None,
112        violin_width: float = 0.85,
113        violin_aspect: float | None = 0.8,
114        scale_per_violin: bool = False,
115        show_median: bool = True,
116        show_feature_labels: bool = True,
117        show_value_axis: bool = True,
118        theme: dict | None = None,
119        height: int = 560,
120        **kwargs: Any,
121    ) -> None:
122        feature = _column(data, "feature")
123        group = _column(data, "group")
124        missing = [
125            name for name, col in (("feature", feature), ("group", group))
126            if col is None
127        ]
128        if missing:
129            raise ValueError("`data` is missing column(s): " + ", ".join(missing))
130        if not 0 < violin_width <= 1:
131            raise ValueError("`violin_width` must be in (0, 1].")
132        violin_aspect = _violin_aspect(violin_aspect)
133
134        g = _to_float32(grid, "grid")
135        if g.size == 0:
136            raise ValueError("`grid` must contain at least one value.")
137        if np.any(np.diff(g) < 0):
138            raise ValueError("`grid` must be ascending.")
139
140        dm = np.atleast_2d(np.asarray(density, dtype=np.float32))
141        n_violins = len(list(feature))
142        if dm.shape[0] != n_violins:
143            raise ValueError("`density` must have one row per violin.")
144        if dm.shape[1] != g.size:
145            raise ValueError("`density` must have one column per `grid` entry.")
146
147        buffer, schema = pack_columns({"grid": g})
148        # A missing feature or group crosses as null, as R sends an NA.
149        json_columns: dict[str, list] = {
150            "feature": _text_or_none(feature),
151            "group": _text_or_none(group),
152        }
153
154        if features is None:
155            features = _category_levels(feature)
156        if groups is None:
157            groups = _category_levels(group)
158
159        meta: dict[str, Any] = {
160            # Sent as float64, as R sends it: the axis labels the grid ends,
161            # and float32 would turn 99.95 into 99.9499969.
162            "grid": [float(v) for v in np.asarray(grid, dtype=np.float64).reshape(-1)],
163            # Row-major: the component indexes it as violin * gridLen + k.
164            "density": [float(v) for v in dm.reshape(-1)],
165        }
166        for key, order, col in (
167            ("features", features, json_columns["feature"]),
168            ("groups", groups, json_columns["group"]),
169        ):
170            if order is None:
171                continue
172            order = _text_or_none(order)
173            unknown = _not_in(col, order)
174            if unknown:
175                raise ValueError(
176                    f"value(s) not present in `{key}`: " + _na_text(unknown[:5])
177                )
178            meta[key] = order
179        if group_colors is not None:
180            # Without `groups`, colours follow the groups in order of first
181            # appearance, the order the browser uses; R does the same.
182            if groups is None:
183                order = list(dict.fromkeys(json_columns["group"]))
184                meta["groups"] = order
185            else:
186                order = meta["groups"]
187            if len(group_colors) != len(order):
188                raise ValueError("`group_colors` must have one entry per group.")
189            meta["groupColors"] = [str(c) for c in group_colors]
190        if grids is not None:
191            gm = np.atleast_2d(np.asarray(grids, dtype=np.float64))
192            if gm.shape[1] != g.size:
193                raise ValueError("`grids` must have one column per `grid` entry.")
194            n_feat = len(features) if features is not None else len(set(json_columns["feature"]))
195            if gm.shape[0] != n_feat:
196                raise ValueError("`grids` must have one row per feature.")
197            meta["grids"] = [float(v) for v in gm.reshape(-1)]
198        if median is not None:
199            med = np.asarray(median).reshape(-1)
200            if med.size != n_violins:
201                raise ValueError("`median` must have one entry per violin.")
202            # A violin with no values has no median: null, as R sends NA.
203            meta["median"] = [
204                float(v) if v is not None and np.isfinite(float(v)) else None
205                for v in med
206            ]
207
208        options: dict[str, Any] = {
209            "violinWidth": violin_width,
210            "violinAspect": violin_aspect,
211            "scalePerViolin": scale_per_violin,
212            "showMedian": show_median,
213            "showFeatureLabels": show_feature_labels,
214            "showValueAxis": show_value_axis,
215        }
216        if theme is not None:
217            options["theme"] = theme
218
219        super().__init__(
220            buffer=buffer,
221            schema=schema,
222            data={"columns": json_columns, "meta": meta},
223            options=options,
224            _height=height,
225            **kwargs,
226        )

One row per feature, one violin per group.

A box plot hides bimodality, which in single-cell data is usually the whole story: a gene expressed in half a cluster and silent in the other half has the same median as one expressed weakly everywhere. The violin shows the shape, and stacking rows on a shared x lets a marker panel be read down the page.

The widget draws densities, it does not estimate them. Each violin arrives as a vector of density values on a shared grid, because kernel bandwidth choice changes what the figure claims and belongs with the data. It also keeps the payload proportional to the grid rather than to the cell count.

Parameters
  • data:: A pandas DataFrame or mapping with feature and group key columns, one row per violin, in the order to draw them.
  • grid:: The shared evaluation grid, ascending.
  • grids:: Optional array shaped (features, len(grid)) giving each feature its own y range. Without it every row shares grid, which lets one highly expressed feature compress the rest into flat lines.
  • density:: Array shaped (violins, len(grid)) of density values. violin_density() computes them from raw values the way R does.
  • median:: Optional per-violin median, drawn as a tick.
  • features, groups:: Fix the row and column order. A pandas Categorical supplies it from its categories.
  • group_colors:: One hex colour per group. None uses the categorical palette.
  • violin_width:: Fraction of a cell's width the widest violin fills, in (0, 1]. When rows are short next to the column width (many features, or a short or wide widget), violin_aspect can make it fill less.
  • violin_aspect:: The largest width of the widest violin, as a multiple of its row height. A violin much wider than its row is tall reads as a flat band. The cap never makes a violin narrower than four times the label text size (44 px at the default font size), so with many features the violins stay visible; nor wider than violin_width of its cell. None turns the cap off.
  • scale_per_violin:: Scale each violin to its own maximum rather than the row's. Per-row is the default so groups stay comparable within a feature.
  • show_median, show_feature_labels:: Toggle the median tick and the row labels.
  • show_value_axis:: Draw each row's value axis on the right, with the highest value of its grid and, on rows tall enough for two labels, the lowest.
  • theme:: Optional theme overrides forwarded to the JS renderer. Its padding entry is the space in px between the edge of the widget and the plot: one number for every side, or a dict with any of the keys top, right, bottom and left, a side left out keeping the default of 10. Its categorical entry is an ordered palette, a list of colours that go to the groups in order; colours are not matched by name. A colour given as a CSS custom property, such as "background": "var(--bg)", takes the value the page gives it when the plot draws. After the page changes the property, what the plot drew on a canvas keeps the old colour until it draws again: resize the widget or display it again.
  • height:: Initial widget height in CSS pixels.
Violin( data: Any, *, grid: Any, density: Any, grids: Any = None, median: Any = None, features: list[str] | None = None, groups: list[str] | None = None, group_colors: list[str] | None = None, violin_width: float = 0.85, violin_aspect: float | None = 0.8, scale_per_violin: bool = False, show_median: bool = True, show_feature_labels: bool = True, show_value_axis: bool = True, theme: dict | None = None, height: int = 560, **kwargs: Any)
101    def __init__(
102        self,
103        data: Any,
104        *,
105        grid: Any,
106        density: Any,
107        grids: Any = None,
108        median: Any = None,
109        features: list[str] | None = None,
110        groups: list[str] | None = None,
111        group_colors: list[str] | None = None,
112        violin_width: float = 0.85,
113        violin_aspect: float | None = 0.8,
114        scale_per_violin: bool = False,
115        show_median: bool = True,
116        show_feature_labels: bool = True,
117        show_value_axis: bool = True,
118        theme: dict | None = None,
119        height: int = 560,
120        **kwargs: Any,
121    ) -> None:
122        feature = _column(data, "feature")
123        group = _column(data, "group")
124        missing = [
125            name for name, col in (("feature", feature), ("group", group))
126            if col is None
127        ]
128        if missing:
129            raise ValueError("`data` is missing column(s): " + ", ".join(missing))
130        if not 0 < violin_width <= 1:
131            raise ValueError("`violin_width` must be in (0, 1].")
132        violin_aspect = _violin_aspect(violin_aspect)
133
134        g = _to_float32(grid, "grid")
135        if g.size == 0:
136            raise ValueError("`grid` must contain at least one value.")
137        if np.any(np.diff(g) < 0):
138            raise ValueError("`grid` must be ascending.")
139
140        dm = np.atleast_2d(np.asarray(density, dtype=np.float32))
141        n_violins = len(list(feature))
142        if dm.shape[0] != n_violins:
143            raise ValueError("`density` must have one row per violin.")
144        if dm.shape[1] != g.size:
145            raise ValueError("`density` must have one column per `grid` entry.")
146
147        buffer, schema = pack_columns({"grid": g})
148        # A missing feature or group crosses as null, as R sends an NA.
149        json_columns: dict[str, list] = {
150            "feature": _text_or_none(feature),
151            "group": _text_or_none(group),
152        }
153
154        if features is None:
155            features = _category_levels(feature)
156        if groups is None:
157            groups = _category_levels(group)
158
159        meta: dict[str, Any] = {
160            # Sent as float64, as R sends it: the axis labels the grid ends,
161            # and float32 would turn 99.95 into 99.9499969.
162            "grid": [float(v) for v in np.asarray(grid, dtype=np.float64).reshape(-1)],
163            # Row-major: the component indexes it as violin * gridLen + k.
164            "density": [float(v) for v in dm.reshape(-1)],
165        }
166        for key, order, col in (
167            ("features", features, json_columns["feature"]),
168            ("groups", groups, json_columns["group"]),
169        ):
170            if order is None:
171                continue
172            order = _text_or_none(order)
173            unknown = _not_in(col, order)
174            if unknown:
175                raise ValueError(
176                    f"value(s) not present in `{key}`: " + _na_text(unknown[:5])
177                )
178            meta[key] = order
179        if group_colors is not None:
180            # Without `groups`, colours follow the groups in order of first
181            # appearance, the order the browser uses; R does the same.
182            if groups is None:
183                order = list(dict.fromkeys(json_columns["group"]))
184                meta["groups"] = order
185            else:
186                order = meta["groups"]
187            if len(group_colors) != len(order):
188                raise ValueError("`group_colors` must have one entry per group.")
189            meta["groupColors"] = [str(c) for c in group_colors]
190        if grids is not None:
191            gm = np.atleast_2d(np.asarray(grids, dtype=np.float64))
192            if gm.shape[1] != g.size:
193                raise ValueError("`grids` must have one column per `grid` entry.")
194            n_feat = len(features) if features is not None else len(set(json_columns["feature"]))
195            if gm.shape[0] != n_feat:
196                raise ValueError("`grids` must have one row per feature.")
197            meta["grids"] = [float(v) for v in gm.reshape(-1)]
198        if median is not None:
199            med = np.asarray(median).reshape(-1)
200            if med.size != n_violins:
201                raise ValueError("`median` must have one entry per violin.")
202            # A violin with no values has no median: null, as R sends NA.
203            meta["median"] = [
204                float(v) if v is not None and np.isfinite(float(v)) else None
205                for v in med
206            ]
207
208        options: dict[str, Any] = {
209            "violinWidth": violin_width,
210            "violinAspect": violin_aspect,
211            "scalePerViolin": scale_per_violin,
212            "showMedian": show_median,
213            "showFeatureLabels": show_feature_labels,
214            "showValueAxis": show_value_axis,
215        }
216        if theme is not None:
217            options["theme"] = theme
218
219        super().__init__(
220            buffer=buffer,
221            schema=schema,
222            data={"columns": json_columns, "meta": meta},
223            options=options,
224            _height=height,
225            **kwargs,
226        )

Public constructor

def upset_intersections(m: Any, max_n: int | None = None) -> dict[str, typing.Any]:
156def upset_intersections(m: Any, max_n: int | None = None) -> dict[str, Any]:
157    """Exclusive set intersections from a membership table.
158
159    Counts the elements that belong to exactly each combination of sets seen
160    in ``m``, as R's ``upset_intersections()`` does, in the same order: the
161    largest intersection first, and equal sizes by their membership read as
162    0/1 text, so ``"01"`` (only the second set) comes before ``"10"``.
163    Elements in no set are left out, since they have no column to sit in.
164
165    Parameters
166    ----------
167    m:
168        A pandas ``DataFrame`` or mapping of arrays: one row per element and
169        one boolean or 0/1 column per set, named by the set. A missing value
170        counts as not in the set.
171    max_n:
172        Keep only the ``max_n`` largest intersections. ``None`` keeps all.
173
174    Returns
175    -------
176    dict
177        ``size`` (integer array), ``membership`` (boolean array shaped
178        (intersections, sets)), ``sets`` (the set names), ``set_sizes``
179        (elements per set) and ``total`` (number of elements), ready for
180        :class:`Upset`.
181
182    Examples
183    --------
184    >>> import pandas as pd
185    >>> m = pd.DataFrame({"A": [True, True, False], "B": [True, False, True]})
186    >>> r = upset_intersections(m)
187    >>> r["size"].tolist(), r["membership"].tolist()
188    ([1, 1, 1], [[False, True], [True, False], [True, True]])
189    >>> Upset({"size": r["size"]}, sets=r["sets"],  # doctest: +SKIP
190    ...       membership=r["membership"], set_sizes=r["set_sizes"],
191    ...       total=r["total"])
192    """
193    if isinstance(m, np.ndarray):
194        raise ValueError(
195            "`m` must have column names naming the sets: pass a pandas "
196            "DataFrame or a dict of columns, not a plain numpy array."
197        )
198    _reject_lazy(m)
199    names = getattr(m, "column_names", None)
200    if names is None:
201        names = m.keys() if isinstance(m, Mapping) else getattr(m, "columns", None)
202    names = list(names) if names is not None else []
203    if not names:
204        raise ValueError("`m` must have column names naming the sets.")
205
206    cols = [_in_set(m[name], str(name)) for name in names]
207    sizes = {c.size for c in cols}
208    if len(sizes) > 1:
209        raise ValueError("every column of `m` must have the same length.")
210    mat = np.column_stack(cols)
211    sets = [str(name) for name in names]
212    total = int(mat.shape[0])
213    set_sizes = mat.sum(axis=0).astype(np.int64)
214
215    hit = mat[mat.any(axis=1)]
216    if hit.shape[0] == 0:
217        return {
218            "size": np.zeros(0, dtype=np.int64),
219            "membership": np.zeros((0, len(sets)), dtype=bool),
220            "sets": sets,
221            "set_sizes": set_sizes,
222            "total": total,
223        }
224    # Distinct rows in 0/1 text order (False before True), then the largest
225    # first; the stable sort keeps that text order for equal sizes, as R's
226    # sort(table(keys), decreasing = TRUE) does.
227    patterns, counts = np.unique(hit, axis=0, return_counts=True)
228    order = np.argsort(-counts, kind="stable")
229    if max_n is not None:
230        order = order[:max_n]
231    return {
232        "size": counts[order].astype(np.int64),
233        "membership": patterns[order].astype(bool),
234        "sets": sets,
235        "set_sizes": set_sizes,
236        "total": total,
237    }

Exclusive set intersections from a membership table.

Counts the elements that belong to exactly each combination of sets seen in m, as R's upset_intersections() does, in the same order: the largest intersection first, and equal sizes by their membership read as 0/1 text, so "01" (only the second set) comes before "10". Elements in no set are left out, since they have no column to sit in.

Parameters
  • m:: A pandas DataFrame or mapping of arrays: one row per element and one boolean or 0/1 column per set, named by the set. A missing value counts as not in the set.
  • max_n:: Keep only the max_n largest intersections. None keeps all.
Returns
  • dict: size (integer array), membership (boolean array shaped (intersections, sets)), sets (the set names), set_sizes (elements per set) and total (number of elements), ready for Upset.
Examples
>>> import pandas as pd
>>> m = pd.DataFrame({"A": [True, True, False], "B": [True, False, True]})
>>> r = upset_intersections(m)
>>> r["size"].tolist(), r["membership"].tolist()
([1, 1, 1], [[False, True], [True, False], [True, True]])
>>> Upset({"size": r["size"]}, sets=r["sets"],  # doctest: +SKIP
...       membership=r["membership"], set_sizes=r["set_sizes"],
...       total=r["total"])
def violin_density( values: Mapping[str, typing.Any], n: int = 64, adjust: float = 1.0) -> dict[str, typing.Any]:
229def violin_density(
230    values: Mapping[str, Any], n: int = 64, adjust: float = 1.0
231) -> dict[str, Any]:
232    """Kernel densities for :class:`Violin`, on one grid shared by all violins.
233
234    The same computation as R's ``violin_density()``, so the same values give
235    the same violins in R and Python: a Gaussian kernel with R's default
236    bandwidth (``bw.nrd0``) times ``adjust``, evaluated the way R's
237    ``density()`` evaluates it. Uses numpy only.
238
239    Parameters
240    ----------
241    values:
242        A mapping from a name to an array of numbers, one entry per violin, in
243        the order to draw them. A name ``"feature|group"`` gives the feature
244        and the group; a name with no ``|`` is a feature with the group ``""``.
245        Values that are not finite are left out.
246    n:
247        Number of grid points.
248    adjust:
249        Bandwidth multiplier, as in R's ``density()``.
250
251    Returns
252    -------
253    dict
254        ``data`` (``feature`` and ``group`` lists), ``grid`` (``n`` points
255        from the smallest to the largest value), ``density`` (violins x
256        ``n``; a violin with fewer than two distinct values is all zeros)
257        and ``median`` (NaN for a violin with no values), ready for
258        :class:`Violin`.
259
260    Examples
261    --------
262    >>> import numpy as np
263    >>> rng = np.random.default_rng(1)
264    >>> d = violin_density({"CD3D|T": rng.normal(2, 1, 200),
265    ...                     "CD3D|B": rng.normal(0, 1, 200)})
266    >>> d["density"].shape
267    (2, 64)
268    >>> Violin(d["data"], grid=d["grid"], density=d["density"],
269    ...        median=d["median"])  # doctest: +SKIP
270    """
271    if not isinstance(values, Mapping) or len(values) == 0:
272        raise ValueError("`values` must be a named list of numeric vectors.")
273    n = int(n)
274    if n < 2:
275        raise ValueError("`n` must be at least 2.")
276    names = [str(k) for k in values.keys()]
277    vecs = []
278    for v in values.values():
279        arr = np.asarray(v, dtype=np.float64).reshape(-1)
280        vecs.append(arr[np.isfinite(arr)])
281    every = np.concatenate(vecs)
282    if every.size == 0:
283        raise ValueError("`values` contains no finite numbers.")
284    lo = float(every.min())
285    hi = float(every.max())
286    if lo == hi:
287        hi = lo + 1.0
288    grid = np.linspace(lo, hi, n)
289
290    density = np.zeros((len(vecs), n))
291    median = np.full(len(vecs), np.nan)
292    for i, v in enumerate(vecs):
293        if v.size:
294            median[i] = float(np.median(v))
295        if v.size >= 2 and np.unique(v).size >= 2:
296            density[i] = _r_density(v, lo, hi, n, adjust)
297
298    parts = [name.split("|") for name in names]
299    return {
300        "data": {
301            "feature": [p[0] for p in parts],
302            "group": [p[1] if len(p) > 1 else "" for p in parts],
303        },
304        "grid": grid,
305        "density": density,
306        "median": median,
307    }

Kernel densities for Violin, on one grid shared by all violins.

The same computation as R's violin_density(), so the same values give the same violins in R and Python: a Gaussian kernel with R's default bandwidth (bw.nrd0) times adjust, evaluated the way R's density() evaluates it. Uses numpy only.

Parameters
  • values:: A mapping from a name to an array of numbers, one entry per violin, in the order to draw them. A name "feature|group" gives the feature and the group; a name with no | is a feature with the group "". Values that are not finite are left out.
  • n:: Number of grid points.
  • adjust:: Bandwidth multiplier, as in R's density().
Returns
  • dict: data (feature and group lists), grid (n points from the smallest to the largest value), density (violins x n; a violin with fewer than two distinct values is all zeros) and median (NaN for a violin with no values), ready for Violin.
Examples
>>> import numpy as np
>>> rng = np.random.default_rng(1)
>>> d = violin_density({"CD3D|T": rng.normal(2, 1, 200),
...                     "CD3D|B": rng.normal(0, 1, 200)})
>>> d["density"].shape
(2, 64)
>>> Violin(d["data"], grid=d["grid"], density=d["density"],
...        median=d["median"])  # doctest: +SKIP
class Volcano(plotomics.PlotomicsWidget):
 23class Volcano(PlotomicsWidget):
 24    """GPU-accelerated volcano plot for differential-expression results.
 25
 26    Parameters
 27    ----------
 28    data:
 29        A pandas ``DataFrame`` or a mapping of arrays. Must provide numeric
 30        ``x`` (log2 fold change) and ``y`` (``-log10`` p-value); an optional
 31        ``label`` column supplies gene names for tooltips and top-hit labels.
 32        A ``y`` of ``inf`` (p = 0) is drawn just above the highest finite value
 33        and the p-value threshold, and counts as significant. Rows with NaN in
 34        ``x`` or ``y``, or a ``y`` of ``-inf``, are not drawn, with a warning
 35        that counts them; R gives the same warning.
 36    fc_threshold:
 37        Absolute log2 fold-change cutoff for calling a hit.
 38    p_threshold:
 39        P-value cutoff (applied on the ``-log10`` scale).
 40    point_size, opacity:
 41        Point radius (px) and opacity in ``[0, 1]``.
 42    x_label, y_label:
 43        Axis titles.
 44    label_top_n:
 45        Number of top up- and down-regulated genes to label. ``math.inf``
 46        labels every up- and down-regulated gene, as in ``Lollipop`` and as
 47        ``Inf`` does in R; ``0`` labels none, and so does NaN, as ``NA`` does
 48        in R.
 49    colors:
 50        Optional mapping overriding the up / down / not-significant point colors
 51        (keys ``"up"``, ``"down"``, ``"ns"``). ``None`` keeps the defaults.
 52    show_threshold_lines:
 53        Draw the fold-change / p-value threshold guide lines. The y axis then
 54        always reaches the p-value guide.
 55    bounded_view:
 56        Keep pan and zoom inside the data: zooming out stops at the view
 57        that shows all of it, a pan stops at its edges, and zooming in stops
 58        at 1/10,000 of its range. ``False`` lets the view move freely.
 59        Either way a double-click, or the reset button in the top right
 60        corner of the plot, goes back to the view of all the data.
 61    theme:
 62        Optional theme overrides forwarded to the JS renderer. Its
 63        ``padding`` entry is the space in px between the edge of the widget
 64        and the plot: one number for every side, or a dict with any of the
 65        keys ``top``, ``right``, ``bottom`` and ``left``, a side left out
 66        keeping the default of 10.
 67        A colour given as a CSS custom property, such as
 68        ``"background": "var(--bg)"``, takes the value the page gives it when
 69        the plot draws. After the page changes the property, what the plot
 70        drew on a canvas keeps the old colour until it draws again: resize
 71        the widget or display it again.
 72    height:
 73        Initial widget height in CSS pixels.
 74
 75    Examples
 76    --------
 77    >>> import numpy as np, pandas as pd
 78    >>> n = 200_000
 79    >>> df = pd.DataFrame({
 80    ...     "x": np.random.randn(n),
 81    ...     "y": np.abs(np.random.randn(n)) * 3,
 82    ...     "label": [f"GENE{i}" for i in range(n)],
 83    ... })
 84    >>> Volcano(df)  # doctest: +SKIP
 85    """
 86
 87    _esm = STATIC / "volcano.js"
 88
 89    def __init__(
 90        self,
 91        data: Any,
 92        *,
 93        fc_threshold: float = 1.0,
 94        p_threshold: float = 0.05,
 95        point_size: float = 3.0,
 96        opacity: float = 0.8,
 97        x_label: str = "log2 fold change",
 98        y_label: str = "-log10 p-value",
 99        label_top_n: int = 10,
100        colors: dict | None = None,
101        show_threshold_lines: bool = True,
102        bounded_view: bool = True,
103        theme: dict | None = None,
104        height: int = 480,
105        **kwargs: Any,
106    ) -> None:
107        x = _column(data, "x")
108        y = _column(data, "y")
109        if x is None or y is None:
110            raise ValueError("`data` must provide `x` and `y` columns.")
111
112        bounded_view = _require_flag(bounded_view, "bounded_view")
113        x_arr = _to_float32(x, "x")
114        y_arr = _to_float32(y, "y")
115        if x_arr.size == 0:
116            raise ValueError("`data` must contain at least one row.")
117
118        # p = 0 gives a y of inf, which is drawn at the top. The warning
119        # counts only the rows the browser leaves out, in the words R uses.
120        y_gone = int(np.count_nonzero(np.isnan(y_arr) | (y_arr == -np.inf)))
121        if y_gone:
122            warnings.warn(
123                f"`y` has {y_gone} value(s) that are missing (NA or NaN) or "
124                "-Inf; those rows are not drawn.",
125                stacklevel=2,
126            )
127        buffer, schema = pack_columns({"x": x_arr, "y": y_arr}, quiet=("y",))
128        # JSON has no inf or NaN. Inf labels are asked for as one per gene,
129        # and NaN goes as null, as R sends NA, which labels none.
130        top_n: Any = label_top_n
131        if isinstance(label_top_n, (float, np.floating)):
132            if math.isnan(label_top_n):
133                top_n = None
134            elif math.isinf(label_top_n):
135                top_n = int(x_arr.size) if label_top_n > 0 else 0
136
137        json_columns: dict[str, list] = {}
138        label = _column(data, "label")
139        if label is not None:
140            # A missing symbol crosses as null, as from R, never as "nan".
141            json_columns["label"] = _text_or_none(label)
142
143        options: dict[str, Any] = {
144            "fcThreshold": fc_threshold,
145            "pThreshold": p_threshold,
146            "pointSize": point_size,
147            "opacity": opacity,
148            "xLabel": x_label,
149            "yLabel": y_label,
150            "labelTopN": top_n,
151            "showThresholdLines": show_threshold_lines,
152            "boundedView": bounded_view,
153        }
154        if colors is not None:
155            options["colors"] = dict(colors)
156        if theme is not None:
157            options["theme"] = theme
158
159        super().__init__(
160            buffer=buffer,
161            schema=schema,
162            data={"columns": json_columns, "meta": {}},
163            options=options,
164            _height=height,
165            **kwargs,
166        )

GPU-accelerated volcano plot for differential-expression results.

Parameters
  • data:: A pandas DataFrame or a mapping of arrays. Must provide numeric x (log2 fold change) and y (-log10 p-value); an optional label column supplies gene names for tooltips and top-hit labels. A y of inf (p = 0) is drawn just above the highest finite value and the p-value threshold, and counts as significant. Rows with NaN in x or y, or a y of -inf, are not drawn, with a warning that counts them; R gives the same warning.
  • fc_threshold:: Absolute log2 fold-change cutoff for calling a hit.
  • p_threshold:: P-value cutoff (applied on the -log10 scale).
  • point_size, opacity:: Point radius (px) and opacity in [0, 1].
  • x_label, y_label:: Axis titles.
  • label_top_n:: Number of top up- and down-regulated genes to label. math.inf labels every up- and down-regulated gene, as in Lollipop and as Inf does in R; 0 labels none, and so does NaN, as NA does in R.
  • colors:: Optional mapping overriding the up / down / not-significant point colors (keys "up", "down", "ns"). None keeps the defaults.
  • show_threshold_lines:: Draw the fold-change / p-value threshold guide lines. The y axis then always reaches the p-value guide.
  • bounded_view:: Keep pan and zoom inside the data: zooming out stops at the view that shows all of it, a pan stops at its edges, and zooming in stops at 1/10,000 of its range. False lets the view move freely. Either way a double-click, or the reset button in the top right corner of the plot, goes back to the view of all the data.
  • theme:: Optional theme overrides forwarded to the JS renderer. Its padding entry is the space in px between the edge of the widget and the plot: one number for every side, or a dict with any of the keys top, right, bottom and left, a side left out keeping the default of 10. A colour given as a CSS custom property, such as "background": "var(--bg)", takes the value the page gives it when the plot draws. After the page changes the property, what the plot drew on a canvas keeps the old colour until it draws again: resize the widget or display it again.
  • height:: Initial widget height in CSS pixels.
Examples
>>> import numpy as np, pandas as pd
>>> n = 200_000
>>> df = pd.DataFrame({
...     "x": np.random.randn(n),
...     "y": np.abs(np.random.randn(n)) * 3,
...     "label": [f"GENE{i}" for i in range(n)],
... })
>>> Volcano(df)  # doctest: +SKIP
Volcano( data: Any, *, fc_threshold: float = 1.0, p_threshold: float = 0.05, point_size: float = 3.0, opacity: float = 0.8, x_label: str = 'log2 fold change', y_label: str = '-log10 p-value', label_top_n: int = 10, colors: dict | None = None, show_threshold_lines: bool = True, bounded_view: bool = True, theme: dict | None = None, height: int = 480, **kwargs: Any)
 89    def __init__(
 90        self,
 91        data: Any,
 92        *,
 93        fc_threshold: float = 1.0,
 94        p_threshold: float = 0.05,
 95        point_size: float = 3.0,
 96        opacity: float = 0.8,
 97        x_label: str = "log2 fold change",
 98        y_label: str = "-log10 p-value",
 99        label_top_n: int = 10,
100        colors: dict | None = None,
101        show_threshold_lines: bool = True,
102        bounded_view: bool = True,
103        theme: dict | None = None,
104        height: int = 480,
105        **kwargs: Any,
106    ) -> None:
107        x = _column(data, "x")
108        y = _column(data, "y")
109        if x is None or y is None:
110            raise ValueError("`data` must provide `x` and `y` columns.")
111
112        bounded_view = _require_flag(bounded_view, "bounded_view")
113        x_arr = _to_float32(x, "x")
114        y_arr = _to_float32(y, "y")
115        if x_arr.size == 0:
116            raise ValueError("`data` must contain at least one row.")
117
118        # p = 0 gives a y of inf, which is drawn at the top. The warning
119        # counts only the rows the browser leaves out, in the words R uses.
120        y_gone = int(np.count_nonzero(np.isnan(y_arr) | (y_arr == -np.inf)))
121        if y_gone:
122            warnings.warn(
123                f"`y` has {y_gone} value(s) that are missing (NA or NaN) or "
124                "-Inf; those rows are not drawn.",
125                stacklevel=2,
126            )
127        buffer, schema = pack_columns({"x": x_arr, "y": y_arr}, quiet=("y",))
128        # JSON has no inf or NaN. Inf labels are asked for as one per gene,
129        # and NaN goes as null, as R sends NA, which labels none.
130        top_n: Any = label_top_n
131        if isinstance(label_top_n, (float, np.floating)):
132            if math.isnan(label_top_n):
133                top_n = None
134            elif math.isinf(label_top_n):
135                top_n = int(x_arr.size) if label_top_n > 0 else 0
136
137        json_columns: dict[str, list] = {}
138        label = _column(data, "label")
139        if label is not None:
140            # A missing symbol crosses as null, as from R, never as "nan".
141            json_columns["label"] = _text_or_none(label)
142
143        options: dict[str, Any] = {
144            "fcThreshold": fc_threshold,
145            "pThreshold": p_threshold,
146            "pointSize": point_size,
147            "opacity": opacity,
148            "xLabel": x_label,
149            "yLabel": y_label,
150            "labelTopN": top_n,
151            "showThresholdLines": show_threshold_lines,
152            "boundedView": bounded_view,
153        }
154        if colors is not None:
155            options["colors"] = dict(colors)
156        if theme is not None:
157            options["theme"] = theme
158
159        super().__init__(
160            buffer=buffer,
161            schema=schema,
162            data={"columns": json_columns, "meta": {}},
163            options=options,
164            _height=height,
165            **kwargs,
166        )

Public constructor

class Embedding(plotomics.PlotomicsWidget):
 22class Embedding(PlotomicsWidget):
 23    """GPU-accelerated 2-D embedding scatter viewer (UMAP / t-SNE / PCA).
 24
 25    Points render on the GPU via regl-scatterplot so hundreds of thousands to
 26    millions of cells stay interactive at 60fps. Lasso selection is enabled
 27    (drag from empty space to select points).
 28
 29    Parameters
 30    ----------
 31    data:
 32        A pandas ``DataFrame`` or a mapping of arrays. Must provide numeric
 33        ``x`` and ``y`` embedding coordinates. An optional ``color`` column
 34        drives coloring: a string/categorical column becomes a discrete legend,
 35        a numeric column a continuous colormap. Text categories are sorted in
 36        natural order ("cluster 2" before "cluster 10"); a pandas
 37        ``Categorical`` color column fixes the legend order and the color
 38        assignment to its categories, and keeps unused ones in the legend. A
 39        missing color is drawn grey and keyed "NA", and a row with a missing
 40        ``x`` or ``y`` is not drawn. An optional ``label``
 41        column supplies per-point tooltip text.
 42    point_scale_mode:
 43        How ``point_size`` responds to zoom. ``"asinh"`` and ``"linear"``
 44        shrink points as you zoom out, which keeps a dense embedding readable,
 45        but both floor at one pixel once the camera scale drops below
 46        ``1 / point_size``. ``"constant"`` sizes points in literal pixels.
 47    point_size, opacity:
 48        Point radius (px) and opacity in ``[0, 1]``.
 49    color_mode:
 50        ``"auto"`` detects categorical vs continuous from the ``color`` column
 51        type; force with ``"categorical"`` / ``"continuous"``.
 52    colormap:
 53        Color ramp for continuous coloring: ``"viridis"``, ``"rdbu"``,
 54        ``"ltc"`` (an earthy teal to sand to rust sequential ramp) or
 55        ``"ltcdiv"`` (its diverging counterpart, neutral cream at the midpoint).
 56    x_label, y_label:
 57        Axis titles (shown when ``show_axes=True``).
 58    aspect:
 59        How the fitted view maps data units onto pixels. ``"fill"`` stretches
 60        each axis to fill the canvas, which suits a UMAP, whose axes carry no
 61        units. ``"equal"`` gives both axes the same units per pixel; use it
 62        when the axes share units and their relative spread is part of the
 63        claim, as in PCA scores.
 64    padding:
 65        Fraction of the data range to pad around the fitted view. Larger values
 66        zoom out, leaving more empty space at the edges, which stops the
 67        outermost points being clipped by the canvas border.
 68    show_axes:
 69        Draw the axis frame + ticks (embeddings usually hide axes).
 70    show_legend:
 71        Draw the legend (discrete swatches or a colorbar).
 72    mouse_mode:
 73        Primary drag gesture: ``"panZoom"`` (default) pans/zooms, ``"lasso"``
 74        makes a plain drag draw a selection.
 75    bounded_view:
 76        Keep pan and zoom inside the data: zooming out stops at the view
 77        that shows all of it, a pan stops at its edges, and zooming in stops
 78        at 1/10,000 of its range. ``False`` lets the view move freely.
 79        Either way a double-click, or the reset button in the top right
 80        corner of the plot, goes back to the view of all the data. A
 81        double-click also clears the lasso selection.
 82    theme:
 83        Optional theme overrides forwarded to the JS renderer. Its
 84        ``padding`` entry is the space in px between the edge of the widget
 85        and the plot: one number for every side, or a dict with any of the
 86        keys ``top``, ``right``, ``bottom`` and ``left``, a side left out
 87        keeping the default of 10.
 88        Its ``categorical`` entry is an ordered palette, a list of colours
 89        that go to the categories in order; colours are not matched by name.
 90        A colour given as a CSS custom property, such as
 91        ``"background": "var(--bg)"``, takes the value the page gives it when
 92        the plot draws. After the page changes the property, what the plot
 93        drew on a canvas keeps the old colour until it draws again: resize
 94        the widget or display it again.
 95    height:
 96        Initial widget height in CSS pixels.
 97
 98    Examples
 99    --------
100    >>> import numpy as np, pandas as pd
101    >>> n = 200_000
102    >>> k = np.random.randint(0, 8, n)
103    >>> df = pd.DataFrame({
104    ...     "x": np.random.randn(n) + k * 4,
105    ...     "y": np.random.randn(n) + (k % 2) * 4,
106    ...     "color": [f"cluster {i + 1}" for i in k],
107    ... })
108    >>> Embedding(df)  # doctest: +SKIP
109    """
110
111    _esm = STATIC / "embedding.js"
112
113    def __init__(
114        self,
115        data: Any,
116        *,
117        point_size: float = 3.0,
118        point_scale_mode: str = "asinh",
119        opacity: float = 0.8,
120        color_mode: str = "auto",
121        colormap: Literal["viridis", "rdbu", "ltc", "ltcdiv"] = "viridis",
122        x_label: str = "UMAP 1",
123        y_label: str = "UMAP 2",
124        aspect: str = "fill",
125        padding: float = 0.04,
126        show_axes: bool = False,
127        show_legend: bool = True,
128        mouse_mode: Literal["panZoom", "lasso"] = "panZoom",
129        bounded_view: bool = True,
130        theme: dict | None = None,
131        height: int = 480,
132        **kwargs: Any,
133    ) -> None:
134        x = _column(data, "x")
135        y = _column(data, "y")
136        if x is None or y is None:
137            raise ValueError("`data` must provide `x` and `y` columns.")
138        _check_choice(mouse_mode, "mouse_mode", ("panZoom", "lasso"))
139        _check_choice(
140            point_scale_mode, "point_scale_mode", ("asinh", "linear", "constant")
141        )
142        _check_choice(color_mode, "color_mode", ("auto", "categorical", "continuous"))
143        _check_choice(colormap, "colormap", ("viridis", "rdbu", "ltc", "ltcdiv"))
144        _check_choice(aspect, "aspect", ("fill", "equal"))
145        bounded_view = _require_flag(bounded_view, "bounded_view")
146
147        x_arr = _to_float32(x, "x")
148        y_arr = _to_float32(y, "y")
149        if x_arr.size == 0:
150            raise ValueError("`data` must contain at least one row.")
151
152        numeric: dict[str, Any] = {"x": x_arr, "y": y_arr}
153        json_columns: dict[str, list] = {}
154
155        color = _column(data, "color")
156        categories: list[str] | None = None
157        if color is not None:
158            # A pandas Categorical is the user stating the order they want, so
159            # read it before np.asarray() flattens it to plain values.
160            categories = _category_levels(color)
161            values = _numeric_values(color) if categories is None else None
162            if values is not None:
163                # Continuous: transport as a packed numeric column, NaN for
164                # a missing value.
165                numeric["color"] = values
166            else:
167                # Categorical: transport as a JSON string column. A missing
168                # value crosses as null, which the browser keys as "NA".
169                json_columns["color"] = _text_or_none(color)
170
171        label = _column(data, "label")
172        if label is not None:
173            json_columns["label"] = _text_or_none(label)
174
175        buffer, schema = pack_columns(numeric)
176
177        options: dict[str, Any] = {
178            "pointSize": point_size,
179            "pointScaleMode": point_scale_mode,
180            "opacity": opacity,
181            "colorMode": color_mode,
182            "colormap": colormap,
183            "xLabel": x_label,
184            "yLabel": y_label,
185            "aspect": aspect,
186            "padding": padding,
187            "showAxes": show_axes,
188            "showLegend": show_legend,
189            "mouseMode": mouse_mode,
190            "boundedView": bounded_view,
191        }
192        if categories is not None:
193            options["categories"] = categories
194        if theme is not None:
195            options["theme"] = theme
196
197        super().__init__(
198            buffer=buffer,
199            schema=schema,
200            data={"columns": json_columns, "meta": {}},
201            options=options,
202            _height=height,
203            **kwargs,
204        )

GPU-accelerated 2-D embedding scatter viewer (UMAP / t-SNE / PCA).

Points render on the GPU via regl-scatterplot so hundreds of thousands to millions of cells stay interactive at 60fps. Lasso selection is enabled (drag from empty space to select points).

Parameters
  • data:: A pandas DataFrame or a mapping of arrays. Must provide numeric x and y embedding coordinates. An optional color column drives coloring: a string/categorical column becomes a discrete legend, a numeric column a continuous colormap. Text categories are sorted in natural order ("cluster 2" before "cluster 10"); a pandas Categorical color column fixes the legend order and the color assignment to its categories, and keeps unused ones in the legend. A missing color is drawn grey and keyed "NA", and a row with a missing x or y is not drawn. An optional label column supplies per-point tooltip text.
  • point_scale_mode:: How point_size responds to zoom. "asinh" and "linear" shrink points as you zoom out, which keeps a dense embedding readable, but both floor at one pixel once the camera scale drops below 1 / point_size. "constant" sizes points in literal pixels.
  • point_size, opacity:: Point radius (px) and opacity in [0, 1].
  • color_mode:: "auto" detects categorical vs continuous from the color column type; force with "categorical" / "continuous".
  • colormap:: Color ramp for continuous coloring: "viridis", "rdbu", "ltc" (an earthy teal to sand to rust sequential ramp) or "ltcdiv" (its diverging counterpart, neutral cream at the midpoint).
  • x_label, y_label:: Axis titles (shown when show_axes=True).
  • aspect:: How the fitted view maps data units onto pixels. "fill" stretches each axis to fill the canvas, which suits a UMAP, whose axes carry no units. "equal" gives both axes the same units per pixel; use it when the axes share units and their relative spread is part of the claim, as in PCA scores.
  • padding:: Fraction of the data range to pad around the fitted view. Larger values zoom out, leaving more empty space at the edges, which stops the outermost points being clipped by the canvas border.
  • show_axes:: Draw the axis frame + ticks (embeddings usually hide axes).
  • show_legend:: Draw the legend (discrete swatches or a colorbar).
  • mouse_mode:: Primary drag gesture: "panZoom" (default) pans/zooms, "lasso" makes a plain drag draw a selection.
  • bounded_view:: Keep pan and zoom inside the data: zooming out stops at the view that shows all of it, a pan stops at its edges, and zooming in stops at 1/10,000 of its range. False lets the view move freely. Either way a double-click, or the reset button in the top right corner of the plot, goes back to the view of all the data. A double-click also clears the lasso selection.
  • theme:: Optional theme overrides forwarded to the JS renderer. Its padding entry is the space in px between the edge of the widget and the plot: one number for every side, or a dict with any of the keys top, right, bottom and left, a side left out keeping the default of 10. Its categorical entry is an ordered palette, a list of colours that go to the categories in order; colours are not matched by name. A colour given as a CSS custom property, such as "background": "var(--bg)", takes the value the page gives it when the plot draws. After the page changes the property, what the plot drew on a canvas keeps the old colour until it draws again: resize the widget or display it again.
  • height:: Initial widget height in CSS pixels.
Examples
>>> import numpy as np, pandas as pd
>>> n = 200_000
>>> k = np.random.randint(0, 8, n)
>>> df = pd.DataFrame({
...     "x": np.random.randn(n) + k * 4,
...     "y": np.random.randn(n) + (k % 2) * 4,
...     "color": [f"cluster {i + 1}" for i in k],
... })
>>> Embedding(df)  # doctest: +SKIP
Embedding( data: Any, *, point_size: float = 3.0, point_scale_mode: str = 'asinh', opacity: float = 0.8, color_mode: str = 'auto', colormap: Literal['viridis', 'rdbu', 'ltc', 'ltcdiv'] = 'viridis', x_label: str = 'UMAP 1', y_label: str = 'UMAP 2', aspect: str = 'fill', padding: float = 0.04, show_axes: bool = False, show_legend: bool = True, mouse_mode: Literal['panZoom', 'lasso'] = 'panZoom', bounded_view: bool = True, theme: dict | None = None, height: int = 480, **kwargs: Any)
113    def __init__(
114        self,
115        data: Any,
116        *,
117        point_size: float = 3.0,
118        point_scale_mode: str = "asinh",
119        opacity: float = 0.8,
120        color_mode: str = "auto",
121        colormap: Literal["viridis", "rdbu", "ltc", "ltcdiv"] = "viridis",
122        x_label: str = "UMAP 1",
123        y_label: str = "UMAP 2",
124        aspect: str = "fill",
125        padding: float = 0.04,
126        show_axes: bool = False,
127        show_legend: bool = True,
128        mouse_mode: Literal["panZoom", "lasso"] = "panZoom",
129        bounded_view: bool = True,
130        theme: dict | None = None,
131        height: int = 480,
132        **kwargs: Any,
133    ) -> None:
134        x = _column(data, "x")
135        y = _column(data, "y")
136        if x is None or y is None:
137            raise ValueError("`data` must provide `x` and `y` columns.")
138        _check_choice(mouse_mode, "mouse_mode", ("panZoom", "lasso"))
139        _check_choice(
140            point_scale_mode, "point_scale_mode", ("asinh", "linear", "constant")
141        )
142        _check_choice(color_mode, "color_mode", ("auto", "categorical", "continuous"))
143        _check_choice(colormap, "colormap", ("viridis", "rdbu", "ltc", "ltcdiv"))
144        _check_choice(aspect, "aspect", ("fill", "equal"))
145        bounded_view = _require_flag(bounded_view, "bounded_view")
146
147        x_arr = _to_float32(x, "x")
148        y_arr = _to_float32(y, "y")
149        if x_arr.size == 0:
150            raise ValueError("`data` must contain at least one row.")
151
152        numeric: dict[str, Any] = {"x": x_arr, "y": y_arr}
153        json_columns: dict[str, list] = {}
154
155        color = _column(data, "color")
156        categories: list[str] | None = None
157        if color is not None:
158            # A pandas Categorical is the user stating the order they want, so
159            # read it before np.asarray() flattens it to plain values.
160            categories = _category_levels(color)
161            values = _numeric_values(color) if categories is None else None
162            if values is not None:
163                # Continuous: transport as a packed numeric column, NaN for
164                # a missing value.
165                numeric["color"] = values
166            else:
167                # Categorical: transport as a JSON string column. A missing
168                # value crosses as null, which the browser keys as "NA".
169                json_columns["color"] = _text_or_none(color)
170
171        label = _column(data, "label")
172        if label is not None:
173            json_columns["label"] = _text_or_none(label)
174
175        buffer, schema = pack_columns(numeric)
176
177        options: dict[str, Any] = {
178            "pointSize": point_size,
179            "pointScaleMode": point_scale_mode,
180            "opacity": opacity,
181            "colorMode": color_mode,
182            "colormap": colormap,
183            "xLabel": x_label,
184            "yLabel": y_label,
185            "aspect": aspect,
186            "padding": padding,
187            "showAxes": show_axes,
188            "showLegend": show_legend,
189            "mouseMode": mouse_mode,
190            "boundedView": bounded_view,
191        }
192        if categories is not None:
193            options["categories"] = categories
194        if theme is not None:
195            options["theme"] = theme
196
197        super().__init__(
198            buffer=buffer,
199            schema=schema,
200            data={"columns": json_columns, "meta": {}},
201            options=options,
202            _height=height,
203            **kwargs,
204        )

Public constructor