Skip to content

ScatterGlyph Class#

The ScatterGlyph class visualizes 2-D point clouds. With a per-point values array the points are colour-mapped through the shared scalar-mapping pipeline (so vmin / vmax / levels / color_scale behave as for the other glyphs) and a matching colorbar is attached. An independent per-point sizes array scales the marker area — with an optional size legend — so colour and size can encode two different quantities at once.

Class Documentation#

cleopatra.glyphs.primitives.scatter_glyph.ScatterGlyph #

Bases: GeoMixin, Glyph

Visualization class for 2D point clouds.

Wraps matplotlib.axes.Axes.scatter. With no values, points are drawn in a single colour. With a per-point values array, points are colour-mapped through the shared scalar-mapping pipeline and a matching colorbar is attached. An independent per-point sizes array scales the marker area (with an optional size legend), so colour and size can encode two different quantities at once.

Parameters:

Name Type Description Default
x ndarray

1D array of point x-coordinates.

required
y ndarray

1D array of point y-coordinates. Must match the length of x.

required
values ndarray | None

Optional 1D array of per-point scalar values used for colour mapping. Must match the length of x when given. Default is None (uncoloured points).

None
sizes ndarray | None

Optional 1D array of per-point magnitudes used for size mapping (kept separate from values, which drives colour, so a point can encode both). Must match the length of x when given. When None, the scalar point_size option is used for every point (the original behaviour). Default is None.

None
colors Sequence | None

Optional explicit per-point colours (length must equal the number of points), the way BarGlyph takes colors= per category. Drawn verbatim -- no colormap, no colorbar -- so it is for a caller that already has one colour per point (e.g. a categorical column mapped upstream), not for value-driven mapping. Mutually exclusive with values and with flat_color. Default is None.

None
ax Axes | None

Pre-existing axes to draw on. Default is None.

None
fig Figure | None

Pre-existing figure. Default is None.

None
**kwargs Any

Override any key in SCATTER_DEFAULT_OPTIONS (e.g. marker, point_size, cmap, vmin, vmax, levels, color_scale, ticks_spacing, cbar_label, figsize, title). flat_color sets a single flat colour for the uncoloured path -- a plain colour string/tuple, kept distinct from plot's grouped color= (a ColorScaling), which is for value-driven mapping only. Mutually exclusive with values and with colors. alpha sets marker opacity (default 1.0). Set add_colorbar=False to suppress the per-glyph colorbar (default True) for shared-axes composition where the host owns a single aggregated colorbar. The size_limits (min/max marker area in points², default (10, 200)), size_scale ("linear" / "log" / "sqrt", default "linear"), size_legend (bool, default False), size_legend_values (explicit representative magnitudes), and size_legend_kwargs (forwarded to the legend) options control the sizes mapping and its legend.

{}

Raises:

Type Description
TypeError

If colors is given as a bare str/bytes rather than a sequence of per-point colours.

ValueError

If x and y (or values / sizes / colors, when given) have mismatched lengths, or if more than one of values, colors, and flat_color is given.

Examples:

  • Colour points by value and read back the mapped array:
    >>> import numpy as np
    >>> from cleopatra.glyphs.primitives.scatter_glyph import ScatterGlyph
    >>> glyph = ScatterGlyph(
    ...     np.array([0.0, 1.0, 2.0]),
    ...     np.array([0.0, 1.0, 0.0]),
    ...     np.array([1.0, 5.0, 9.0]),
    ... )
    >>> fig, ax, paths = glyph.plot()
    >>> [float(v) for v in paths.get_array()]
    [1.0, 5.0, 9.0]
    
  • Draw a flat-coloured point cloud (no values, no colorbar):
    >>> import numpy as np
    >>> from cleopatra.glyphs.primitives.scatter_glyph import ScatterGlyph
    >>> glyph = ScatterGlyph(
    ...     np.array([0.0, 1.0]), np.array([0.0, 1.0]), flat_color="navy", alpha=0.7
    ... )
    >>> fig, ax, paths = glyph.plot()
    >>> paths.get_array() is None
    True
    
  • Size points by a magnitude; the areas span size_limits:
    >>> import numpy as np
    >>> from cleopatra.glyphs.primitives.scatter_glyph import ScatterGlyph
    >>> glyph = ScatterGlyph(
    ...     np.array([0.0, 1.0, 2.0]),
    ...     np.array([0.0, 1.0, 0.0]),
    ...     sizes=np.array([1.0, 5.0, 9.0]),
    ...     size_limits=(10, 200),
    ... )
    >>> fig, ax, paths = glyph.plot()
    >>> [float(s) for s in paths.get_sizes()]
    [10.0, 105.0, 200.0]
    
See Also

cleopatra.glyphs.base.glyph.Glyph._prepare_scalar_mapping: Shared norm/colorbar/ticks pipeline used for the coloured path. cleopatra.styling.styles.resolve_sizes: The value→size helper used for the sizes mapping (reusable by other size-encoding glyphs). cleopatra.styling.styles.size_legend: Builds the size legend drawn when size_legend is truthy. cleopatra.glyphs.stats.bar_glyph.BarGlyph: Takes an explicit colors= sequence the same way, one colour per category instead of per point.

Source code in src/cleopatra/glyphs/primitives/scatter_glyph.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
class ScatterGlyph(GeoMixin, Glyph):
    """Visualization class for 2D point clouds.

    Wraps `matplotlib.axes.Axes.scatter`. With no `values`, points are
    drawn in a single colour. With a per-point `values` array, points
    are colour-mapped through the shared scalar-mapping pipeline and a
    matching colorbar is attached. An independent per-point `sizes` array
    scales the marker area (with an optional size legend), so colour and
    size can encode two different quantities at once.

    Args:
        x: 1D array of point x-coordinates.
        y: 1D array of point y-coordinates. Must match the length of
            `x`.
        values: Optional 1D array of per-point scalar values used for
            colour mapping. Must match the length of `x` when given.
            Default is None (uncoloured points).
        sizes: Optional 1D array of per-point magnitudes used for *size*
            mapping (kept separate from `values`, which drives colour, so a
            point can encode both). Must match the length of `x` when
            given. When None, the scalar `point_size` option is used for
            every point (the original behaviour). Default is None.
        colors: Optional explicit per-point colours (length must equal the
            number of points), the way `BarGlyph` takes `colors=` per
            category. Drawn verbatim -- no colormap, no colorbar -- so it is
            for a caller that already has one colour per point (e.g. a
            categorical column mapped upstream), not for value-driven
            mapping. Mutually exclusive with `values` and with `flat_color`.
            Default is None.
        ax: Pre-existing axes to draw on. Default is None.
        fig: Pre-existing figure. Default is None.
        **kwargs (Any): Override any key in `SCATTER_DEFAULT_OPTIONS`
            (e.g. `marker`, `point_size`, `cmap`, `vmin`, `vmax`,
            `levels`, `color_scale`, `ticks_spacing`, `cbar_label`,
            `figsize`, `title`). `flat_color` sets a single flat colour for
            the uncoloured path -- a plain colour string/tuple, kept
            distinct from `plot`'s grouped `color=` (a `ColorScaling`),
            which is for value-driven mapping only. Mutually exclusive with
            `values` and with `colors`. `alpha` sets marker opacity
            (default `1.0`). Set
            `add_colorbar=False` to suppress the per-glyph colorbar (default
            True) for shared-axes composition where the host owns a single
            aggregated colorbar. The `size_limits` (min/max marker area in
            points², default `(10, 200)`), `size_scale` (`"linear"` /
            `"log"` / `"sqrt"`, default `"linear"`), `size_legend` (bool,
            default False), `size_legend_values` (explicit representative
            magnitudes), and `size_legend_kwargs` (forwarded to the legend)
            options control the `sizes` mapping and its legend.

    Raises:
        TypeError: If `colors` is given as a bare `str`/`bytes` rather than a
            sequence of per-point colours.
        ValueError: If `x` and `y` (or `values` / `sizes` / `colors`, when
            given) have mismatched lengths, or if more than one of `values`,
            `colors`, and `flat_color` is given.

    Examples:
        - Colour points by value and read back the mapped array:
            ```python
            >>> import numpy as np
            >>> from cleopatra.glyphs.primitives.scatter_glyph import ScatterGlyph
            >>> glyph = ScatterGlyph(
            ...     np.array([0.0, 1.0, 2.0]),
            ...     np.array([0.0, 1.0, 0.0]),
            ...     np.array([1.0, 5.0, 9.0]),
            ... )
            >>> fig, ax, paths = glyph.plot()
            >>> [float(v) for v in paths.get_array()]
            [1.0, 5.0, 9.0]

            ```
        - Draw a flat-coloured point cloud (no `values`, no colorbar):
            ```python
            >>> import numpy as np
            >>> from cleopatra.glyphs.primitives.scatter_glyph import ScatterGlyph
            >>> glyph = ScatterGlyph(
            ...     np.array([0.0, 1.0]), np.array([0.0, 1.0]), flat_color="navy", alpha=0.7
            ... )
            >>> fig, ax, paths = glyph.plot()
            >>> paths.get_array() is None
            True

            ```
        - Size points by a magnitude; the areas span `size_limits`:
            ```python
            >>> import numpy as np
            >>> from cleopatra.glyphs.primitives.scatter_glyph import ScatterGlyph
            >>> glyph = ScatterGlyph(
            ...     np.array([0.0, 1.0, 2.0]),
            ...     np.array([0.0, 1.0, 0.0]),
            ...     sizes=np.array([1.0, 5.0, 9.0]),
            ...     size_limits=(10, 200),
            ... )
            >>> fig, ax, paths = glyph.plot()
            >>> [float(s) for s in paths.get_sizes()]
            [10.0, 105.0, 200.0]

            ```

    See Also:
        cleopatra.glyphs.base.glyph.Glyph._prepare_scalar_mapping: Shared
            norm/colorbar/ticks pipeline used for the coloured path.
        cleopatra.styling.styles.resolve_sizes: The value→size helper used for the
            `sizes` mapping (reusable by other size-encoding glyphs).
        cleopatra.styling.styles.size_legend: Builds the size legend drawn when
            `size_legend` is truthy.
        cleopatra.glyphs.stats.bar_glyph.BarGlyph: Takes an explicit `colors=`
            sequence the same way, one colour per category instead of per point.
    """

    #: Option keys this glyph accepts (see `Glyph.option_keys`/`filter_kwargs`).
    DEFAULT_OPTIONS = SCATTER_DEFAULT_OPTIONS
    #: Per-point `values` are a nominal class label just as often as a
    #: continuous magnitude, so `scheme="categorical"` is supported.
    _SUPPORTS_CATEGORICAL_SCHEME = True

    def __init__(
        self,
        x: np.ndarray,
        y: np.ndarray,
        values: np.ndarray | None = None,
        *,
        sizes: np.ndarray | None = None,
        colors: Sequence | None = None,
        ax: Axes | None = None,
        fig: Figure | None = None,
        **kwargs,
    ):
        super().__init__(
            default_options=SCATTER_DEFAULT_OPTIONS, fig=fig, ax=ax, **kwargs
        )
        self.x = np.asarray(x)
        self.y = np.asarray(y)
        if self.x.shape != self.y.shape:
            raise ValueError(
                f"x and y must have the same shape, got {self.x.shape} "
                f"and {self.y.shape}."
            )
        if values is not None:
            values = np.asarray(values)
            if values.shape != self.x.shape:
                raise ValueError(
                    f"values must match x/y shape {self.x.shape}, got {values.shape}."
                )
        if sizes is not None:
            sizes = np.asarray(sizes)
            if sizes.shape != self.x.shape:
                raise ValueError(
                    f"sizes must match x/y shape {self.x.shape}, got {sizes.shape}."
                )
        # `values`/`colors`/`flat_color` each drive point colour a different way
        # (colormap / explicit sequence / single flat colour) -- at most one may
        # be given, checked together rather than pairwise so a third colour
        # source added later cannot reopen this gap the way `colors`+`flat_color`
        # originally did.
        given = [
            name
            for name, val in (
                ("values", values),
                ("colors", colors),
                ("flat_color", self.default_options["flat_color"]),
            )
            if val is not None
        ]
        if len(given) > 1:
            raise ValueError(
                f"{' and '.join(given)} are mutually exclusive: values maps a "
                "scalar through a colormap, colors is an explicit per-point "
                "colour sequence, and flat_color is a single explicit colour -- "
                "only one colour source may be given."
            )
        if colors is not None:
            colors = validate_color_sequence(
                colors, self.x.shape[0], param="colors", noun="points"
            )
        self.values = values
        self.sizes = sizes
        self.colors = colors
        self.cbar: Colorbar | None = None
        #: The size legend created by `plot` when `size_legend` is truthy
        #: (None otherwise); built via `cleopatra.styling.styles.size_legend`.
        self.size_legend_artist: Legend | None = None
        #: The disjoint legend created by `plot` when `scheme="categorical"`
        #: (`None` otherwise); built via `Glyph.create_categorical_legend`.
        self.category_legend: Legend | None = None

    def plot(
        self,
        ax: Axes | None = None,
        title: str | None = None,
        add_colorbar: bool | None = None,
        colorbar: bool | ColorBar | None = None,
        color: ColorScaling | None = None,
        contour: Contour | None = None,
        classify: Classify | None = None,
    ) -> tuple[Figure, Axes, PathCollection]:
        """Draw the point cloud, colour- and/or size-mapping per point.

        When `values` was supplied at construction, the colour scale,
        norm, ticks, and colorbar are resolved through
        `_prepare_scalar_mapping`, so `vmin` / `vmax` / `levels` /
        `color_scale` behave as for the other glyphs. With no values,
        a single-colour scatter is drawn and no colorbar is added.

        The one exception is `scheme="categorical"`: `vmin` / `vmax` /
        `levels` / `color_scale` are ignored (with a warning if set), and
        instead of a colorbar a `disjoint_legend` is drawn and stored on
        `self.category_legend` (`self.cbar` stays `None`). See
        `Glyph._prepare_categorical_mapping`.

        When `sizes` was supplied, each marker's area is resolved from
        that magnitude via `cleopatra.styling.styles.resolve_sizes` (honouring
        `size_limits` / `size_scale`); otherwise the scalar `point_size`
        option is used for every point. Colour and size are independent,
        so a point can encode two quantities at once. If `size_legend` is
        truthy, a size legend is drawn via `cleopatra.styling.styles.size_legend`
        and stored on `self.size_legend_artist`.

        Args:
            ax: Axes to draw on. Falls back to the axes supplied at
                construction, otherwise a new figure/axes is created.
            title: Plot title. Overrides `default_options["title"]`
                when given.
            add_colorbar: Override the `add_colorbar` option for this call
                — True draws the colorbar, False suppresses it (for
                shared-axes composition). Defaults to None, which keeps the
                value set at construction.
            colorbar: Typed `ColorBar` spec (or `True`/`False`/`None`) for the
                colorbar's placement, caption, and sizing; resolved into the
                `cbar_*` options. A `ColorBar`/`True` also enables the bar and is
                **sticky** -- it persists into later plots, overriding a
                construction-time `add_colorbar=False`; an explicit
                `add_colorbar=` argument still wins the on/off decision.

        Returns:
            tuple[Figure, Axes, PathCollection]: The figure, the axes,
                and the `PathCollection` returned by `scatter` (the
                mappable for the coloured path).

        Examples:
            - Uncoloured points return a PathCollection with no array:
                ```python
                >>> import numpy as np
                >>> from cleopatra.glyphs.primitives.scatter_glyph import ScatterGlyph
                >>> glyph = ScatterGlyph(
                ...     np.array([0.0, 1.0]), np.array([0.0, 1.0])
                ... )
                >>> fig, ax, paths = glyph.plot()
                >>> paths.get_array() is None
                True

                ```
            - A title passed to plot overrides the default:
                ```python
                >>> import numpy as np
                >>> from cleopatra.glyphs.primitives.scatter_glyph import ScatterGlyph
                >>> glyph = ScatterGlyph(
                ...     np.array([0.0, 1.0]), np.array([0.0, 1.0])
                ... )
                >>> fig, ax, paths = glyph.plot(title="Stations")
                >>> ax.get_title()
                'Stations'

                ```
            - Combine colour and size, with a size legend:
                ```python
                >>> import numpy as np
                >>> from cleopatra.glyphs.primitives.scatter_glyph import ScatterGlyph
                >>> glyph = ScatterGlyph(
                ...     np.array([0.0, 1.0, 2.0]),
                ...     np.array([0.0, 1.0, 0.0]),
                ...     values=np.array([1.0, 2.0, 3.0]),
                ...     sizes=np.array([5.0, 10.0, 20.0]),
                ...     size_legend=True,
                ... )
                >>> fig, ax, paths = glyph.plot()
                >>> bool(paths.get_sizes()[0] < paths.get_sizes()[-1])
                True
                >>> glyph.size_legend_artist is not None
                True

                ```
        """
        with self._rollback_options_on_error():
            self._merge_group_params(color, contour, classify)

            if ax is not None:
                self.ax = ax
                self.fig = _root_figure(ax)
            elif self.ax is None:
                self.fig, self.ax = self.create_figure_axes()
            ax = self.ax
            assert self.fig is not None
            opts = self.default_options

            if title is not None:
                opts["title"] = title
            opts.update(_resolve_colorbar(colorbar))
            draw_colorbar = (
                opts["add_colorbar"] if add_colorbar is None else add_colorbar
            )
            self.cbar = None
            self.category_legend = None

            marker_area = self._resolve_marker_area()

            if self.colors is not None:
                paths = ax.scatter(
                    self.x,
                    self.y,
                    c=self.colors,
                    s=marker_area,
                    marker=opts["marker"],
                    alpha=opts["alpha"],
                )
            elif self.values is None:
                paths = ax.scatter(
                    self.x,
                    self.y,
                    s=marker_area,
                    marker=opts["marker"],
                    color=opts["flat_color"],
                    alpha=opts["alpha"],
                )
            else:
                norm, cbar_kw, ticks = self._prepare_scalar_mapping(self.values)
                categorical = self._categorical
                if categorical is not None:
                    color_array, cmap = categorical["codes"], categorical["cmap"]
                else:
                    color_array, cmap = (
                        np.asarray(self.values),
                        resolve_colormap(opts["cmap"]),
                    )
                paths = ax.scatter(
                    self.x,
                    self.y,
                    c=color_array,
                    s=marker_area,
                    marker=opts["marker"],
                    cmap=cmap,
                    norm=norm,
                    vmin=None if norm else ticks[0],
                    vmax=None if norm else ticks[-1],
                    alpha=opts["alpha"],
                )
                if draw_colorbar:
                    if categorical is not None:
                        self.category_legend = self.create_categorical_legend(ax)
                    else:
                        self.cbar = self.create_color_bar(ax, paths, cbar_kw)

            if self.sizes is not None and opts["size_legend"]:
                if self.category_legend is not None:
                    ax.add_artist(self.category_legend)
                self.size_legend_artist = self._draw_size_legend(
                    ax, cast(np.ndarray, marker_area)
                )

            if opts["title"]:
                ax.set_title(opts["title"], fontsize=opts["title_size"])
            self._apply_axis_style(ax)

            return self.fig, ax, paths

    def _resolve_marker_area(self) -> float | np.ndarray:
        """Resolve the scatter `s` (marker area) for this glyph.

        Returns the per-point areas mapped from `sizes` when a `sizes`
        array was supplied (via `cleopatra.styling.styles.resolve_sizes`, honouring
        the `size_limits` / `size_scale` options), or the scalar
        `point_size` option when no `sizes` were given.

        Returns:
            float or np.ndarray: A scalar area (no `sizes`) or a per-point
                area array spanning `size_limits` monotonically in `sizes`.
        """
        if self.sizes is None:
            return float(self.default_options["point_size"])
        size_min, size_max = self.default_options["size_limits"]
        return resolve_sizes(
            self.sizes,
            size_min,
            size_max,
            scale=self.default_options["size_scale"],
        )

    def _draw_size_legend(self, ax: Axes, marker_area: np.ndarray) -> Legend:
        """Draw a size legend for the resolved per-point areas.

        Picks representative magnitudes (`size_legend_values`, or the min /
        median / max of `sizes` when unset), maps each to its plotted
        marker area by interpolating the already-computed `(sizes ->
        marker_area)` mapping (so the swatches match the points exactly),
        and hands them to `cleopatra.styling.styles.size_legend`.

        Args:
            ax: The axes to attach the legend to.
            marker_area: The per-point marker areas returned by
                `_resolve_marker_area`.

        Returns:
            matplotlib.legend.Legend: The size legend added to `ax`.
        """
        sizes = np.asarray(self.sizes, dtype=float)
        legend_values = self.default_options["size_legend_values"]
        if legend_values is None:
            legend_values = np.quantile(sizes, [0.0, 0.5, 1.0])
        legend_values = np.asarray(legend_values, dtype=float)
        order = np.argsort(sizes)
        legend_areas = np.interp(
            legend_values, sizes[order], np.asarray(marker_area)[order]
        )
        labels = [f"{v:g}" for v in legend_values]
        legend_kwargs = self.default_options["size_legend_kwargs"] or {}
        return size_legend(ax, legend_areas, labels, **legend_kwargs)

plot(ax=None, title=None, add_colorbar=None, colorbar=None, color=None, contour=None, classify=None) #

Draw the point cloud, colour- and/or size-mapping per point.

When values was supplied at construction, the colour scale, norm, ticks, and colorbar are resolved through _prepare_scalar_mapping, so vmin / vmax / levels / color_scale behave as for the other glyphs. With no values, a single-colour scatter is drawn and no colorbar is added.

The one exception is scheme="categorical": vmin / vmax / levels / color_scale are ignored (with a warning if set), and instead of a colorbar a disjoint_legend is drawn and stored on self.category_legend (self.cbar stays None). See Glyph._prepare_categorical_mapping.

When sizes was supplied, each marker's area is resolved from that magnitude via cleopatra.styling.styles.resolve_sizes (honouring size_limits / size_scale); otherwise the scalar point_size option is used for every point. Colour and size are independent, so a point can encode two quantities at once. If size_legend is truthy, a size legend is drawn via cleopatra.styling.styles.size_legend and stored on self.size_legend_artist.

Parameters:

Name Type Description Default
ax Axes | None

Axes to draw on. Falls back to the axes supplied at construction, otherwise a new figure/axes is created.

None
title str | None

Plot title. Overrides default_options["title"] when given.

None
add_colorbar bool | None

Override the add_colorbar option for this call — True draws the colorbar, False suppresses it (for shared-axes composition). Defaults to None, which keeps the value set at construction.

None
colorbar bool | ColorBar | None

Typed ColorBar spec (or True/False/None) for the colorbar's placement, caption, and sizing; resolved into the cbar_* options. A ColorBar/True also enables the bar and is sticky -- it persists into later plots, overriding a construction-time add_colorbar=False; an explicit add_colorbar= argument still wins the on/off decision.

None

Returns:

Type Description
tuple[Figure, Axes, PathCollection]

tuple[Figure, Axes, PathCollection]: The figure, the axes, and the PathCollection returned by scatter (the mappable for the coloured path).

Examples:

  • Uncoloured points return a PathCollection with no array:
    >>> import numpy as np
    >>> from cleopatra.glyphs.primitives.scatter_glyph import ScatterGlyph
    >>> glyph = ScatterGlyph(
    ...     np.array([0.0, 1.0]), np.array([0.0, 1.0])
    ... )
    >>> fig, ax, paths = glyph.plot()
    >>> paths.get_array() is None
    True
    
  • A title passed to plot overrides the default:
    >>> import numpy as np
    >>> from cleopatra.glyphs.primitives.scatter_glyph import ScatterGlyph
    >>> glyph = ScatterGlyph(
    ...     np.array([0.0, 1.0]), np.array([0.0, 1.0])
    ... )
    >>> fig, ax, paths = glyph.plot(title="Stations")
    >>> ax.get_title()
    'Stations'
    
  • Combine colour and size, with a size legend:
    >>> import numpy as np
    >>> from cleopatra.glyphs.primitives.scatter_glyph import ScatterGlyph
    >>> glyph = ScatterGlyph(
    ...     np.array([0.0, 1.0, 2.0]),
    ...     np.array([0.0, 1.0, 0.0]),
    ...     values=np.array([1.0, 2.0, 3.0]),
    ...     sizes=np.array([5.0, 10.0, 20.0]),
    ...     size_legend=True,
    ... )
    >>> fig, ax, paths = glyph.plot()
    >>> bool(paths.get_sizes()[0] < paths.get_sizes()[-1])
    True
    >>> glyph.size_legend_artist is not None
    True
    
Source code in src/cleopatra/glyphs/primitives/scatter_glyph.py
def plot(
    self,
    ax: Axes | None = None,
    title: str | None = None,
    add_colorbar: bool | None = None,
    colorbar: bool | ColorBar | None = None,
    color: ColorScaling | None = None,
    contour: Contour | None = None,
    classify: Classify | None = None,
) -> tuple[Figure, Axes, PathCollection]:
    """Draw the point cloud, colour- and/or size-mapping per point.

    When `values` was supplied at construction, the colour scale,
    norm, ticks, and colorbar are resolved through
    `_prepare_scalar_mapping`, so `vmin` / `vmax` / `levels` /
    `color_scale` behave as for the other glyphs. With no values,
    a single-colour scatter is drawn and no colorbar is added.

    The one exception is `scheme="categorical"`: `vmin` / `vmax` /
    `levels` / `color_scale` are ignored (with a warning if set), and
    instead of a colorbar a `disjoint_legend` is drawn and stored on
    `self.category_legend` (`self.cbar` stays `None`). See
    `Glyph._prepare_categorical_mapping`.

    When `sizes` was supplied, each marker's area is resolved from
    that magnitude via `cleopatra.styling.styles.resolve_sizes` (honouring
    `size_limits` / `size_scale`); otherwise the scalar `point_size`
    option is used for every point. Colour and size are independent,
    so a point can encode two quantities at once. If `size_legend` is
    truthy, a size legend is drawn via `cleopatra.styling.styles.size_legend`
    and stored on `self.size_legend_artist`.

    Args:
        ax: Axes to draw on. Falls back to the axes supplied at
            construction, otherwise a new figure/axes is created.
        title: Plot title. Overrides `default_options["title"]`
            when given.
        add_colorbar: Override the `add_colorbar` option for this call
            — True draws the colorbar, False suppresses it (for
            shared-axes composition). Defaults to None, which keeps the
            value set at construction.
        colorbar: Typed `ColorBar` spec (or `True`/`False`/`None`) for the
            colorbar's placement, caption, and sizing; resolved into the
            `cbar_*` options. A `ColorBar`/`True` also enables the bar and is
            **sticky** -- it persists into later plots, overriding a
            construction-time `add_colorbar=False`; an explicit
            `add_colorbar=` argument still wins the on/off decision.

    Returns:
        tuple[Figure, Axes, PathCollection]: The figure, the axes,
            and the `PathCollection` returned by `scatter` (the
            mappable for the coloured path).

    Examples:
        - Uncoloured points return a PathCollection with no array:
            ```python
            >>> import numpy as np
            >>> from cleopatra.glyphs.primitives.scatter_glyph import ScatterGlyph
            >>> glyph = ScatterGlyph(
            ...     np.array([0.0, 1.0]), np.array([0.0, 1.0])
            ... )
            >>> fig, ax, paths = glyph.plot()
            >>> paths.get_array() is None
            True

            ```
        - A title passed to plot overrides the default:
            ```python
            >>> import numpy as np
            >>> from cleopatra.glyphs.primitives.scatter_glyph import ScatterGlyph
            >>> glyph = ScatterGlyph(
            ...     np.array([0.0, 1.0]), np.array([0.0, 1.0])
            ... )
            >>> fig, ax, paths = glyph.plot(title="Stations")
            >>> ax.get_title()
            'Stations'

            ```
        - Combine colour and size, with a size legend:
            ```python
            >>> import numpy as np
            >>> from cleopatra.glyphs.primitives.scatter_glyph import ScatterGlyph
            >>> glyph = ScatterGlyph(
            ...     np.array([0.0, 1.0, 2.0]),
            ...     np.array([0.0, 1.0, 0.0]),
            ...     values=np.array([1.0, 2.0, 3.0]),
            ...     sizes=np.array([5.0, 10.0, 20.0]),
            ...     size_legend=True,
            ... )
            >>> fig, ax, paths = glyph.plot()
            >>> bool(paths.get_sizes()[0] < paths.get_sizes()[-1])
            True
            >>> glyph.size_legend_artist is not None
            True

            ```
    """
    with self._rollback_options_on_error():
        self._merge_group_params(color, contour, classify)

        if ax is not None:
            self.ax = ax
            self.fig = _root_figure(ax)
        elif self.ax is None:
            self.fig, self.ax = self.create_figure_axes()
        ax = self.ax
        assert self.fig is not None
        opts = self.default_options

        if title is not None:
            opts["title"] = title
        opts.update(_resolve_colorbar(colorbar))
        draw_colorbar = (
            opts["add_colorbar"] if add_colorbar is None else add_colorbar
        )
        self.cbar = None
        self.category_legend = None

        marker_area = self._resolve_marker_area()

        if self.colors is not None:
            paths = ax.scatter(
                self.x,
                self.y,
                c=self.colors,
                s=marker_area,
                marker=opts["marker"],
                alpha=opts["alpha"],
            )
        elif self.values is None:
            paths = ax.scatter(
                self.x,
                self.y,
                s=marker_area,
                marker=opts["marker"],
                color=opts["flat_color"],
                alpha=opts["alpha"],
            )
        else:
            norm, cbar_kw, ticks = self._prepare_scalar_mapping(self.values)
            categorical = self._categorical
            if categorical is not None:
                color_array, cmap = categorical["codes"], categorical["cmap"]
            else:
                color_array, cmap = (
                    np.asarray(self.values),
                    resolve_colormap(opts["cmap"]),
                )
            paths = ax.scatter(
                self.x,
                self.y,
                c=color_array,
                s=marker_area,
                marker=opts["marker"],
                cmap=cmap,
                norm=norm,
                vmin=None if norm else ticks[0],
                vmax=None if norm else ticks[-1],
                alpha=opts["alpha"],
            )
            if draw_colorbar:
                if categorical is not None:
                    self.category_legend = self.create_categorical_legend(ax)
                else:
                    self.cbar = self.create_color_bar(ax, paths, cbar_kw)

        if self.sizes is not None and opts["size_legend"]:
            if self.category_legend is not None:
                ax.add_artist(self.category_legend)
            self.size_legend_artist = self._draw_size_legend(
                ax, cast(np.ndarray, marker_area)
            )

        if opts["title"]:
            ax.set_title(opts["title"], fontsize=opts["title_size"])
        self._apply_axis_style(ax)

        return self.fig, ax, paths

Examples#

A flat colour (no value mapping)#

import numpy as np
from cleopatra.glyphs.primitives.scatter_glyph import ScatterGlyph

rng = np.random.default_rng(0)
x, y = rng.random(100), rng.random(100)

sg = ScatterGlyph(x, y, flat_color="navy", alpha=0.7)
fig, ax, paths = sg.plot(title="Flat-coloured points")

colors takes an explicit per-point sequence instead, the way BarGlyph takes colors= per category:

categories = rng.integers(0, 3, size=100)
palette = {0: "navy", 1: "crimson", 2: "forestgreen"}
sg = ScatterGlyph(x, y, colors=[palette[c] for c in categories])
fig, ax, paths = sg.plot(title="Explicit per-point colours")

Value-coloured points#

import numpy as np
from cleopatra.glyphs.primitives.scatter_glyph import ScatterGlyph

rng = np.random.default_rng(0)
x, y = rng.random(100), rng.random(100)
values = rng.random(100)

sg = ScatterGlyph(x, y, values=values)
fig, ax, paths = sg.plot(title="Coloured points")

Colour and size encoding two quantities#

import numpy as np
from cleopatra.glyphs.primitives.scatter_glyph import ScatterGlyph

rng = np.random.default_rng(0)
x, y = rng.random(50), rng.random(50)
values = rng.random(50)          # drives colour
sizes = rng.random(50) * 10      # drives marker area (independent of colour)

sg = ScatterGlyph(x, y, values=values, sizes=sizes, size_legend=True)
fig, ax, paths = sg.plot(title="Two encodings at once")

Composing onto shared axes (no per-glyph colorbar)#

fig, ax, paths = sg.plot(ax=ax, add_colorbar=False)