Skip to content

scatter

scatter #

Scatter — points over named columns, either axis picked from a menu.

GROUP = 'Group' module-attribute #

What the legend and the tooltip call groups.

TIME_OF_DAY = ' (time of day)' module-attribute #

The suffix naming the clock-time choice an instants column adds to the menus.

Scatter #

Bases: Component

Every point over named columns, either axis picked from a menu above the plot.

A column is a quantity per point — a broadcast column (frames.iso) or a plain list, every column the same length. A value that was never recorded is absent, and its point sits off the axes showing it; a column with nothing recorded is left out of the menus, and the plot opens on default only when both its columns have something to plot. Each axis spans spread standard deviations of its own column, clamped to that column's range, so one far-off point cannot squash the rest into a line — and picking a new axis re-frames it, dragged or zoomed as the reader may have left it. A column named in spans always spans that fixed range instead, wherever its points fall. The page carries each value to six significant figures.

A column of instants offers two choices: the instant itself, read as a date, and its time of day, both in the reader's own time zone. color and size name number columns that shade and size every point; groups colours the points by category instead, so a scatter takes one or the other.

cgui.Scatter(
    {"Sun altitude (°)": sun.altitude, "ISO": frames.iso, "Cloud (0–1)": weather.cloud},
    default=("Sun altitude (°)", "ISO"),
    groups=frames.session,
    spans={"Sun altitude (°)": (0.0, 90.0)},
)
Source code in capturegraph-ui/capturegraph_ui/charts/scatter.py
class Scatter(Component):
    """Every point over named ``columns``, either axis picked from a menu above the plot.

    A column is a quantity per point — a broadcast column (``frames.iso``) or a
    plain list, every column the same length. A value that was never recorded
    is absent, and its point sits off the axes showing it; a column with nothing
    recorded is left out of the menus, and the plot opens on ``default`` only
    when both its columns have something to plot. Each axis spans ``spread`` standard
    deviations of its own column, clamped to that column's range, so one far-off
    point cannot squash the rest into a line — and picking a new axis re-frames
    it, dragged or zoomed as the reader may have left it. A column named in
    ``spans`` always spans that fixed range instead, wherever its points fall.
    The page carries each value to six significant figures.

    A column of instants offers two choices: the instant itself, read as a date,
    and its time of day, both in the reader's own time zone. ``color`` and
    ``size`` name number columns that shade and size every point; ``groups``
    colours the points by category instead, so a scatter takes one or the other.

    ```python
    cgui.Scatter(
        {"Sun altitude (°)": sun.altitude, "ISO": frames.iso, "Cloud (0–1)": weather.cloud},
        default=("Sun altitude (°)", "ISO"),
        groups=frames.session,
        spans={"Sun altitude (°)": (0.0, 90.0)},
    )
    ```
    """

    columns: dict[str, cg.Array]
    default: tuple[str, str] | None = None
    groups: cg.Array | None = None
    spread: float = 3.0
    spans: dict[str, tuple[float, float]] | None = None
    color: str | None = None
    size: str | None = None

    @classmethod
    def of(
        cls,
        *sources: Source,
        default: tuple[str, str] | None = None,
        groups: cg.Array | None = None,
        spread: float = 3.0,
        spans: dict[str, tuple[float, float]] | None = None,
        color: str | None = None,
        size: str | None = None,
    ) -> Self:
        """A scatter over every quantity of each source, labelled by its type.

        A source is an array of records — every field its type marks with a
        ``cg.Quantity`` becomes a column labelled from it, such as
        ``"Temperature (°C)"``, spanning the quantity's fixed span where it
        declares one — or a dict of further columns, named as given.

        Args:
            *sources: Arrays of records (``exif``, ``exif.gps``, ``weather``) or dicts of columns.
            default: The two columns the plot opens on.
            groups: The category of each point, coloured and listed in the legend.
            spread: How many standard deviations each axis spans.
            spans: Fixed ranges by column, over any its quantity declares.
            color: The number column that shades each point.
            size: The number column that sizes each point.

        A ``default`` quantity no record carries — no photographs yet — counts
        as recorded nowhere, and the plot opens on the first columns instead.

        Raises:
            ValueError: If two sources give columns the same label.

        ```python
        cgui.Scatter.of(
            sun,
            exif,
            exif.gps,
            weather,
            {"File size (MB)": sizes},
            default=("Sun azimuth (°)", "Sun altitude (°)"),
        )
        ```
        """
        columns, declared = named_columns(*sources)
        length = len(next(iter(columns.values()), ()))
        for name in default or ():
            columns.setdefault(name.removesuffix(TIME_OF_DAY), cg.Array([cg.Missing] * length))
        return cls(
            columns,
            default=default,
            groups=groups,
            spread=spread,
            spans={**declared, **(spans or {})},
            color=color,
            size=size,
        )

    def __post_init__(self) -> None:
        """Check the props, then that the columns line up and every named column exists.

        Raises:
            ValueError: If the columns are of different lengths, ``groups`` is
                of another length, ``default``, ``spans``, ``color`` or ``size``
                names a column that is absent, ``color`` or ``size`` names a
                column of instants, or ``color`` comes with ``groups``.
        """
        super().__post_init__()
        if self.absent:
            return
        lengths = {name: len(column) for name, column in self.columns.items()}
        if self.groups is not None:
            lengths[GROUP] = len(self.groups)
        if len(set(lengths.values())) > 1:
            raise ValueError(f"Scatter columns are one value per point, got lengths {lengths}")
        choices = {*self.columns, *(f"{name}{TIME_OF_DAY}" for name in self.columns)}
        for name in self.default or ():
            if name not in choices:
                raise ValueError(f"Scatter.default names {name!r}, which is not a column")
        for name in self.spans or ():
            if name not in self.columns:
                raise ValueError(f"Scatter.spans names {name!r}, which is not a column")
        for prop, name in (("color", self.color), ("size", self.size)):
            if name is None:
                continue
            if name not in self.columns:
                raise ValueError(f"Scatter.{prop} names {name!r}, which is not a column")
            if encode(self.columns[name]).kind != "number":
                raise ValueError(f"Scatter.{prop} names {name!r}, which is not a number column")
        if self.color is not None and self.groups is not None:
            raise ValueError("Scatter colours points by color or by groups, not both")

    def html(self, render: Render) -> str:
        """The points as one Vega-Lite scatter, the menus and the per-axis spans built in."""
        encoded = {name: encode(column) for name, column in self.columns.items()}
        fixed = self.spans or {}
        spans: dict[str, list[float]] = {}
        kinds: dict[str, str] = {}
        for name, column in encoded.items():
            span = _span(column.values, self.spread)
            if span is None:
                continue
            spans[name] = list(fixed[name]) if name in fixed else span
            kinds[name] = "date" if column.kind == "instant" else "number"
            if column.kind == "instant":
                spans[f"{name}{TIME_OF_DAY}"] = [0.0, 24.0]
                kinds[f"{name}{TIME_OF_DAY}"] = "clock"
        if not spans:
            return ""
        return embed(render, self._spec(encoded, spans, kinds))

    def _spec(
        self,
        encoded: dict[str, Encoded],
        spans: dict[str, list[float]],
        kinds: dict[str, str],
    ) -> dict[str, cg.JSONValue]:
        """The specification: the points, the two menus, and each axis read through them."""
        choices = list(spans)
        opening = (
            self.default
            if self.default is not None and all(name in spans for name in self.default)
            else (choices[0], choices[-1])
        )
        groups = None if self.groups is None else encode(self.groups)
        params: list[cg.JSONValue] = [
            _menu("x_axis", opening[0], choices, "X axis "),
            _menu("y_axis", opening[1], choices, "Y axis "),
            {"name": "spans", "value": {name: list(span) for name, span in spans.items()}},
            {"name": "kinds", "value": dict(kinds)},
            {
                "name": "zoom",
                "select": {"type": "interval", "clear": {"source": "window", "type": "change"}},
                "bind": "scales",
            },
        ]
        tooltip: list[cg.JSONValue] = [
            {"field": "x_text", "type": "nominal", "title": {"expr": "x_axis"}},
            {"field": "y_text", "type": "nominal", "title": {"expr": "y_axis"}},
        ]
        encoding: dict[str, cg.JSONValue] = {
            "x": _axis("x", "x_axis"),
            "y": _axis("y", "y_axis"),
        }
        if groups is not None:
            color: dict[str, cg.JSONValue] = {"field": GROUP, "type": "nominal"}
            if groups.kind == "instant":
                color["legend"] = {"labelExpr": _MOMENT.format(v="toNumber(datum.value)")}
            encoding["color"] = color
            tooltip.insert(0, {"field": "group_text", "type": "nominal", "title": GROUP})
        for channel, name in (("color", self.color), ("size", self.size)):
            if name is not None:
                encoding[channel] = {"field": _field(name), "type": "quantitative", "title": name}
                tooltip.append({"field": _field(name), "type": "quantitative", "title": name})
        encoding["tooltip"] = tooltip
        columns = self._columns(encoded, groups)
        return {
            "width": "container",
            "height": 460,
            "data": {"values": [columns]},
            "params": params,
            "transform": [
                {"flatten": [_field(name) for name in columns], "as": list(columns)},
                *(
                    {"calculate": _time_of_day(name), "as": f"{name}{TIME_OF_DAY}"}
                    for name, column in encoded.items()
                    if column.kind == "instant"
                ),
                {"calculate": "datum[x_axis]", "as": "x"},
                {"calculate": "datum[y_axis]", "as": "y"},
                {"filter": "isValid(datum.x) && isValid(datum.y)"},
                {"calculate": _shown("x_axis", "datum.x"), "as": "x_text"},
                {"calculate": _shown("y_axis", "datum.y"), "as": "y_text"},
                *(
                    [{"calculate": _group_text(groups), "as": "group_text"}]
                    if groups is not None
                    else []
                ),
            ],
            "mark": {"type": "point", "filled": True, "size": 45, "opacity": 0.65},
            "encoding": encoding,
        }

    def _columns(
        self,
        encoded: dict[str, Encoded],
        groups: Encoded | None,
    ) -> dict[str, cg.JSONValue]:
        """One list per column of its value at each point, and one of the group each belongs to."""
        columns: dict[str, cg.JSONValue] = {
            name: [_rounded(value, column.kind) for value in column.values]
            for name, column in encoded.items()
        }
        if self.groups is not None and groups is not None:
            columns[GROUP] = (
                [None if value is None else f"{value:.0f}" for value in groups.values]
                if groups.kind == "instant"
                else [_text(item) for item in self.groups]
            )
        return columns

__post_init__() #

Check the props, then that the columns line up and every named column exists.

Raises:

Type Description
ValueError

If the columns are of different lengths, groups is of another length, default, spans, color or size names a column that is absent, color or size names a column of instants, or color comes with groups.

Source code in capturegraph-ui/capturegraph_ui/charts/scatter.py
def __post_init__(self) -> None:
    """Check the props, then that the columns line up and every named column exists.

    Raises:
        ValueError: If the columns are of different lengths, ``groups`` is
            of another length, ``default``, ``spans``, ``color`` or ``size``
            names a column that is absent, ``color`` or ``size`` names a
            column of instants, or ``color`` comes with ``groups``.
    """
    super().__post_init__()
    if self.absent:
        return
    lengths = {name: len(column) for name, column in self.columns.items()}
    if self.groups is not None:
        lengths[GROUP] = len(self.groups)
    if len(set(lengths.values())) > 1:
        raise ValueError(f"Scatter columns are one value per point, got lengths {lengths}")
    choices = {*self.columns, *(f"{name}{TIME_OF_DAY}" for name in self.columns)}
    for name in self.default or ():
        if name not in choices:
            raise ValueError(f"Scatter.default names {name!r}, which is not a column")
    for name in self.spans or ():
        if name not in self.columns:
            raise ValueError(f"Scatter.spans names {name!r}, which is not a column")
    for prop, name in (("color", self.color), ("size", self.size)):
        if name is None:
            continue
        if name not in self.columns:
            raise ValueError(f"Scatter.{prop} names {name!r}, which is not a column")
        if encode(self.columns[name]).kind != "number":
            raise ValueError(f"Scatter.{prop} names {name!r}, which is not a number column")
    if self.color is not None and self.groups is not None:
        raise ValueError("Scatter colours points by color or by groups, not both")

html(render) #

The points as one Vega-Lite scatter, the menus and the per-axis spans built in.

Source code in capturegraph-ui/capturegraph_ui/charts/scatter.py
def html(self, render: Render) -> str:
    """The points as one Vega-Lite scatter, the menus and the per-axis spans built in."""
    encoded = {name: encode(column) for name, column in self.columns.items()}
    fixed = self.spans or {}
    spans: dict[str, list[float]] = {}
    kinds: dict[str, str] = {}
    for name, column in encoded.items():
        span = _span(column.values, self.spread)
        if span is None:
            continue
        spans[name] = list(fixed[name]) if name in fixed else span
        kinds[name] = "date" if column.kind == "instant" else "number"
        if column.kind == "instant":
            spans[f"{name}{TIME_OF_DAY}"] = [0.0, 24.0]
            kinds[f"{name}{TIME_OF_DAY}"] = "clock"
    if not spans:
        return ""
    return embed(render, self._spec(encoded, spans, kinds))

of(*sources, default=None, groups=None, spread=3.0, spans=None, color=None, size=None) classmethod #

A scatter over every quantity of each source, labelled by its type.

A source is an array of records — every field its type marks with a cg.Quantity becomes a column labelled from it, such as "Temperature (°C)", spanning the quantity's fixed span where it declares one — or a dict of further columns, named as given.

Parameters:

Name Type Description Default
*sources Source

Arrays of records (exif, exif.gps, weather) or dicts of columns.

()
default tuple[str, str] | None

The two columns the plot opens on.

None
groups Array | None

The category of each point, coloured and listed in the legend.

None
spread float

How many standard deviations each axis spans.

3.0
spans dict[str, tuple[float, float]] | None

Fixed ranges by column, over any its quantity declares.

None
color str | None

The number column that shades each point.

None
size str | None

The number column that sizes each point.

None

A default quantity no record carries — no photographs yet — counts as recorded nowhere, and the plot opens on the first columns instead.

Raises:

Type Description
ValueError

If two sources give columns the same label.

cgui.Scatter.of(
    sun,
    exif,
    exif.gps,
    weather,
    {"File size (MB)": sizes},
    default=("Sun azimuth (°)", "Sun altitude (°)"),
)
Source code in capturegraph-ui/capturegraph_ui/charts/scatter.py
@classmethod
def of(
    cls,
    *sources: Source,
    default: tuple[str, str] | None = None,
    groups: cg.Array | None = None,
    spread: float = 3.0,
    spans: dict[str, tuple[float, float]] | None = None,
    color: str | None = None,
    size: str | None = None,
) -> Self:
    """A scatter over every quantity of each source, labelled by its type.

    A source is an array of records — every field its type marks with a
    ``cg.Quantity`` becomes a column labelled from it, such as
    ``"Temperature (°C)"``, spanning the quantity's fixed span where it
    declares one — or a dict of further columns, named as given.

    Args:
        *sources: Arrays of records (``exif``, ``exif.gps``, ``weather``) or dicts of columns.
        default: The two columns the plot opens on.
        groups: The category of each point, coloured and listed in the legend.
        spread: How many standard deviations each axis spans.
        spans: Fixed ranges by column, over any its quantity declares.
        color: The number column that shades each point.
        size: The number column that sizes each point.

    A ``default`` quantity no record carries — no photographs yet — counts
    as recorded nowhere, and the plot opens on the first columns instead.

    Raises:
        ValueError: If two sources give columns the same label.

    ```python
    cgui.Scatter.of(
        sun,
        exif,
        exif.gps,
        weather,
        {"File size (MB)": sizes},
        default=("Sun azimuth (°)", "Sun altitude (°)"),
    )
    ```
    """
    columns, declared = named_columns(*sources)
    length = len(next(iter(columns.values()), ()))
    for name in default or ():
        columns.setdefault(name.removesuffix(TIME_OF_DAY), cg.Array([cg.Missing] * length))
    return cls(
        columns,
        default=default,
        groups=groups,
        spread=spread,
        spans={**declared, **(spans or {})},
        color=color,
        size=size,
    )