Skip to content

Maps (matplotlib)#

Map is the default backend's host: a matplotlib figure with a display CRS, one axes, and a list of layers it can re-order, hide and replace after they are drawn.

from digitalearth import Map

m = Map(crs=3857)
m.field(dataset, cmap="terrain")
m.points(stations, name="obs")
m.lines(rivers, column="discharge", width=1.5)
m.coastlines()
m.colorbar()
m.save("map.png")

colorbar() with no argument keys the most recent layer that is coloured by a value — a coastline, a basemap or a text label added after the data cannot take the key. Name a layer (colorbar("obs")) to key that one instead, and colorbars() keys every layer that has a key to show. The request is recorded on the layer, so the bar moves, hides and disappears with it.

Every input is reprojected to the display CRS through pyramids and drawn on a plain axes — there is no Cartopy, because the projection is applied to the data rather than to the axes. The rendering itself is cleopatra's: each builder assembles a glyph and hands the styling keywords straight to it, which is why cmap, levels, figsize and the cbar_* family are documented there rather than here.

What this tier is for#

Scientific field rendering and anything that has to come back as a file: rasters, contours, unstructured meshes, vector and flow fields, KDE, ensemble series and animations. It is the one tier installed without an extra, which is all that distinguishes it: digitalearth.interactive, digitalearth.web and digitalearth.three_d are peers, answering to the same method names wherever they can draw the same thing, and each owns what the others have no primitive for.

The layer list#

A builder returns the artist it drew and records a layer beside it, addressed by the name= you gave it (or a generated id). layer_ids lists them in draw order, and move_layer, remove_layer, replace_layer and set_visible work on that list afterwards, so a figure can be rearranged without being rebuilt. Layers sit in bands — underlay, reference, data, overlay — and a later call cannot slip under an earlier band, so a basemap stays under the data and a label stays over it however the calls were ordered.

figure_spec is the whole figure as a value: its panels, their layers, the view each is drawn in and the furniture anchored to them. That description is what the other tiers read back, and it is the reason a layer records its recipe (via) rather than the method that drew it.

What field accepts#

A pyramids Dataset, a path or URL to a raster — and a bare 2-D NumPy array, for the "just show me this grid" case. Such a layer is not georeferenced: it is placed at its own indices, nothing is reprojected, and no georeferenced layer may share the figure with it (a basemap, a coastline and a reprojected raster are all in the display CRS, so mixing them is refused rather than drawn with one of them as an invisible speck). Nodata in a bare array is a masked array, since there is no sidecar to carry a no_data_value. Anything else is refused by name, saying what the call takes.

The domain the ramp spans#

robust=True clips the colour limits to the 2nd and 98th percentile of the band, xarray-style, so a single outlier stops flattening the rest of the field.

center= states the value a diverging scale is built around — zero for an anomaly, a difference or a trend, and whatever the reference is otherwise. The limits are symmetrised on it, so one unit of departure is one step of colour on either side, and the ramp becomes a diverging one centred there: its lightest colour lands on the centre and the two arms darken away from it. color_scale="midpoint", midpoint= is the other spelling, and a different request — it keeps the data's own asymmetric limits and moves the colour centre instead. Both get the diverging ramp.

m.field(anomaly, center=0, robust=True)
m.field(anomaly, color_scale="midpoint", midpoint=0)   # asymmetric limits, colour centred on zero

The ramp is only substituted where no colormap was named: cmap= is always what draws. And the centre has to be inside the data — a ramp centred outside it draws every value in one arm, which is worse than the sequential ramp it would replace — so for a centre the band does not straddle the diverging ramp is declined, the resolved colormap is kept, and the decline is logged at WARNING naming the centre and the range it measured.

Only the ramp is declined. center= is cleopatra's own keyword and it symmetrises the colour limits whether the band straddles the centre or not, so an off-band centre still widens the colour domain to reach it: measured, a band running 12 to 88 drawn with center=0 goes through limits (-88.0, 88.0) instead of (12.0, 88.0), leaving the data in the top 43% of the ramp. The color_scale="midpoint", midpoint= spelling has no such effect — it keeps the data's own limits — so an off-band centre there costs nothing but the ramp. Either way the remedy the warning names is the same: move the centre inside the data, or drop it.

The colours a ramp cannot place#

Three values fall outside a colour ramp, and a field render takes a colour for each: missing= for a cell with no value, under= for a value below vmin and over= for one above vmax. They are stated on the call and folded onto the layer's colormap, so they also reach the figure's description — the layer's colour Scale carries them, so a backend that read them back could colour the same values the same way. None does yet: the static style schema declares missing/over/under and the interactive one declares none of the three, so the round trip that works today is this tier reading back its own figure.

m.field(dataset, vmin=0, vmax=100, missing="#cccccc", under="#0000ff", over="#ff0000")

Stating one is opt-in and leaves the rest alone. Without missing= a nodata cell keeps matplotlib's default — fully transparent, so the gap shows through — and without over= a clipped value keeps the ramp's own end colour, which is why a field clipped at vmax reads the same as one that really peaks there. A colormap you built yourself keeps the extremes it already carried; only the ones named in the call are restated.

Small multiples on one scale#

facet(stack) draws a raster stack — a multi-band Dataset, a DatasetCollection or a list of frames — as one panel per frame, and resolves the colour scale once over the whole stack: the frames are warped into the display CRS and measured together, so every panel colours one value the same way, and a named scheme is cut into one set of class edges for all of them. col_wrap folds the row, col/labels title the panels, and one colorbar spans them. Each panel is an ordinary Map, returned for further drawing.

from digitalearth.static import facet

fig, maps = facet(monthly_rain, crs=4326, col="month", labels=months, col_wrap=4, cbar_label="mm")
for m in maps:
    m.coastlines()
fig.savefig("rain.png")

digitalearth.static.panels.figure.facet(stack, *, col=None, col_wrap=None, labels=None, kind='field', band=DEFAULT_BAND, crs=3857, globe=False, figsize=None, colorbar=True, cbar_label=None, **style) #

Draw a raster stack as small multiples — one panel per frame — on one shared colour scale.

Small multiples are read against each other, so the scale is resolved once over the whole stack rather than per panel: the frames are warped into the display CRS and measured together, vmin/vmax become the stack's range, and a named scheme is cut into one set of class edges over every frame — scheme="categorical" included, whose class codes are pooled over the stack so one code is one colour on every panel. Each panel is an ordinary :class:Map from :func:grid, so its frame is a described layer and the panel takes a basemap, coastlines or a graticule like any other map. One colorbar spans the panels.

Parameters:

Name Type Description Default
stack Any

A multi-band Dataset (one panel per band), a DatasetCollection (one per member), or a sequence of Dataset frames. Anything else is refused by name — facet opens nothing, so a path or URL is read with Dataset.read_file() first.

required
col str | None

What the panels are, as each title names it — "time" titles them "time = 0", "time = 1", … None (default) says "band" for a multi-band dataset and "frame" otherwise.

None
col_wrap int | None

Panels per row; the rest wrap onto further rows, and the unused slots of the last row are hidden. None (default) puts every panel on one row.

None
labels Sequence[Any] | None

One label per panel for its title, in place of the index (1-based band numbers for a multi-band dataset, 0-based positions otherwise). Any iterable, a generator included — it is spent into a list before the panels are counted.

None
kind str

The render — "field" (default), "pcolormesh", "contourf" or "contour". The two contour renders need explicit levels=.

'field'
band int

The band each frame of a collection or sequence is drawn from. Ignored for a multi-band dataset, whose bands are the panels.

DEFAULT_BAND
crs Any

Display CRS of every panel.

3857
globe bool

Draw every panel on a globe frame.

False
figsize tuple[float, float] | None

Figure size in inches; None uses the matplotlib default.

None
colorbar bool

Draw one colorbar spanning the panels (default True). It is left off, with a logged warning, when no frame holds a finite value: the shared scale is then the (0, 1) fallback a colour domain takes for an unmeasurable stack, and a bar labelled 0-1 over a figure where no cell holds a value reads as data that is not there.

True
cbar_label str | None

The colorbar's label.

None
**style Any

Styling for every panel, forwarded to the render (cmap, vmin, vmax, scheme, k, levels, …). A vmin/vmax given here is the shared scale instead of the stack's range. k counts the classes a named scheme cuts — five when it is left unset or passed as None — and is refused wherever it cannot do that rather than forwarded as a no-op: with no scheme, beside an explicit list of class edges, under scheme="categorical" (a code is its own class), and when it is not a whole number of at least one (k=2.7 and k="4" were silently truncated and coerced).

{}

Returns:

Type Description
tuple[Figure, list[Map]]

(fig, maps) — the figure and one Map per panel, in panel order.

Raises:

Type Description
ValueError

when stack is none of the three shapes it takes (a path, a mapping, a frame that is not a Dataset) or has no frames, col_wrap is below 1, labels does not number the panels, kind is not one of the four, a contour kind has no levels, or k cannot count classes as given (see **style). Also from the classifier, when a named scheme cannot cut the pooled values: a stack with no spread (every cell the same), one with no finite cell at all, or — under scheme="categorical" — pooled values that are not class codes (a non-integer value, or more distinct codes than a key can show).

Examples:

  • Four frames on one row, one scale, titled by month:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import matplotlib.pyplot as plt
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalearth.static import facet
    >>> geo = GeoReference(geo=(0.0, 1.0, 0.0, 4.0, 0.0, -1.0), epsg=4326)
    >>> frames = [
    ...     Dataset.from_array(arr=np.full((4, 4), 10.0 * i), geo_ref=geo, no_data_value=-9999.0)
    ...     for i in range(4)
    ... ]
    >>> fig, maps = facet(frames, crs=4326, col="month", labels=["Jan", "Feb", "Mar", "Apr"])
    >>> [m.ax.get_title() for m in maps]
    ['month = Jan', 'month = Feb', 'month = Mar', 'month = Apr']
    >>> {m.layers[-1][1].get_clim() for m in maps}
    {(0.0, 30.0)}
    >>> plt.close(fig)  # one figure holds every panel, so one close is the whole facet
    
  • Wrap onto rows of three; the last row's spare slots are hidden:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import matplotlib.pyplot as plt
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalearth.static import facet
    >>> geo = GeoReference(geo=(0.0, 1.0, 0.0, 4.0, 0.0, -1.0), epsg=4326)
    >>> frames = [
    ...     Dataset.from_array(arr=np.full((4, 4), float(i)), geo_ref=geo, no_data_value=-9999.0)
    ...     for i in range(4)
    ... ]
    >>> fig, maps = facet(frames, crs=4326, col_wrap=3, colorbar=False)
    >>> maps[0].ax.get_subplotspec().get_geometry()[:2], sum(not ax.get_visible() for ax in fig.axes)
    ((2, 3), 2)
    >>> plt.close(fig)
    
  • A categorical stack cuts its classes over every frame, so the second frame's codes carry on the palette rather than restarting it — code 1 is its first colour and code 3 its third:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import matplotlib.pyplot as plt
    >>> import numpy as np
    >>> from matplotlib.colors import to_hex
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalearth.static import facet
    >>> geo = GeoReference(geo=(0.0, 1.0, 0.0, 2.0, 0.0, -1.0), epsg=4326)
    >>> early = Dataset.from_array(
    ...     arr=np.array([[1.0, 1.0], [2.0, 2.0]]), geo_ref=geo, no_data_value=-9999.0
    ... )
    >>> late = Dataset.from_array(
    ...     arr=np.array([[3.0, 3.0], [4.0, 4.0]]), geo_ref=geo, no_data_value=-9999.0
    ... )
    >>> fig, maps = facet([early, late], crs=4326, scheme="categorical", colorbar=False)
    >>> art = [m.layers[-1][1] for m in maps]
    >>> [to_hex(art[0].cmap(art[0].norm(code))) for code in (1.0, 2.0)]
    ['#1f77b4', '#ff7f0e']
    >>> [to_hex(art[1].cmap(art[1].norm(code))) for code in (3.0, 4.0)]
    ['#2ca02c', '#d62728']
    >>> [m.layers[-1][1].get_clim() for m in maps]
    [(0.5, 4.5), (0.5, 4.5)]
    >>> plt.close(fig)
    
  • A stack where every cell is nodata still draws its panels, but no colorbar: the figure holds the two panels and nothing else, where a measurable stack of the same shape holds a third axes for the bar. k without a scheme is refused outright, since it would classify nothing:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import matplotlib.pyplot as plt
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalearth.static import facet
    >>> geo = GeoReference(geo=(0.0, 1.0, 0.0, 2.0, 0.0, -1.0), epsg=4326)
    >>> blank = [
    ...     Dataset.from_array(
    ...         arr=np.full((2, 2), -9999.0), geo_ref=geo, no_data_value=-9999.0
    ...     )
    ...     for _ in range(2)
    ... ]
    >>> fig, maps = facet(blank, crs=4326)
    >>> len(maps), len(fig.axes)
    (2, 2)
    >>> maps[0].layers[-1][1].get_clim()
    (0.0, 1.0)
    >>> try:
    ...     facet(blank, crs=4326, k=4)
    ... except ValueError as error:
    ...     print(str(error)[:69])
    facet(k=4) counts the classes a scheme cuts, so it classifies nothing
    >>> plt.close(fig)
    
See Also

grid: the panels alone, for a layout that draws something different on each. shared_colorbar: the spanning bar on its own.

Source code in src/digitalearth/static/panels/figure.py
def facet(
    stack: Any,
    *,
    col: str | None = None,
    col_wrap: int | None = None,
    labels: Sequence[Any] | None = None,
    kind: str = "field",
    band: int = DEFAULT_BAND,
    crs: Any = 3857,
    globe: bool = False,
    figsize: tuple[float, float] | None = None,
    colorbar: bool = True,
    cbar_label: str | None = None,
    **style: Any,
) -> tuple[Figure, list[Map]]:
    """Draw a raster stack as small multiples — one panel per frame — on one shared colour scale.

    Small multiples are read against each other, so the scale is resolved **once over the whole stack**
    rather than per panel: the frames are warped into the display CRS and measured together, ``vmin``/``vmax``
    become the stack's range, and a named ``scheme`` is cut into one set of class edges over every frame —
    ``scheme="categorical"`` included, whose class codes are pooled over the stack so one code is one colour
    on every panel. Each panel is an ordinary :class:`Map` from :func:`grid`, so its frame is a described
    layer and the panel takes a basemap, coastlines or a graticule like any other map. One colorbar spans the
    panels.

    Args:
        stack: A multi-band ``Dataset`` (one panel per band), a ``DatasetCollection`` (one per member), or
            a sequence of ``Dataset`` frames. Anything else is refused by name — ``facet`` opens nothing, so
            a path or URL is read with ``Dataset.read_file()`` first.
        col: What the panels are, as each title names it — ``"time"`` titles them ``"time = 0"``,
            ``"time = 1"``, … ``None`` (default) says ``"band"`` for a multi-band dataset and ``"frame"``
            otherwise.
        col_wrap: Panels per row; the rest wrap onto further rows, and the unused slots of the last row are
            hidden. ``None`` (default) puts every panel on one row.
        labels: One label per panel for its title, in place of the index (``1``-based band numbers for a
            multi-band dataset, ``0``-based positions otherwise). Any iterable, a generator included — it is
            spent into a list before the panels are counted.
        kind: The render — ``"field"`` (default), ``"pcolormesh"``, ``"contourf"`` or ``"contour"``. The two
            contour renders need explicit ``levels=``.
        band: The band each frame of a collection or sequence is drawn from. Ignored for a multi-band
            dataset, whose bands are the panels.
        crs: Display CRS of every panel.
        globe: Draw every panel on a globe frame.
        figsize: Figure size in inches; ``None`` uses the matplotlib default.
        colorbar: Draw one colorbar spanning the panels (default ``True``). It is left off, with a logged
            warning, when no frame holds a finite value: the shared scale is then the ``(0, 1)`` fallback a
            colour domain takes for an unmeasurable stack, and a bar labelled 0-1 over a figure where no
            cell holds a value reads as data that is not there.
        cbar_label: The colorbar's label.
        **style: Styling for every panel, forwarded to the render (``cmap``, ``vmin``, ``vmax``, ``scheme``,
            ``k``, ``levels``, …). A ``vmin``/``vmax`` given here is the shared scale instead of the stack's
            range. ``k`` counts the classes a **named** ``scheme`` cuts — five when it is left unset or
            passed as ``None`` — and is refused wherever it cannot do that rather than forwarded as a
            no-op: with no ``scheme``, beside an explicit list of class edges, under
            ``scheme="categorical"`` (a code is its own class), and when it is not a whole number of at
            least one (``k=2.7`` and ``k="4"`` were silently truncated and coerced).

    Returns:
        ``(fig, maps)`` — the figure and one ``Map`` per panel, in panel order.

    Raises:
        ValueError: when ``stack`` is none of the three shapes it takes (a path, a mapping, a frame that is
            not a ``Dataset``) or has no frames, ``col_wrap`` is below 1, ``labels`` does not number the
            panels, ``kind`` is not one of the four, a contour ``kind`` has no ``levels``, or ``k`` cannot
            count classes as given (see ``**style``). Also from the classifier, when a named ``scheme``
            cannot cut the pooled values: a stack with no spread (every cell the same), one with no finite
            cell at all, or — under ``scheme="categorical"`` — pooled values that are not class codes (a
            non-integer value, or more distinct codes than a key can show).

    Examples:
        - Four frames on one row, one scale, titled by month:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import matplotlib.pyplot as plt
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalearth.static import facet
            >>> geo = GeoReference(geo=(0.0, 1.0, 0.0, 4.0, 0.0, -1.0), epsg=4326)
            >>> frames = [
            ...     Dataset.from_array(arr=np.full((4, 4), 10.0 * i), geo_ref=geo, no_data_value=-9999.0)
            ...     for i in range(4)
            ... ]
            >>> fig, maps = facet(frames, crs=4326, col="month", labels=["Jan", "Feb", "Mar", "Apr"])
            >>> [m.ax.get_title() for m in maps]
            ['month = Jan', 'month = Feb', 'month = Mar', 'month = Apr']
            >>> {m.layers[-1][1].get_clim() for m in maps}
            {(0.0, 30.0)}
            >>> plt.close(fig)  # one figure holds every panel, so one close is the whole facet

            ```
        - Wrap onto rows of three; the last row's spare slots are hidden:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import matplotlib.pyplot as plt
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalearth.static import facet
            >>> geo = GeoReference(geo=(0.0, 1.0, 0.0, 4.0, 0.0, -1.0), epsg=4326)
            >>> frames = [
            ...     Dataset.from_array(arr=np.full((4, 4), float(i)), geo_ref=geo, no_data_value=-9999.0)
            ...     for i in range(4)
            ... ]
            >>> fig, maps = facet(frames, crs=4326, col_wrap=3, colorbar=False)
            >>> maps[0].ax.get_subplotspec().get_geometry()[:2], sum(not ax.get_visible() for ax in fig.axes)
            ((2, 3), 2)
            >>> plt.close(fig)

            ```
        - A categorical stack cuts its classes over every frame, so the second frame's codes carry on the
          palette rather than restarting it — code 1 is its first colour and code 3 its third:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import matplotlib.pyplot as plt
            >>> import numpy as np
            >>> from matplotlib.colors import to_hex
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalearth.static import facet
            >>> geo = GeoReference(geo=(0.0, 1.0, 0.0, 2.0, 0.0, -1.0), epsg=4326)
            >>> early = Dataset.from_array(
            ...     arr=np.array([[1.0, 1.0], [2.0, 2.0]]), geo_ref=geo, no_data_value=-9999.0
            ... )
            >>> late = Dataset.from_array(
            ...     arr=np.array([[3.0, 3.0], [4.0, 4.0]]), geo_ref=geo, no_data_value=-9999.0
            ... )
            >>> fig, maps = facet([early, late], crs=4326, scheme="categorical", colorbar=False)
            >>> art = [m.layers[-1][1] for m in maps]
            >>> [to_hex(art[0].cmap(art[0].norm(code))) for code in (1.0, 2.0)]
            ['#1f77b4', '#ff7f0e']
            >>> [to_hex(art[1].cmap(art[1].norm(code))) for code in (3.0, 4.0)]
            ['#2ca02c', '#d62728']
            >>> [m.layers[-1][1].get_clim() for m in maps]
            [(0.5, 4.5), (0.5, 4.5)]
            >>> plt.close(fig)

            ```
        - A stack where every cell is nodata still draws its panels, but no colorbar: the figure holds the
          two panels and nothing else, where a measurable stack of the same shape holds a third axes for the
          bar. ``k`` without a ``scheme`` is refused outright, since it would classify nothing:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import matplotlib.pyplot as plt
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalearth.static import facet
            >>> geo = GeoReference(geo=(0.0, 1.0, 0.0, 2.0, 0.0, -1.0), epsg=4326)
            >>> blank = [
            ...     Dataset.from_array(
            ...         arr=np.full((2, 2), -9999.0), geo_ref=geo, no_data_value=-9999.0
            ...     )
            ...     for _ in range(2)
            ... ]
            >>> fig, maps = facet(blank, crs=4326)
            >>> len(maps), len(fig.axes)
            (2, 2)
            >>> maps[0].layers[-1][1].get_clim()
            (0.0, 1.0)
            >>> try:
            ...     facet(blank, crs=4326, k=4)
            ... except ValueError as error:
            ...     print(str(error)[:69])
            facet(k=4) counts the classes a scheme cuts, so it classifies nothing
            >>> plt.close(fig)

            ```

    See Also:
        grid: the panels alone, for a layout that draws something different on each.
        shared_colorbar: the spanning bar on its own.
    """
    if kind not in _FACET_KINDS:
        raise ValueError(
            f"facet(kind={kind!r}) is not a render; use one of {sorted(_FACET_KINDS)}"
        )
    style = _checked_classes(style)
    # Every panel argument — the frames, the grid shape, the titles — is answered here, before any axes
    # exist, so a refused call leaves no figure open.
    plan = _PanelPlan.resolve(stack, band, col=col, col_wrap=col_wrap, labels=labels)
    fig, slots = grid(plan.nrows, plan.ncols, crs=crs, globe=globe, figsize=figsize)
    maps, spare = slots[: plan.count], slots[plan.count :]
    for empty in spare:
        empty.ax.set_visible(False)
    values = _stack_values(maps[0], plan.frames, plan.bands)
    # The one reduction of the stack: it fills the shared vmin/vmax below and decides the colorbar.
    measured = measure_clim(values)
    shared = _shared_style(values, style, kind, measured)
    method, fixed = _FACET_KINDS[kind]
    drawn = None
    for panel, frame, frame_band, title in plan.panels(maps):
        getattr(panel, method)(frame, band=frame_band, **fixed, **shared)
        # The builders hand back the panel rather than the artist since ST-20, so the mappable the shared
        # bar is keyed to is asked for by name — through `Map.artist`, the public accessor that replaced
        # the read of the renderer's private record here (L9). `layer_ids` lists only layers that *were*
        # drawn — a skip is forgotten again — so an off-limb panel contributes nothing (there is no id to
        # pass, and `artist()` would refuse the id of a layer that drew nothing) and the first panel that
        # drew something still wins, exactly as the artist-or-`None` pick did.
        artist = panel.artist(panel.layer_ids[-1]) if panel.layer_ids else None
        if drawn is None and artist is not None:
            drawn = artist
        panel.set_title(title)
    if colorbar and drawn is not None and measured is None:
        # The shared scale fell back to the (0, 1) a `Scale` uses for an unmeasurable domain, so a bar here
        # would label the figure 0-1 while no cell on it holds a value at all. The panels are legitimate —
        # an empty frame is a real datum — and `facet` has no `strict` to refuse under, so only the bar goes.
        logger.warning(
            "facet(): no frame holds a finite value, so the stack has no colour scale to key; the "
            "colorbar is left off rather than drawn over the (0, 1) fallback limits"
        )
    elif colorbar:
        shared_colorbar(fig, drawn, maps, label=cbar_label)
    return fig, maps

Hatching a mask#

contours(..., filled=True, hatches=[...]) gives each band between levels a hatch pattern, and fill=False leaves the bands uncoloured so only the hatching draws — the usual way to mark a significance or uncertainty mask over another field without spending its colours. legend() on such a layer keys the bands it marks by their pattern; hatch_color= colours the strokes on the map and in the key alike.

labels= names the bands levels= declares — one label per band, the same count as hatches= — and the labels of the bands the map does not mark are dropped alongside their rows. The count therefore comes from the call and not from the raster, so a labels= written against one reading of the field keeps working when the data stops reaching a band (or starts reaching another).

m.field(trend, cmap="RdBu_r")
m.contours(p_value, levels=[0, 0.05, 1], filled=True, hatches=["///", ""], fill=False, name="sig")
m.legend("sig", labels=["p < 0.05", "not significant"])  # two declared bands; only the hatched one is keyed

A layer that marks none of its bands — every pattern empty, or every hatched band past where the data reaches — has no rows to key, so legend() draws nothing rather than an empty framed box, and logs legend(): layer 'sig' marks none of its 4 hatched bands, … at WARNING. The guide is still recorded on the layer, so the figure says what was asked for.

Overlays computed from the globe itself#

nightshade(when) shades the night side of the day/night terminator at one instant, and tissot() draws Tissot's indicatrices — circles of one ground radius, shown as the projection distorts them. cleopatra computes both in lon/lat (cleopatra.basemap.solar) and they are projected into the display CRS through pyramids, so a Web Mercator map shows the polar night reaching the pole and the indicatrices swelling toward it. On a globe the night side is filled only where it faces the viewer, and a circle on the far side is left out.

from datetime import datetime, timezone

m = Map(crs=3857)
m.nightshade(datetime(2026, 6, 21, 12, tzinfo=timezone.utc), alpha=0.3)
m.nightshade("2026-06-21T12:00:00", refraction=-6.0, alpha=0.15)  # civil twilight
m.tissot(edgecolor="crimson")                                      # a world grid of 500 km circles

digitalearth.static.map.Map #

Bases: RasterMixin, VectorMixin, DecorationMixin, InsetMixin, ProjectionMixin, AnimationMixin, GeoLayerBase

A geospatial :class:~digitalearth.static.core.scene.Scene that reprojects to a display CRS.

The tier's workhorse, and a composition rather than a class with methods of its own: every capability lives in one of the six mixins under digitalearth.static.builders — RasterMixin (fields, composites, spaghetti), VectorMixin (points, polygons, unstructured, flow, u/v fields), DecorationMixin (text, annotate, basemap, Natural-Earth layers), InsetMixin (inset, mark_extent), ProjectionMixin (extent, domain, globe frame, save/show) and AnimationMixin (animate, rotate) — and map.py only lists them. tests/static/test_map_composition.py pins that MRO, so a seventh mixin fails it until the list is updated.

Every data builder returns Self, so calls chain (m.field(ds).coastlines().colorbar()), and the matplotlib artist a layer drew is reached by name through :meth:~digitalearth.static.core.scene.Scene.artist — never through the renderer's private record.

Parameters:

Name Type Description Default
crs Any

Display CRS as an EPSG int / string / CRS (anything Dataset.to_crs accepts). Default 3857.

3857
domain Any

A registered region name ("europe", "africa", …) or an explicit (west, south, east, north) bbox in EPSG:4326. Stored, not applied: constructing with one does not frame the axes, and it is not validated either — it becomes the fallback a bare :meth:~digitalearth.static.builders.projection.ProjectionMixin.set_domain call resolves, and the domain the panel's Viewport carries. None (the default) leaves the view to fit the data.

None
ax Any

Existing axes to draw on (a new figure/axes is created when None). One axes holds one map; two maps sharing one is unsupported (see :class:~digitalearth.static.core.scene.Scene).

None
fig Any

Figure owning ax. Taken from ax (its root figure) when only ax is given.

None
figsize tuple[float, float]

New-figure size in inches when one is created; (8, 8) by default.

(8, 8)
globe bool

Draw the projection boundary/graticule and clip layers to it (an orthographic globe).

False
strict bool

When True a layer whose data cannot be placed in the display CRS raises :class:~digitalearth.base.crs.OffLimbError instead of being skipped with a warning.

False

Attributes:

Name Type Description
crs

The display CRS every layer is reprojected to, exactly as it was passed.

domain

The configured domain (or None). Never rewritten by a framing call.

strict bool

Whether a layer that would draw nothing raises instead of being skipped.

Examples:

  • Create a map in Web Mercator and read its display CRS; it describes nothing yet:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth.static import Map
    >>> m = Map(crs=3857)
    >>> m.crs
    3857
    >>> m.layers
    []
    >>> m.close()
    
  • Render a reprojected raster and chain decoration onto it — each builder hands the map back, so the layer ids accumulate in draw order:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from pyramids.dataset import Dataset
    >>> from digitalearth.static import Map
    >>> ds = Dataset.read_file("examples/data/acc4000.tif")
    >>> m = Map(crs=ds.epsg)          # same CRS -> no reprojection
    >>> m.field(ds).coastlines(name="coast") is m
    True
    >>> m.layer_ids
    ['raster-1', 'coast']
    >>> m.close()
    
  • A domain is remembered rather than applied: the axes is framed only once set_domain() asks for it, and the attribute survives the framing:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth.static import Map
    >>> m = Map(crs=4326, domain="europe")
    >>> [float(v) for v in m.ax.get_xlim()]
    [0.0, 1.0]
    >>> _ = m.set_domain()
    >>> [float(v) for v in m.ax.get_xlim()], m.domain
    ([-25.0, 45.0], 'europe')
    >>> m.close()
    
Source code in src/digitalearth/static/map.py
class Map(
    RasterMixin,
    VectorMixin,
    DecorationMixin,
    InsetMixin,
    ProjectionMixin,
    AnimationMixin,
    GeoLayerBase,
):
    """A geospatial :class:`~digitalearth.static.core.scene.Scene` that reprojects to a display CRS.

    The tier's workhorse, and a **composition rather than a class with methods of its own**: every
    capability lives in one of the six mixins under `digitalearth.static.builders` — `RasterMixin` (fields,
    composites, spaghetti), `VectorMixin` (points, polygons, unstructured, flow, u/v fields),
    `DecorationMixin` (text, annotate, basemap, Natural-Earth layers), `InsetMixin` (`inset`,
    `mark_extent`), `ProjectionMixin` (extent, domain, globe frame, save/show) and `AnimationMixin`
    (`animate`, `rotate`) — and `map.py` only lists them. `tests/static/test_map_composition.py` pins that
    MRO, so a seventh mixin fails it until the list is updated.

    **Every data builder returns `Self`, so calls chain** (`m.field(ds).coastlines().colorbar()`), and the
    matplotlib artist a layer drew is reached by name through :meth:`~digitalearth.static.core.scene.Scene.artist`
    — never through the renderer's private record.

    Args:
        crs: Display CRS as an EPSG int / string / CRS (anything ``Dataset.to_crs`` accepts). Default 3857.
        domain: A registered region name (`"europe"`, `"africa"`, …) or an explicit
            `(west, south, east, north)` bbox in EPSG:4326. **Stored, not applied**: constructing with one
            does not frame the axes, and it is not validated either — it becomes the fallback a bare
            :meth:`~digitalearth.static.builders.projection.ProjectionMixin.set_domain` call resolves, and the
            `domain` the panel's `Viewport` carries. `None` (the default) leaves the view to fit the data.
        ax: Existing axes to draw on (a new figure/axes is created when ``None``). One axes holds one map;
            two maps sharing one is unsupported (see :class:`~digitalearth.static.core.scene.Scene`).
        fig: Figure owning ``ax``. Taken from `ax` (its root figure) when only `ax` is given.
        figsize: New-figure size in inches when one is created; `(8, 8)` by default.
        globe: Draw the projection boundary/graticule and clip layers to it (an orthographic globe).
        strict: When ``True`` a layer whose data cannot be placed in the display CRS raises
            :class:`~digitalearth.base.crs.OffLimbError` instead of being skipped with a warning.

    Attributes:
        crs: The display CRS every layer is reprojected to, exactly as it was passed.
        domain: The configured domain (or ``None``). Never rewritten by a framing call.
        strict: Whether a layer that would draw nothing raises instead of being skipped.

    Examples:
        - Create a map in Web Mercator and read its display CRS; it describes nothing yet:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth.static import Map
            >>> m = Map(crs=3857)
            >>> m.crs
            3857
            >>> m.layers
            []
            >>> m.close()

            ```
        - Render a reprojected raster and chain decoration onto it — each builder hands the map back, so
            the layer ids accumulate in draw order:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from pyramids.dataset import Dataset
            >>> from digitalearth.static import Map
            >>> ds = Dataset.read_file("examples/data/acc4000.tif")
            >>> m = Map(crs=ds.epsg)          # same CRS -> no reprojection
            >>> m.field(ds).coastlines(name="coast") is m
            True
            >>> m.layer_ids
            ['raster-1', 'coast']
            >>> m.close()

            ```
        - A domain is remembered rather than applied: the axes is framed only once `set_domain()` asks for
            it, and the attribute survives the framing:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth.static import Map
            >>> m = Map(crs=4326, domain="europe")
            >>> [float(v) for v in m.ax.get_xlim()]
            [0.0, 1.0]
            >>> _ = m.set_domain()
            >>> [float(v) for v in m.ax.get_xlim()], m.domain
            ([-25.0, 45.0], 'europe')
            >>> m.close()

            ```
    """

    def draw_figure(self, figure: FigureSpec) -> Self:
        """Draw a figure into this map, bringing it from whatever it showed before.

        The 2-D counterpart of the 3-D tier's ``draw_figure``, with one difference in the plumbing: this
        tier's :meth:`~digitalearth.static.core.scene.Scene._change` derives a candidate's sources from
        ``self._sources`` (filtered to the tree), not from the incoming figure, so the figure's own sources
        are installed here first — otherwise :meth:`~digitalearth.static.render.renderer.Renderer.apply` would have
        nothing to open. The 3-D tier replays its incoming figure's sources directly and needs no such step.

        **The two titles land in their own slots, and the round trip is idempotent.** This tier describes a
        heading in two places — the panel's title, which `set_title` paints on the axes, and the figure's
        heading, which is its `suptitle` — so each is restored to the one it was described from. Measured on
        a figure carrying both: described `('rainfall, 2020', 'January')` as
        `(figure.title, figure.panels[0].title)`, restored to the same pair as
        `(fig.get_suptitle(), ax.get_title())`, and redescribed unchanged; `to_dict()` of the figure before
        and after is equal, and equal again on a third pass.

        **The heading is figure-wide, so it is restored only onto a figure this map owns.** A `grid` panel
        is built on an axes :func:`~digitalearth.static.panels.figure.grid` laid out, and every panel of that grid
        shares one figure — so writing the described heading through ``Figure.suptitle`` from one panel
        reaches the whole figure and its siblings, which then describe the incoming heading as their own.
        Measured on a two-panel grid headed `'grid heading'`, drawing a description headed `'INCOMING'`
        into `maps[1]`: before the guard `fig.get_suptitle()` became `'INCOMING'` and `maps[0]` described
        `'INCOMING'`; now both still read `'grid heading'` and the declined heading is named in a
        ``UserWarning``. A map that made its own figure — `Map(crs=4326)`, and so every
        :meth:`from_figure` round trip — restores it as before. The panel's title is not guarded, because
        `set_title` paints the axes and that is panel-local.

        **A title is written only when the incoming figure carries one**, so drawing an untitled figure does
        not blank a heading the map already had. "Carries one" is decided by
        :meth:`~digitalearth.static.core.scene.Scene._recorded_title`, the same normaliser `set_title` and
        `grid(suptitle=)` use: a `FigureSpec` refuses `""` but accepts `"   "`, and a whitespace heading is
        the request "no heading" rather than a heading made of spaces. It used to be painted and then
        described as none, so a figure written down and read back drew a different picture (R2-L5). The layers are reconciled, not merely added — that part
        really does bring the map from whatever it showed before.

        One asymmetry is worth knowing, because the two titles live in different places. The figure's
        heading is on the figure and always survives. The panel's title is painted on the **axes**, and a
        cleopatra glyph clears the axes on a scene's *first* render — so on a map that has not drawn a glyph
        yet, an axes title set beforehand is wiped by the incoming figure's first layer while the scene goes
        on describing it. Measured, drawing an untitled figure into a map titled
        `('stale heading', 'stale panel')`: a map that had **already** drawn a layer reports
        `('stale heading', 'stale panel')` from `(fig.get_suptitle(), ax.get_title())`, while a map that had
        drawn nothing reports `('stale heading', '')` — and `figure_spec` still says `'stale panel'` for
        both, because the panel's title is held on the scene rather than read back off the axes.

        Args:
            figure: The figure to draw. Its one panel's :class:`~digitalearth.base.spec.Viewport` set the
                display CRS/domain/globe at construction; here its layers are drawn in order, each title it
                carries is restored to its own slot, and any `set_bounds` framing on the panel's view is
                reapplied (a fit-to-data view carries no bounds and is left to re-fit). An ``object:``
                (in-memory) source is replayed in process, so the scene that registered it must stay alive
                until this returns; a path or URL source has no such constraint.

        Returns:
            This map, so the call chains.

        Raises:
            KeyError: when a layer names a kind this tier does not draw, or a recipe it does not know —
                `"the static tier does not draw 'terrain' layers; it draws [...]"`.
            OffLimbError: when a layer's data cannot be placed and the map is ``strict``.

        Warns:
            UserWarning: when the incoming figure carries a heading and this map does not own its figure —
                naming the heading that was not drawn, and the ``fig.suptitle`` call that would draw it.

        Examples:
            - A figure drawn into a fresh map comes back describing exactly what it described, each title
                in its own place, and stays there on a second pass:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from digitalearth.base.spec import FigureSpec
                >>> from digitalearth.static import Map
                >>> first = Map(crs=4326)
                >>> _ = first.field("examples/data/acc4000.tif")
                >>> _ = first.set_title("January")
                >>> _ = first.fig.suptitle("rainfall, 2020")
                >>> stored = first.figure_spec.to_dict()
                >>> first.close()
                >>> second = Map(crs=4326).draw_figure(FigureSpec.from_dict(stored))
                >>> second.fig.get_suptitle(), second.ax.get_title()
                ('rainfall, 2020', 'January')
                >>> second.figure_spec.to_dict() == stored
                True
                >>> second.close()

                ```
            - A figure that carries no title of its own does not blank the headings already on the map —
                and the panel title survives on the axes because this map had already drawn a layer:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from digitalearth.base.spec import FigureSpec
                >>> from digitalearth.static import Map
                >>> blank = Map(crs=4326)
                >>> _ = blank.field("examples/data/acc4000.tif")
                >>> untitled = FigureSpec.from_dict(blank.figure_spec.to_dict())
                >>> blank.close()
                >>> m = Map(crs=4326)
                >>> _ = m.field("examples/data/acc4000.tif")
                >>> _ = m.set_title("stale panel")
                >>> _ = m.fig.suptitle("stale heading")
                >>> _ = m.draw_figure(untitled)
                >>> m.fig.get_suptitle(), m.ax.get_title()
                ('stale heading', 'stale panel')
                >>> m.close()

                ```
            - On a map that has drawn **nothing** yet, the first layer's render clears the axes and takes a
                pre-existing axes title with it, while the description keeps it:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from digitalearth.base.spec import FigureSpec
                >>> from digitalearth.static import Map
                >>> blank = Map(crs=4326)
                >>> _ = blank.field("examples/data/acc4000.tif")
                >>> untitled = FigureSpec.from_dict(blank.figure_spec.to_dict())
                >>> blank.close()
                >>> m = Map(crs=4326)
                >>> _ = m.set_title("stale panel")
                >>> _ = m.draw_figure(untitled)
                >>> m.ax.get_title(), m.figure_spec.panels[0].title
                ('', 'stale panel')
                >>> m.close()

                ```
            - A kind this tier has no drawer for is refused by name, and the map is left as it was:
                ```python
                >>> import copy
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from digitalearth.base.spec import FigureSpec
                >>> from digitalearth.static import Map
                >>> source = Map(crs=4326)
                >>> _ = source.field("examples/data/acc4000.tif")
                >>> stored = copy.deepcopy(source.figure_spec.to_dict())
                >>> source.close()
                >>> stored["layers"]["layers"][0]["kind"] = "terrain"
                >>> m = Map(crs=4326)
                >>> try:
                ...     m.draw_figure(FigureSpec.from_dict(stored))
                ... except KeyError as error:
                ...     print(str(error).split(";")[0].strip('"'))
                the static tier does not draw 'terrain' layers
                >>> m.layer_ids
                []
                >>> m.close()

                ```
        """
        # Normalise recipe names before drawing, so a figure the web or interactive tier described draws here:
        # a foreign recipe is retargeted to this tier's own, and the field drawer fills the style a portable
        # figure omits from its own defaults. A same-tier figure already knows every recipe, so this is a no-op.
        from digitalearth.static.render.renderer import retarget_via

        figure = retarget_via(figure)
        self._sources = dict(figure.sources)
        self._change(figure)
        # The layer diff does not re-read either title, so both are set here — each into the slot it was
        # described from. This tier describes two: the **panel's** title, which `set_title` paints on the
        # axes (ST-18), and the **figure's** heading, which is its `suptitle` (M4). Restoring them through
        # one `set_title` — `figure.title or figure.panels[0].title` — put the heading on the axes and
        # dropped the panel's title with it, so the round trip was not even idempotent. Measured on a
        # one-panel grid carrying both: described `('rainfall, 2020', 'January')` as
        # `(figure.title, panels[0].title)`, restored `('', 'rainfall, 2020')` as
        # `(fig.get_suptitle(), ax.get_title())`, and redescribed `(None, 'rainfall, 2020')`.
        if figure.panels[0].title:
            self.set_title(figure.panels[0].title)
        # Only onto a figure this map owns. `Figure.suptitle` is figure-level, and in a `grid` every panel
        # shares one figure, so an unguarded restore is a per-panel call rewriting the whole figure's
        # heading: measured on a two-panel grid headed `'grid heading'`, drawing a description headed
        # `'INCOMING'` into `maps[1]` left `fig.get_suptitle()` as `'INCOMING'`, and `maps[0]` — never
        # drawn into — then described `'INCOMING'` as its own (R2-M1). The panel's title above is
        # unguarded because `set_title` paints the **axes**, which is panel-local.
        # Through `_recorded_title`, like `set_title` and `grid(suptitle=)`: a `FigureSpec` refuses `""`
        # but accepts `"   "`, so whitespace is the blank spelling that reaches this tier, and the
        # `if figure.title:` guard let it through to be painted and then described as no heading (R2-L5).
        heading = self._recorded_title(figure.title)
        if heading is not None:
            if self._owns_fig:
                self.fig.suptitle(heading)
            else:
                warnings.warn(
                    f"draw_figure() did not restore the figure heading {heading!r}: this map was "
                    f"built on an axes somebody else laid out, and the heading belongs to the figure "
                    f"that axes is in, which its siblings share. Call "
                    f"`map.fig.suptitle({heading!r})` yourself if the whole figure should carry it.",
                    UserWarning,
                    stacklevel=2,
                )
        # The view's explicit framing is not a layer, so `_change` does not carry it: restore any `set_bounds`
        # region from the panel's viewport, or a map framed on a subregion replays showing the full data
        # extent. `set_bounds` reprojects a `Bounds` in any CRS, so a figure another tier described frames
        # correctly too. A fit-to-data view (no bounds) is left to re-fit.
        bounds = getattr(figure.panels[0].view, "bounds", None)
        if bounds is not None:
            self.set_bounds(bounds)
        return self

    @classmethod
    def from_figure(cls, figure: FigureSpec, **scene_kwargs: Any) -> Self:
        """Build a map and draw a figure into it — the round trip the description seam exists for.

        A map describes itself with :attr:`~digitalearth.static.core.scene.Scene.figure_spec`, the description
        survives ``to_dict()``/``from_dict()``, and this draws it again. :func:`digitalearth.api.to_backend`
        dispatches here for ``backend="static"``.

        Args:
            figure: The figure to draw.
            **scene_kwargs: Passed to the constructor — ``figsize``, ``strict``, ``ax``/``fig``; a ``crs``,
                ``domain`` or ``globe`` here overrides the one the figure's viewport carries.

        Returns:
            The map, with every layer drawn.

        Raises:
            KeyError: from :meth:`draw_figure`, when a layer names a kind this tier does not draw or a
                recipe it does not know. The map has been constructed by then, so its figure is left open.
            OffLimbError: from :meth:`draw_figure`, when a layer's data cannot be placed and `strict=True`
                was passed through `**scene_kwargs`.

        Examples:
            - A figure a map describes draws again into a fresh map, carrying its display CRS:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from pyramids.dataset import Dataset
                >>> from digitalearth.static import Map
                >>> ds = Dataset.read_file("examples/data/acc4000.tif")
                >>> first = Map(crs=ds.epsg)
                >>> _ = first.field(ds)
                >>> second = Map.from_figure(first.figure_spec)
                >>> second.layer_ids == first.layer_ids
                True
                >>> first.close()
                >>> second.close()

                ```
        """
        view = figure.panels[0].view
        kwargs: dict[str, Any] = {
            "domain": getattr(view, "domain", None),
            "globe": bool(getattr(view, "globe", False)),
        }
        crs = getattr(view, "crs", None)
        if crs is not None:
            kwargs["crs"] = crs
        scene = cls(**{**kwargs, **scene_kwargs})
        scene.draw_figure(figure)
        return scene

layer_ids property #

The ids of the layers this scene draws, in draw order, bottom first.

Returns:

Type Description
list[str]

One id per described layer. A layer the caller named carries that name, with surrounding

list[str]

whitespace removed; an unnamed one gets a generated id counting the layers of its kind —

list[str]

scatter, text, scatter, text is points-1, points-2, text-1, text-2, listed in draw

list[str]

order. It counted the figure until review R2-M10, while this sentence already said otherwise

list[str]

(review R2-L2).

figure_spec property #

What the scene draws, as data: its layers, their sources and the view.

Returns:

Name Type Description
A FigureSpec

class:~digitalearth.base.spec.FigureSpec with one panel, :data:PANEL_ID, whose layers are

FigureSpec

the tree in draw order and whose sources are what each builder was given.

FigureSpec

It carries the plain half of the caller's styling and no more: a keyword passed through

FigureSpec

**opts is described when :func:~digitalearth.base.spec._serial.travels_in_a_figure accepts

FigureSpec

it, and held beside the layer

FigureSpec

(:attr:LayerRecord.opts) when it does not — so a figure drawn on another scene draws the

FigureSpec

described vmin, alpha, color or title, and the engine's defaults in place of a

FigureSpec

dash tuple, a per-pixel array or a Normalize.

FigureSpec

A scene built from data already in memory can be handed straight to a renderer, but not written:

FigureSpec

to_dict() refuses an object: source, because a reference into this process's memory would

FigureSpec

be unreadable everywhere else. Give a builder a path or a URL to get a figure that can be stored.

viewport property #

Where the map is looking, as a value — including the region it has been framed on.

Returns:

Name Type Description
Viewport

The view :class:~digitalearth.static.builders.base.GeoLayerBase builds from the display CRS, the

Viewport

declared domain and the globe flag, carrying the region the last framing call asked for when

Viewport

there has been one. A view holds a region or a named domain, never both, so a map that was

Viewport

built with a domain and then framed reports the rectangle it is actually showing — which is

what Viewport

meth:~digitalearth.base.spec.viewport.Viewport.framed does, and what keeps a stale

Viewport

domain from sitting beside a live frame.

Viewport

Before order 26 this always answered None for bounds: a map framed by its own data

Viewport

described itself as unframed, which is why the basemap coverage guard had to record the axes

Viewport

extent on its own layer instead of reading it off the panel.

Viewport

A frame recorded in a CRS the map no longer draws in is not reported, and is not converted

Viewport

either. A rotation swaps the display CRS between frames, and the region a previous frame was

Viewport

globally framed on is often one the next projection cannot show at all — so the honest answer

Viewport

there is that nothing has framed this view yet, rather than a rectangle reprojected across a

Viewport

limb or a refusal raised from a property.

field(data, *, band=DEFAULT_BAND, cmap=None, limits=None, opacity=None, name=None, visible=True, **kwargs) #

Render a raster band as a coloured field — a pixel grid (ArrayGlyph kind="imshow").

A bare 2-D numpy array is drawn too — the "just show me this grid" case, which was StaticGlyph.plot(arr) until that class was deleted and which nothing took over (#343). Such a layer is not georeferenced, and that is not a detail:

  • its coordinates are its own indices — the column index on x, the row index on y, cell centres on the integers and the image covering [-0.5, cols - 0.5] x [-0.5, rows - 0.5], with the first row drawn at the top as matplotlib draws every array;
  • nothing is reprojected. An array declares no CRS, so :attr:crs says nothing about where it is and no warp is attempted — :meth:~digitalearth.static.builders.base.GeoLayerBase._reproject hands it straight back and the layer's Source carries crs=None;
  • no georeferenced layer may share the figure. A basemap, a coastline, a graticule and a reprojected raster are all placed in the display CRS, so mixing one in is refused by :meth:~digitalearth.static.core.scene.Scene._require_one_placement rather than drawn with the array as an invisible speck beside it;
  • a globe frame is refused for the same reason, at this call;
  • :meth:~digitalearth.static.builders.projection.ProjectionMixin.set_bounds still frames the figure, and its bounds are read in the display CRS — which for such a figure means array indices. set_bounds(None) fits the array, and set_bounds((0, 0, 4, 3)) frames columns 0-4 and rows 0-3. Geographic bounds would frame empty axes, and there is nothing to tell them apart by.

Nodata in a bare array is a masked array. There is no sidecar to carry a no_data_value, so np.ma.masked_equal(grid, -9999) (or NaN in the values) is how a cell says it has none, and those cells are left blank.

Parameters:

Name Type Description Default
data Any

A pyramids Dataset, a bare 2-D numpy array, or a path or URL to a raster (reprojected to :attr:crs first, except for the array — see above). Only a path-backed layer can be written down.

required
band int

1-based band index to draw — the Core keyword, named here rather than reached through **kwargs so it is written down (#324, #332).

DEFAULT_BAND
cmap str | None

Colormap name, or None (default) to resolve one from the variable via auto_style. The Core keyword, named here rather than reached through **kwargs (#324, #332).

None
limits tuple[float, float] | None

The colour domain as (vmin, vmax); None (default) auto-scales. The spelling :data:~digitalearth.base.spec.encoding.CHANNELS and the Core contract use, so the same channel is written the same way on every tier (#332); it reaches ArrayGlyph as its own vmin/vmax.

None
opacity float | None

How opaque the field is, in [0, 1]. The Core spelling; None (default) sets no opacity at all, which is not the same as 1.0. matplotlib's own alpha is what it arrives as (#332).

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the figure is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the drawing (#327).

True
**kwargs Any

Forwarded to :meth:_field, which documents the named ones (levels, add_colorbar, default_cmap, draw_band, zorder). Anything left over is the caller's own engine styling, split between the layer's description and the scene (see the class docstring). scheme and k classify the band into discrete classes, as on the vector layers: a named scheme ("quantiles", "equal_interval", "fisher_jenks", …) cut into k classes, or a list of explicit class edges. The classes are drawn as steps, published as :attr:last_breaks and on the layer's colour encoding, and keyed by :meth:colorbar (ticks on the edges) or :meth:legend (one swatch per class). Cut points that coincide — tied values under "quantiles" — merge, so fewer than k classes can be drawn; nodata cells fall in no class and stay blank. Explicit edges narrower than the data leave cells outside them, and those are painted the colormap's end colours — the first and last classes' colours when there are two or more classes — while the key lists only the given ranges, so span the data's range when that matters. Without scheme the field is a continuous ramp, and k alone is ignored — it counts the classes a named scheme cuts, so it does nothing without one. scheme="categorical" is for a band of integer class codes (land cover, zone ids): each distinct code becomes its own class, coloured from the same categorical palette the vector layers use (cmap picks the palette), keyed by :meth:legend with one swatch per code and published as the layer's categories rather than class edges — so :attr:last_breaks stays None and a colorbar is refused in favour of the legend.

Five more of those keywords decide the colour domain and what falls outside it, and they are declared in STATIC_STYLE_SCHEMA (ST-3, ST-10) rather than named in this signature. Measured, STATIC_STYLE_SCHEMA carries all five while INTERACTIVE_STYLE_SCHEMA carries none of them:

  • robust=True takes the limits from the band's 2nd and 98th percentile instead of its min and max, so one outlier stops flattening the rest of the field — xarray's spelling, honoured by cleopatra. How much it helps depends on how large a share of the band the outliers are, so the figure it reaches is grid-dependent: measured on a 10x10 grid of zeros with two cells at 1000, the upper limit comes out at about 20 rather than 1000, while on a 5x5 grid the same two cells are 8% of the band — past the 2% tail — and the limits stay (0.0, 1000.0). An explicit vmin/vmax wins over it.
  • center= is the value a diverging scale is built around. cleopatra symmetrises the limits on it, and this tier supplies the diverging ramp — built from the resolved colormap's own two ends — but only when the caller named no cmap of their own and the band straddles the centre. A centre outside the band keeps the sequential ramp and says so at WARNING, because one arm would otherwise hold every value — the ramp is what is declined there, not the centre: cleopatra symmetrises the limits either way, so an off-band centre also widens the domain to reach it (measured: a band running 12 to 88 with center=0 draws through (-88.0, 88.0)).
  • missing=, over= and under= colour what the ramp cannot place: a nodata cell, a value above the upper limit and one below the lower. They are this tier's own keywords (:class:FieldColors), folded onto the drawn colormap and onto the scale the layer publishes, so they survive into the figure's description and come back on a re-read. This tier is the only one that reads them back so far. Unstated, each leaves the colormap's own treatment alone — which is matplotlib's transparent "bad" and the ramp's end colours.
{}

Returns:

Type Description
Self

This map, so a figure reads as one expression — measured:

Self

type(m.field(ds).set_title("Flow").colorbar()).__name__ is 'Map' (ST-20). **This is the

Self

canonical note the other builders point at.**

Self

The decoration methods chain too, as of round 1's L6: coastlines, borders, land,

Self

ocean, lakes, rivers, text, annotate, nightshade, tissot and basemap are all

Self

annotated -> Self, so m.field(ds).coastlines().set_title("Flow") is a Map the whole way

Self

(measured). The deliberate -> Any carve-outs are enumerated here, and a new one belongs

Self

in this list rather than beside its own method: stock_img hands back its backdrop artist, and

Self

meth:~digitalearth.static.builders.vector.VectorMixin.quiverkey hands back matplotlib's

Self

QuiverKey. For both, the return is the point of the call. quiverkey is the further case:

Self

it draws onto the axes while registering no layer, so — measured on a map carrying one

Self

quiver layer — layer_ids is ['vectors-1'] either side of it and

Self

m.artist("quiverkey") raises KeyError, the reference arrow being furniture that explains a

Self

layer rather than a layer of its own.

Self

It returned the AxesImage until ST-20, and that was a silent divergence from this

Self

package's own contract: Method (in digitalearth.base.contract) declares

Self

returns = "self" as its default, so every builder the Core names has always been

Self

declared chainable — and this tier handed back the engine's object instead. That contract,

Self

not the other tiers, is what the change answers to: the web and interactive builders do

Self

answer that way (field, points, choropleth and lines are annotated

Self

-> Self on both), but the 3-D tier does not — measured by an AST scan of

Self

src/digitalearth/three_d/, all seven of its data builders are annotated -> Any:

Self

terrain, volume, isosurface, point_cloud, vectors, extruded_polygons and globe.

Self

Each hands back the pyvista.Actor its drawer produced, or None when the drawer declined

Self

the layer. So this tier was not the only one returning the engine's object, and the 3-D row is

Self

still open.

Self

tests/test_contract_names.py holds the tiers to the Core's keywords and call shape and

Self

does not measure return values, which is why the divergence went unnoticed: the same line

Self

chained on two tiers and raised AttributeError on this one. The -> Self promise is

Self

checked by tests/test_mixin_contract.py instead, which requires both halves — the

Self

annotation, and a body that really hands back self.

Self

The artist is still reachable, through

Self

meth:~digitalearth.static.core.scene.Scene.artist: m.artist() hands back what this call used

Self

to return — the layer drawn last — and m.artist(layer_id) names one, so name= is the way

Self

to keep a stable handle on a layer's artist in a figure of several.

Self

An off-limb layer is now read from the figure rather than from a None. A layer whose

Self

data lies entirely outside what the display CRS shows draws nothing and is absent from

Self

attr:~digitalearth.static.core.scene.Scene.layer_ids, so

Self

meth:~digitalearth.static.core.scene.Scene.artist refuses it by name — the same answer every other

Self

tier gives, and testable without a return value. An off-limb draw still renders an empty frame

Self

rather than raising.

Raises:

Type Description
TypeError

when data is neither a raster, an array nor a reference to one — refused by name (see :meth:_field).

ValueError

when data is an array and the map is drawn on a globe frame, or when it is an array of any rank but two; or from ArrayGlyph for a styling keyword it does not accept; or for a scheme that cannot classify the band — an unknown name, k below one, or, under scheme="categorical", a band holding non-integer values, more than :data:~digitalearth.base.raster_classes.MAX_RASTER_CATEGORIES distinct codes, or no valid cell.

Examples:

  • Draw a bare grid, and read back where its image was placed:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import Map
    >>> with Map() as canvas:
    ...     _ = canvas.field(np.arange(12.0).reshape(3, 4), name="grid")
    ...     canvas.artist("grid").get_extent()
    [-0.5, 3.5, -0.5, 2.5]
    
  • A diverging field: the centre asks for symmetric limits and a diverging ramp, and the extreme colours say what a clipped value and a nodata cell are drawn as:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from matplotlib.colors import to_hex
    >>> from digitalearth.static import Map
    >>> anomaly = np.array([[-3.0, 0.0], [4.0, 8.0]])
    >>> with Map() as m:
    ...     _ = m.field(anomaly, name="anom", center=0.0, over="#ff0000", missing="#cccccc")
    ...     m.artist("anom").get_clim()
    ...     m.artist("anom").get_cmap().name
    ...     to_hex(m.artist("anom").get_cmap().get_over())
    (-8.0, 8.0)
    'viridis-diverging'
    '#ff0000'
    
  • A centre the band does not straddle keeps the sequential ramp rather than drawing one arm of a diverging one, and says so in the log:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import Map
    >>> rainfall = np.array([[12.0, 40.0], [50.0, 88.0]])
    >>> with Map() as m:
    ...     _ = m.field(rainfall, name="rain", center=0.0)
    ...     m.artist("rain").get_cmap().name
    'viridis'
    
  • Classify a raster into four equal-interval classes, and read back the edges it was cut at:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from pyramids.dataset import Dataset
    >>> from digitalearth.static import Map
    >>> ds = Dataset.read_file("examples/data/acc4000.tif")
    >>> with Map(crs=ds.epsg) as m:
    ...     _ = m.field(ds, scheme="equal_interval", k=4)
    ...     m.last_breaks
    [0.0, 22.0, 44.0, 66.0, 88.0]
    
  • Draw a band of class codes as categories, and read the key's labels — one per code:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import Map
    >>> landcover = np.array([[1.0, 1.0, 2.0], [3.0, 3.0, 2.0]])
    >>> with Map() as m:
    ...     _ = m.field(landcover, scheme="categorical")
    ...     _ = m.legend()
    ...     [label.get_text() for label in m.ax.get_legend().get_texts()]
    ['1', '2', '3']
    
  • A band of fractional values is a magnitude, so the categorical scheme refuses it:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import Map
    >>> with Map() as m:
    ...     m.field(np.array([[0.5, 1.0]]), scheme="categorical")  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: scheme='categorical' needs integer class codes ...
    
Source code in src/digitalearth/static/builders/raster.py
def field(
    self,
    data: Any,
    *,
    band: int = DEFAULT_BAND,
    cmap: str | None = None,
    limits: tuple[float, float] | None = None,
    opacity: float | None = None,
    name: str | None = None,
    visible: bool = True,
    **kwargs: Any,
) -> Self:
    """Render a raster band as a coloured field — a pixel grid (``ArrayGlyph`` ``kind="imshow"``).

    **A bare 2-D numpy array is drawn too** — the "just show me this grid" case, which was
    ``StaticGlyph.plot(arr)`` until that class was deleted and which nothing took over (#343). Such a
    layer is **not georeferenced**, and that is not a detail:

    * its coordinates are its **own indices** — the column index on x, the row index on y, cell centres
      on the integers and the image covering ``[-0.5, cols - 0.5] x [-0.5, rows - 0.5]``, with the first
      row drawn at the **top** as matplotlib draws every array;
    * **nothing is reprojected.** An array declares no CRS, so :attr:`crs` says nothing about where it
      is and no warp is attempted — :meth:`~digitalearth.static.builders.base.GeoLayerBase._reproject` hands
      it straight back and the layer's `Source` carries ``crs=None``;
    * **no georeferenced layer may share the figure.** A basemap, a coastline, a graticule and a
      reprojected raster are all placed in the display CRS, so mixing one in is refused by
      :meth:`~digitalearth.static.core.scene.Scene._require_one_placement` rather than drawn with the array
      as an invisible speck beside it;
    * **a globe frame is refused** for the same reason, at this call;
    * :meth:`~digitalearth.static.builders.projection.ProjectionMixin.set_bounds` still frames the figure,
      and its ``bounds`` are read in the display CRS — which for such a figure means *array indices*.
      ``set_bounds(None)`` fits the array, and ``set_bounds((0, 0, 4, 3))`` frames columns 0-4 and rows
      0-3. Geographic bounds would frame empty axes, and there is nothing to tell them apart by.

    **Nodata in a bare array is a masked array.** There is no sidecar to carry a ``no_data_value``, so
    ``np.ma.masked_equal(grid, -9999)`` (or ``NaN`` in the values) is how a cell says it has none, and
    those cells are left blank.

    Args:
        data: A pyramids ``Dataset``, a bare 2-D numpy array, or a path or URL to a raster
            (reprojected to :attr:`crs` first, except for the array — see above). Only a path-backed
            layer can be written down.
        band: 1-based band index to draw — the Core keyword, named here rather than reached through
            ``**kwargs`` so it is written down (#324, #332).
        cmap: Colormap name, or ``None`` (default) to resolve one from the variable via ``auto_style``.
            The Core keyword, named here rather than reached through ``**kwargs`` (#324, #332).
        limits: The colour domain as ``(vmin, vmax)``; ``None`` (default) auto-scales. The spelling
            :data:`~digitalearth.base.spec.encoding.CHANNELS` and the Core contract use, so the same
            channel is written the same way on every tier (#332); it reaches ``ArrayGlyph`` as its own
            ``vmin``/``vmax``.
        opacity: How opaque the field is, in ``[0, 1]``. The Core spelling; ``None`` (default) sets no
            opacity at all, which is not the same as ``1.0``. matplotlib's own ``alpha`` is what it
            arrives as (#332).
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the figure is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden, so a switcher reading the figure agrees with the drawing (#327).
        **kwargs: Forwarded to :meth:`_field`, which documents the named ones (``levels``,
            ``add_colorbar``, ``default_cmap``, ``draw_band``, ``zorder``). Anything
            left over is the caller's own engine styling, split between the layer's description and
            the scene (see the class docstring). ``scheme`` and ``k`` classify the band into discrete
            classes, as on the vector layers: a named scheme (``"quantiles"``, ``"equal_interval"``,
            ``"fisher_jenks"``, …) cut into ``k`` classes, or a list of explicit class edges. The
            classes are drawn as steps, published as :attr:`last_breaks` and on the layer's colour
            encoding, and keyed by :meth:`colorbar` (ticks on the edges) or :meth:`legend` (one swatch
            per class). Cut points that coincide — tied values under ``"quantiles"`` — merge, so fewer
            than ``k`` classes can be drawn; nodata cells fall in no class and stay blank. Explicit edges
            narrower than the data leave cells outside them, and those are painted the colormap's end
            colours — the first and last classes' colours when there are two or more classes — while
            the key lists only the given ranges, so span the data's range when that matters. Without
            ``scheme`` the field is a continuous ramp, and ``k`` alone is ignored — it counts the classes
            a named scheme cuts, so it does nothing without one. ``scheme="categorical"`` is for a band of
            integer class codes (land cover, zone ids): each distinct code becomes its own class,
            coloured from the same categorical palette the vector layers use (``cmap`` picks the
            palette), keyed by :meth:`legend` with one swatch per code and published as the layer's
            categories rather than class edges — so :attr:`last_breaks` stays ``None`` and a
            colorbar is refused in favour of the legend.

            Five more of those keywords decide the **colour domain** and what falls outside it, and
            they are declared in `STATIC_STYLE_SCHEMA` (ST-3, ST-10) rather than named in this
            signature. Measured, `STATIC_STYLE_SCHEMA` carries all five while
            `INTERACTIVE_STYLE_SCHEMA` carries none of them:

            * ``robust=True`` takes the limits from the band's 2nd and 98th percentile instead of its
              min and max, so one outlier stops flattening the rest of the field — xarray's spelling,
              honoured by cleopatra. How much it helps depends on how large a share of the band the
              outliers are, so the figure it reaches is grid-dependent: measured on a **10x10** grid
              of zeros with two cells at 1000, the upper limit comes out at about ``20`` rather than
              ``1000``, while on a 5x5 grid the same two cells are 8% of the band — past the 2% tail
              — and the limits stay ``(0.0, 1000.0)``. An explicit ``vmin``/``vmax`` wins over it.
            * ``center=`` is the value a diverging scale is built around. cleopatra symmetrises the
              limits on it, and this tier supplies the diverging **ramp** — built from the resolved
              colormap's own two ends — but only when the caller named no ``cmap`` of their own and
              the band straddles the centre. A centre outside the band keeps the sequential ramp and
              says so at ``WARNING``, because one arm would otherwise hold every value — the *ramp* is
              what is declined there, not the centre: cleopatra symmetrises the limits either way, so an
              off-band centre also widens the domain to reach it (measured: a band running ``12`` to
              ``88`` with ``center=0`` draws through ``(-88.0, 88.0)``).
            * ``missing=``, ``over=`` and ``under=`` colour what the ramp cannot place: a nodata cell,
              a value above the upper limit and one below the lower. They are this tier's own keywords
              (:class:`FieldColors`), folded onto the drawn colormap *and* onto the scale the layer
              publishes, so they survive into the figure's description and come back on a re-read.
              This tier is the only one that reads them back so far.
              Unstated, each leaves the colormap's own treatment alone — which is matplotlib's
              transparent "bad" and the ramp's end colours.

    Returns:
        This map, so a figure reads as one expression — measured:
        ``type(m.field(ds).set_title("Flow").colorbar()).__name__`` is ``'Map'`` (ST-20). **This is the
        canonical note the other builders point at.**

        **The decoration methods chain too**, as of round 1's L6: `coastlines`, `borders`, `land`,
        `ocean`, `lakes`, `rivers`, `text`, `annotate`, `nightshade`, `tissot` and `basemap` are all
        annotated `-> Self`, so `m.field(ds).coastlines().set_title("Flow")` is a `Map` the whole way
        (measured). **The deliberate `-> Any` carve-outs are enumerated here**, and a new one belongs
        in this list rather than beside its own method: `stock_img` hands back its backdrop artist, and
        :meth:`~digitalearth.static.builders.vector.VectorMixin.quiverkey` hands back matplotlib's
        ``QuiverKey``. For both, the return *is* the point of the call. `quiverkey` is the further case:
        it draws onto the axes while registering **no layer**, so — measured on a map carrying one
        ``quiver`` layer — `layer_ids` is `['vectors-1']` either side of it and
        ``m.artist("quiverkey")`` raises `KeyError`, the reference arrow being furniture that explains a
        layer rather than a layer of its own.

        It returned the ``AxesImage`` until ST-20, and that was a silent divergence from this
        package's own contract: `Method` (in `digitalearth.base.contract`) declares
        ``returns = "self"`` as its *default*, so every builder the Core names has always been
        declared chainable — and this tier handed back the engine's object instead. That contract,
        not the other tiers, is what the change answers to: the web and interactive builders do
        answer that way (``field``, ``points``, ``choropleth`` and ``lines`` are annotated
        ``-> Self`` on both), but the **3-D tier does not** — measured by an AST scan of
        `src/digitalearth/three_d/`, all **seven** of its data builders are annotated `-> Any`:
        `terrain`, `volume`, `isosurface`, `point_cloud`, `vectors`, `extruded_polygons` and `globe`.
        Each hands back the ``pyvista.Actor`` its drawer produced, or ``None`` when the drawer declined
        the layer. So this tier was not the only one returning the engine's object, and the 3-D row is
        still open.
        ``tests/test_contract_names.py`` holds the tiers to the Core's keywords and call shape and
        does not measure return values, which is why the divergence went unnoticed: the same line
        chained on two tiers and raised ``AttributeError`` on this one. The ``-> Self`` promise is
        checked by ``tests/test_mixin_contract.py`` instead, which requires both halves — the
        annotation, and a body that really hands back ``self``.

        **The artist is still reachable**, through
        :meth:`~digitalearth.static.core.scene.Scene.artist`: ``m.artist()`` hands back what this call used
        to return — the layer drawn last — and ``m.artist(layer_id)`` names one, so ``name=`` is the way
        to keep a stable handle on a layer's artist in a figure of several.

        **An off-limb layer is now read from the figure rather than from a ``None``.** A layer whose
        data lies entirely outside what the display CRS shows draws nothing and is **absent from**
        :attr:`~digitalearth.static.core.scene.Scene.layer_ids`, so
        :meth:`~digitalearth.static.core.scene.Scene.artist` refuses it by name — the same answer every other
        tier gives, and testable without a return value. An off-limb draw still renders an empty frame
        rather than raising.

    Raises:
        TypeError: when `data` is neither a raster, an array nor a reference to one — refused by name
            (see :meth:`_field`).
        ValueError: when `data` is an array and the map is drawn on a globe frame, or when it is an
            array of any rank but two; or from ``ArrayGlyph`` for a styling keyword it does not accept;
            or for a ``scheme`` that cannot classify the band — an unknown
            name, ``k`` below one, or, under ``scheme="categorical"``, a band holding non-integer values,
            more than :data:`~digitalearth.base.raster_classes.MAX_RASTER_CATEGORIES` distinct codes, or
            no valid cell.

    Examples:
        - Draw a bare grid, and read back where its image was placed:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import Map
            >>> with Map() as canvas:
            ...     _ = canvas.field(np.arange(12.0).reshape(3, 4), name="grid")
            ...     canvas.artist("grid").get_extent()
            [-0.5, 3.5, -0.5, 2.5]

            ```
        - A diverging field: the centre asks for symmetric limits *and* a diverging ramp, and the
          extreme colours say what a clipped value and a nodata cell are drawn as:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from matplotlib.colors import to_hex
            >>> from digitalearth.static import Map
            >>> anomaly = np.array([[-3.0, 0.0], [4.0, 8.0]])
            >>> with Map() as m:
            ...     _ = m.field(anomaly, name="anom", center=0.0, over="#ff0000", missing="#cccccc")
            ...     m.artist("anom").get_clim()
            ...     m.artist("anom").get_cmap().name
            ...     to_hex(m.artist("anom").get_cmap().get_over())
            (-8.0, 8.0)
            'viridis-diverging'
            '#ff0000'

            ```
        - A centre the band does not straddle keeps the sequential ramp rather than drawing one arm
          of a diverging one, and says so in the log:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import Map
            >>> rainfall = np.array([[12.0, 40.0], [50.0, 88.0]])
            >>> with Map() as m:
            ...     _ = m.field(rainfall, name="rain", center=0.0)
            ...     m.artist("rain").get_cmap().name
            'viridis'

            ```
        - Classify a raster into four equal-interval classes, and read back the edges it was cut at:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from pyramids.dataset import Dataset
            >>> from digitalearth.static import Map
            >>> ds = Dataset.read_file("examples/data/acc4000.tif")
            >>> with Map(crs=ds.epsg) as m:
            ...     _ = m.field(ds, scheme="equal_interval", k=4)
            ...     m.last_breaks
            [0.0, 22.0, 44.0, 66.0, 88.0]

            ```
        - Draw a band of class codes as categories, and read the key's labels — one per code:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import Map
            >>> landcover = np.array([[1.0, 1.0, 2.0], [3.0, 3.0, 2.0]])
            >>> with Map() as m:
            ...     _ = m.field(landcover, scheme="categorical")
            ...     _ = m.legend()
            ...     [label.get_text() for label in m.ax.get_legend().get_texts()]
            ['1', '2', '3']

            ```
        - A band of fractional values is a magnitude, so the categorical scheme refuses it:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import Map
            >>> with Map() as m:
            ...     m.field(np.array([[0.5, 1.0]]), scheme="categorical")  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: scheme='categorical' needs integer class codes ...

            ```
    """
    if limits is not None:
        # The Core channel is `limits`; ArrayGlyph reads its two ends as `vmin`/`vmax`, so it travels
        # on under the engine's own spelling — exactly where a caller's `vmin=`/`vmax=` always went.
        kwargs["vmin"], kwargs["vmax"] = limits
    if opacity is not None:
        # Named `opacity` here and `alpha` where it reaches matplotlib, as on the vector builders.
        kwargs["alpha"] = opacity
    self._field(
        data,
        kind="imshow",
        band=band,
        cmap=cmap,
        name=name,
        visible=visible,
        **kwargs,
    )
    return self

contours(dataset, *, levels=None, interval=None, filled=False, hatches=None, hatch_color=None, name=None, visible=True, **kwargs) #

Trace iso-value lines through a raster band, or fill between them.

One method for both renders, which is what the Tier-2 contract declares and what the web and interactive tiers offer. This tier had two — contour and contourf — so filled= meant nothing here and a script moving between tiers had to know which of the two to write. Neither spelling survives: filled= is the argument that picks the render.

Parameters:

Name Type Description Default
dataset Any

A pyramids Dataset, or a path or URL to one (reprojected to :attr:crs first). Only a path-backed layer can be written down.

required
levels Any

The iso-values to trace — an int (a count) or a sequence of values. None (default) takes the variable's canonical levels from auto_style, and leaves the choice to matplotlib when it carries none. Give at most one of this or interval.

None
interval float | None

Spacing between levels — one level every N, in the band's own units. Resolved against the band's range when it is drawn, so only the multiples inside the data are traced. Give at most one of this or levels.

None
filled bool

False (default) draws the levels as lines; True fills the bands between them. The two are different matplotlib renders, so this is the argument that picks one.

False
hatches Sequence[str | None] | None

A hatch pattern per band between levels — ["///", ""] marks the first band and leaves the second plain; matplotlib cycles a short list. Bands only exist on a filled render, so this needs filled=True. Pass fill=False as well to leave the bands uncoloured and draw only the hatching: the overlay form for a significance or uncertainty mask over another field. :meth:legend on a hatched layer keys its bands by pattern.

None
hatch_color str | None

The colour of the hatch strokes. None (default) leaves matplotlib's. It needs hatches too — there is nothing to colour without them.

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the figure is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the drawing (#327).

True
**kwargs Any

Forwarded to :meth:_field, which documents the named ones. Anything left over is the caller's own engine styling, split between the layer's description and the scene (see the class docstring).

{}

Returns:

Type Description
Self

This map (chainable). The drawn artist is reached with

Self

meth:~digitalearth.static.core.scene.Scene.artist — map.artist() for the layer just

Self

drawn, or map.artist(layer_id) by name — and a layer the display CRS could not place

Self

drew nothing, so it is absent from the figure and refused there. See :meth:field for why

Self

the return value is the map rather than the artist.

Raises:

Type Description
ValueError

when hatches, hatch_color or fill is given without filled=True — line contours have no bands to hatch, and cleopatra would only warn and draw them plain; when hatch_color or fill=False is given without hatches — the first colours strokes that do not exist, the second leaves a layer that marks the map with nothing, and cleopatra warns and draws both anyway; when both levels and interval are given — two ways of asking for one thing, so neither can be silently preferred; when interval is not a positive finite spacing or crosses no level inside the band; for scheme="categorical", because a contour interpolates between class codes (draw categories with :meth:field, :meth:pcolormesh or :meth:block); or from ArrayGlyph for a styling keyword it does not accept.

Examples:

  • A significance overlay: hatch where p < 0.05, leave the rest of the map as it is, and key it. labels= carries one label per band levels= declares — two here — while the key draws only the bands the map actually marks and the data reaches, which is the first. The count therefore comes from the call and not from the raster, so a recorded labels= keeps working when the data stops reaching a band:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalearth import Map
    >>> p = Dataset.from_array(
    ...     arr=np.array([[0.01, 0.3], [0.02, 0.6]]),
    ...     geo_ref=GeoReference(geo=(0.0, 1.0, 0.0, 2.0, 0.0, -1.0), epsg=4326),
    ...     no_data_value=-9999.0,
    ... )
    >>> m = Map(crs=4326)
    >>> _ = m.contours(
    ...     p, levels=[0, 0.05, 1], filled=True, hatches=["///", ""], fill=False, name="sig"
    ... )
    >>> list(m.artist("sig").hatches)
    ['///', '']
    >>> legend = m.legend(
    ...     "sig", labels=["p < 0.05", "p >= 0.05"]
    ... ).ax.get_legend()
    >>> [t.get_text() for t in legend.get_texts()], legend.legend_handles[0].get_hatch()
    (['p < 0.05'], '///')
    >>> m.close()
    
  • Each of the three band keywords is refused where it would have no effect, by name — a line render has no bands to hatch, and the other two have nothing to hatch with:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalearth import Map
    >>> p = Dataset.from_array(
    ...     arr=np.array([[0.01, 0.3], [0.02, 0.6]]),
    ...     geo_ref=GeoReference(geo=(0.0, 1.0, 0.0, 2.0, 0.0, -1.0), epsg=4326),
    ...     no_data_value=-9999.0,
    ... )
    >>> m = Map(crs=4326)
    >>> for bands in ({"hatches": ["///", ""]}, {"filled": True, "hatch_color": "black"}):
    ...     try:
    ...         m.contours(p, levels=[0, 0.05, 1], **bands)
    ...     except ValueError as error:
    ...         print(str(error)[:67])
    contours() hatches the bands between levels, which only a filled re
    contours(hatch_color=) colours the hatch strokes and there are none
    >>> m.close()
    
Source code in src/digitalearth/static/builders/raster.py
def contours(
    self,
    dataset: Any,
    *,
    levels: Any = None,
    interval: float | None = None,
    filled: bool = False,
    hatches: Sequence[str | None] | None = None,
    hatch_color: str | None = None,
    name: str | None = None,
    visible: bool = True,
    **kwargs: Any,
) -> Self:
    """Trace iso-value lines through a raster band, or fill between them.

    One method for both renders, which is what the Tier-2 contract declares and what the web and
    interactive tiers offer. This tier had two — ``contour`` and ``contourf`` — so ``filled=`` meant
    nothing here and a script moving between tiers had to know which of the two to write. Neither
    spelling survives: ``filled=`` is the argument that picks the render.

    Args:
        dataset: A pyramids ``Dataset``, or a path or URL to one (reprojected to :attr:`crs`
            first). Only a path-backed layer can be written down.
        levels: The iso-values to trace — an int (a count) or a sequence of values. ``None``
            (default) takes the variable's canonical levels from ``auto_style``, and leaves the choice
            to matplotlib when it carries none. Give at most one of this or ``interval``.
        interval: Spacing between levels — one level every N, in the band's own units. Resolved
            against the band's range when it is drawn, so only the multiples *inside* the data are
            traced. Give at most one of this or ``levels``.
        filled: ``False`` (default) draws the levels as lines; ``True`` fills the bands between them.
            The two are different matplotlib renders, so this is the argument that picks one.
        hatches: A hatch pattern per band between ``levels`` — ``["///", ""]`` marks the first band and
            leaves the second plain; matplotlib cycles a short list. Bands only exist on a filled
            render, so this needs ``filled=True``. Pass ``fill=False`` as well to leave the bands
            uncoloured and draw only the hatching: the overlay form for a significance or uncertainty
            mask over another field. :meth:`legend` on a hatched layer keys its bands by pattern.
        hatch_color: The colour of the hatch strokes. ``None`` (default) leaves matplotlib's. It needs
            ``hatches`` too — there is nothing to colour without them.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the figure is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden, so a switcher reading the figure agrees with the drawing (#327).
        **kwargs: Forwarded to :meth:`_field`, which documents the named ones. Anything left over is
            the caller's own engine styling, split between the layer's description and the scene
            (see the class docstring).

    Returns:
        This map (chainable). The drawn artist is reached with
        :meth:`~digitalearth.static.core.scene.Scene.artist` — ``map.artist()`` for the layer just
        drawn, or ``map.artist(layer_id)`` by name — and a layer the display CRS could not place
        drew nothing, so it is absent from the figure and refused there. See :meth:`field` for why
        the return value is the map rather than the artist.

    Raises:
        ValueError: when ``hatches``, ``hatch_color`` or ``fill`` is given without ``filled=True`` —
            line contours have no bands to hatch, and cleopatra would only warn and draw them plain;
            when ``hatch_color`` or ``fill=False`` is given without ``hatches`` — the first colours
            strokes that do not exist, the second leaves a layer that marks the map with nothing, and
            cleopatra warns and draws both anyway; when
            both ``levels`` and ``interval`` are given — two ways of asking for one
            thing, so neither can be silently preferred; when ``interval`` is not a positive finite
            spacing or crosses no level inside the band; for ``scheme="categorical"``, because a contour
            interpolates between class codes (draw categories with :meth:`field`, :meth:`pcolormesh` or
            :meth:`block`); or from ``ArrayGlyph`` for a styling keyword it does not accept.

    Examples:
        - A significance overlay: hatch where p < 0.05, leave the rest of the map as it is, and key it.
          ``labels=`` carries one label per band ``levels=`` declares — two here — while the key draws
          only the bands the map actually marks and the data reaches, which is the first. The count
          therefore comes from the call and not from the raster, so a recorded ``labels=`` keeps
          working when the data stops reaching a band:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalearth import Map
            >>> p = Dataset.from_array(
            ...     arr=np.array([[0.01, 0.3], [0.02, 0.6]]),
            ...     geo_ref=GeoReference(geo=(0.0, 1.0, 0.0, 2.0, 0.0, -1.0), epsg=4326),
            ...     no_data_value=-9999.0,
            ... )
            >>> m = Map(crs=4326)
            >>> _ = m.contours(
            ...     p, levels=[0, 0.05, 1], filled=True, hatches=["///", ""], fill=False, name="sig"
            ... )
            >>> list(m.artist("sig").hatches)
            ['///', '']
            >>> legend = m.legend(
            ...     "sig", labels=["p < 0.05", "p >= 0.05"]
            ... ).ax.get_legend()
            >>> [t.get_text() for t in legend.get_texts()], legend.legend_handles[0].get_hatch()
            (['p < 0.05'], '///')
            >>> m.close()

            ```
        - Each of the three band keywords is refused where it would have no effect, by name — a line
          render has no bands to hatch, and the other two have nothing to hatch *with*:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalearth import Map
            >>> p = Dataset.from_array(
            ...     arr=np.array([[0.01, 0.3], [0.02, 0.6]]),
            ...     geo_ref=GeoReference(geo=(0.0, 1.0, 0.0, 2.0, 0.0, -1.0), epsg=4326),
            ...     no_data_value=-9999.0,
            ... )
            >>> m = Map(crs=4326)
            >>> for bands in ({"hatches": ["///", ""]}, {"filled": True, "hatch_color": "black"}):
            ...     try:
            ...         m.contours(p, levels=[0, 0.05, 1], **bands)
            ...     except ValueError as error:
            ...         print(str(error)[:67])
            contours() hatches the bands between levels, which only a filled re
            contours(hatch_color=) colours the hatch strokes and there are none
            >>> m.close()

            ```
    """
    if levels is not None and interval is not None:
        raise ValueError(
            "contours() takes at most one of interval= or levels=; "
            f"got interval={interval!r} and levels={levels!r}"
        )
    # The three band keywords are guarded together, on both axes. Each one cleopatra answers with a
    # warning and then a render that drops the encoding, which is the silent drop this builder exists
    # to refuse — and until now only two of the three were refused, and only on the `filled=` axis
    # (review M8).
    fill = kwargs.get("fill")
    if not filled and (
        hatches is not None or hatch_color is not None or fill is not None
    ):
        raise ValueError(
            "contours() hatches the bands between levels, which only a filled render has; "
            "pass filled=True (and fill=False to draw the hatching alone)"
        )
    if hatches is None and hatch_color is not None:
        raise ValueError(
            "contours(hatch_color=) colours the hatch strokes and there are none to colour; "
            f"pass hatches=[...] as well, or drop hatch_color={hatch_color!r}"
        )
    if hatches is None and fill is False:
        raise ValueError(
            "contours(fill=False) leaves every band uncoloured, so with no hatches= the layer marks "
            "the map with nothing at all; pass hatches=[...] to draw the overlay, or drop fill=False"
        )
    if hatches is not None:
        kwargs["hatches"] = list(hatches)
    if hatch_color is not None:
        kwargs["hatch_color"] = hatch_color
    self._field(
        dataset,
        kind="contourf" if filled else "contour",
        levels=levels,
        interval=interval,
        name=name,
        visible=visible,
        **kwargs,
    )
    return self

pcolormesh(dataset, *, name=None, visible=True, **kwargs) #

Render a raster as a quadrilateral mesh (ArrayGlyph kind="pcolormesh").

Parameters:

Name Type Description Default
dataset Any

A pyramids Dataset, or a path or URL to one (reprojected to :attr:crs first). Only a path-backed layer can be written down.

required
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the figure is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the drawing (#327).

True
**kwargs Any

Forwarded to :meth:_field, which documents the named ones. Anything left over is the caller's own engine styling, split between the layer's description and the scene (see the class docstring).

{}

Returns:

Type Description
Self

This map (chainable). The drawn artist is reached with

Self

meth:~digitalearth.static.core.scene.Scene.artist — map.artist() for the layer just

Self

drawn, or map.artist(layer_id) by name — and a layer the display CRS could not place

Self

drew nothing, so it is absent from the figure and refused there. See :meth:field for why

Self

the return value is the map rather than the artist.

Raises:

Type Description
ValueError

from ArrayGlyph for a styling keyword it does not accept.

Source code in src/digitalearth/static/builders/raster.py
def pcolormesh(
    self,
    dataset: Any,
    *,
    name: str | None = None,
    visible: bool = True,
    **kwargs: Any,
) -> Self:
    """Render a raster as a quadrilateral mesh (``ArrayGlyph`` ``kind="pcolormesh"``).

    Args:
        dataset: A pyramids ``Dataset``, or a path or URL to one (reprojected to :attr:`crs`
            first). Only a path-backed layer can be written down.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the figure is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden, so a switcher reading the figure agrees with the drawing (#327).
        **kwargs: Forwarded to :meth:`_field`, which documents the named ones. Anything left over is
            the caller's own engine styling, split between the layer's description and the scene
            (see the class docstring).

    Returns:
        This map (chainable). The drawn artist is reached with
        :meth:`~digitalearth.static.core.scene.Scene.artist` — ``map.artist()`` for the layer just
        drawn, or ``map.artist(layer_id)`` by name — and a layer the display CRS could not place
        drew nothing, so it is absent from the figure and refused there. See :meth:`field` for why
        the return value is the map rather than the artist.

    Raises:
        ValueError: from ``ArrayGlyph`` for a styling keyword it does not accept.
    """
    self._field(dataset, kind="pcolormesh", name=name, visible=visible, **kwargs)
    return self

block(dataset, *, name=None, visible=True, **kwargs) #

Render a raster as a filled cell mesh — currently an alias of :meth:pcolormesh.

block is meant for discrete per-cell rectangles aligned to cell edges. cleopatra's pcolormesh path accepts cell-centre coordinates only (it rejects edge arrays of length n + 1), so true edge-aligned blocks need an upstream cleopatra option; until that lands block draws the same filled mesh as :meth:pcolormesh. It is kept as a distinct, stable entry point so callers and examples can switch to true blocks transparently once cleopatra supports them.

Parameters:

Name Type Description Default
dataset Any

A pyramids Dataset, or a path or URL to one (reprojected to :attr:crs first). Only a path-backed layer can be written down.

required
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the figure is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the drawing (#327).

True
**kwargs Any

Forwarded to :meth:_field, which documents the named ones. Anything left over is the caller's own engine styling, split between the layer's description and the scene (see the class docstring).

{}

Returns:

Type Description
Self

This map (chainable). The drawn artist is reached with

Self

meth:~digitalearth.static.core.scene.Scene.artist — map.artist() for the layer just

Self

drawn, or map.artist(layer_id) by name — and a layer the display CRS could not place

Self

drew nothing, so it is absent from the figure and refused there. See :meth:field for why

Self

the return value is the map rather than the artist.

Raises:

Type Description
ValueError

from ArrayGlyph for a styling keyword it does not accept.

Source code in src/digitalearth/static/builders/raster.py
def block(
    self,
    dataset: Any,
    *,
    name: str | None = None,
    visible: bool = True,
    **kwargs: Any,
) -> Self:
    """Render a raster as a filled cell mesh — currently an alias of :meth:`pcolormesh`.

    ``block`` is meant for *discrete* per-cell rectangles aligned to cell **edges**. cleopatra's
    ``pcolormesh`` path accepts cell-**centre** coordinates only (it rejects edge arrays of length
    ``n + 1``), so true edge-aligned blocks need an upstream cleopatra option; until that lands ``block``
    draws the same filled mesh as :meth:`pcolormesh`. It is kept as a distinct, stable entry point so
    callers and examples can switch to true blocks transparently once cleopatra supports them.

    Args:
        dataset: A pyramids ``Dataset``, or a path or URL to one (reprojected to :attr:`crs`
            first). Only a path-backed layer can be written down.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the figure is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden, so a switcher reading the figure agrees with the drawing (#327).
        **kwargs: Forwarded to :meth:`_field`, which documents the named ones. Anything left over is
            the caller's own engine styling, split between the layer's description and the scene
            (see the class docstring).

    Returns:
        This map (chainable). The drawn artist is reached with
        :meth:`~digitalearth.static.core.scene.Scene.artist` — ``map.artist()`` for the layer just
        drawn, or ``map.artist(layer_id)`` by name — and a layer the display CRS could not place
        drew nothing, so it is absent from the figure and refused there. See :meth:`field` for why
        the return value is the map rather than the artist.

    Raises:
        ValueError: from ``ArrayGlyph`` for a styling keyword it does not accept.
    """
    self._field(dataset, kind="pcolormesh", name=name, visible=visible, **kwargs)
    return self

rgb_composite(dataset, bands=DEFAULT_COMPOSITE_BANDS, *, mask_nodata=True, limits=None, name=None, visible=True, **opts) #

Render three raster bands as a true/false-colour RGB image (ArrayGlyph RGB path).

Parameters:

Name Type Description Default
dataset Any

A multiband pyramids Dataset, or a path or URL to one (reprojected to the display CRS first). Only a path-backed layer can be written down.

required
bands Sequence[int]

Three 1-based band indices mapped to R, G, B. Defaults to (1, 2, 3).

DEFAULT_COMPOSITE_BANDS
mask_nodata bool

When True (default) each band's nodata cells are excluded from the 2-98 percentile stretch (and render transparent). Pass False for the raw values (the pre-mask behaviour, where the nodata sentinel participates in the stretch).

True
limits ChannelLimits | None

Optional frozen (lo, hi) stretch bounds, one pair per channel — skips the per-call percentile scan. :meth:~digitalearth.static.builders.animation.AnimationMixin.animate fills these from the whole stack so a composite animation holds one stretch across its frames.

None
**opts Any

Styling kwargs, filtered to ArrayGlyph's accepted options.

{}

Returns:

Type Description
Self

This map (chainable). The drawn artist is reached with

Self

meth:~digitalearth.static.core.scene.Scene.artist — map.artist() for the layer just

Self

drawn, or map.artist(layer_id) by name — and a layer the display CRS could not place

Self

drew nothing, so it is absent from the figure and refused there. See :meth:field for why

Self

the return value is the map rather than the artist.

Raises:

Type Description
ValueError

when bands does not hold exactly three indices, or limits is given without one (lo, hi) pair per channel.

Examples:

  • Composite three bands of a multiband raster into one RGB image:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalearth.static import Map
    >>> ds = Dataset.read_file("examples/data/acc4000.tif")
    >>> base = np.nan_to_num(ds.read_array(band=0).astype("float32"))
    >>> rgb = Dataset.from_array(arr=np.stack([base, base, base]),
    ...                          geo_ref=GeoReference(geo=ds.geotransform, epsg=ds.epsg))
    >>> m = Map(crs=rgb.epsg)
    >>> _ = m.rgb_composite(rgb)
    >>> len(m.ax.images)
    1
    >>> m.close()
    
  • Frozen limits replace the per-call stretch: a white point far above the data renders it black, which is what holds a sequence of frames on one scale:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalearth.static import Map
    >>> ds = Dataset.read_file("examples/data/acc4000.tif")
    >>> base = np.nan_to_num(ds.read_array(band=0).astype("float32"))
    >>> rgb = Dataset.from_array(arr=np.stack([base, base, base]),
    ...                          geo_ref=GeoReference(geo=ds.geotransform, epsg=ds.epsg))
    >>> m = Map(crs=rgb.epsg)
    >>> _ = m.rgb_composite(rgb, limits=[(0.0, 1e6)] * 3)
    >>> round(float(np.nanmax(m.ax.images[-1].get_array())), 3)
    0.0
    >>> m.close()
    
See Also

hsv_composite: The same three bands read as hue/saturation/value instead. digitalearth.base.stretch.channel_limits: Derives the limits this accepts.

Source code in src/digitalearth/static/builders/raster.py
def rgb_composite(
    self,
    dataset: Any,
    bands: Sequence[int] = DEFAULT_COMPOSITE_BANDS,
    *,
    mask_nodata: bool = True,
    limits: ChannelLimits | None = None,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Render three raster bands as a true/false-colour RGB image (``ArrayGlyph`` RGB path).

    Args:
        dataset: A multiband pyramids ``Dataset``, or a path or URL to one (reprojected to the
            display CRS first). Only a path-backed layer can be written down.
        bands: Three 1-based band indices mapped to R, G, B. Defaults to ``(1, 2, 3)``.
        mask_nodata: When ``True`` (default) each band's nodata cells are excluded from the 2-98
            percentile stretch (and render transparent). Pass ``False`` for the raw values (the
            pre-mask behaviour, where the nodata sentinel participates in the stretch).
        limits: Optional frozen ``(lo, hi)`` stretch bounds, one pair per channel — skips the per-call
            percentile scan. :meth:`~digitalearth.static.builders.animation.AnimationMixin.animate` fills
            these from the whole stack so a composite animation holds one stretch across its frames.
        **opts: Styling kwargs, filtered to ``ArrayGlyph``'s accepted options.

    Returns:
        This map (chainable). The drawn artist is reached with
        :meth:`~digitalearth.static.core.scene.Scene.artist` — ``map.artist()`` for the layer just
        drawn, or ``map.artist(layer_id)`` by name — and a layer the display CRS could not place
        drew nothing, so it is absent from the figure and refused there. See :meth:`field` for why
        the return value is the map rather than the artist.

    Raises:
        ValueError: when ``bands`` does not hold exactly three indices, or ``limits`` is given without
            one ``(lo, hi)`` pair per channel.

    Examples:
        - Composite three bands of a multiband raster into one RGB image:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalearth.static import Map
            >>> ds = Dataset.read_file("examples/data/acc4000.tif")
            >>> base = np.nan_to_num(ds.read_array(band=0).astype("float32"))
            >>> rgb = Dataset.from_array(arr=np.stack([base, base, base]),
            ...                          geo_ref=GeoReference(geo=ds.geotransform, epsg=ds.epsg))
            >>> m = Map(crs=rgb.epsg)
            >>> _ = m.rgb_composite(rgb)
            >>> len(m.ax.images)
            1
            >>> m.close()

            ```
        - Frozen ``limits`` replace the per-call stretch: a white point far above the data renders it
            black, which is what holds a sequence of frames on one scale:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalearth.static import Map
            >>> ds = Dataset.read_file("examples/data/acc4000.tif")
            >>> base = np.nan_to_num(ds.read_array(band=0).astype("float32"))
            >>> rgb = Dataset.from_array(arr=np.stack([base, base, base]),
            ...                          geo_ref=GeoReference(geo=ds.geotransform, epsg=ds.epsg))
            >>> m = Map(crs=rgb.epsg)
            >>> _ = m.rgb_composite(rgb, limits=[(0.0, 1e6)] * 3)
            >>> round(float(np.nanmax(m.ax.images[-1].get_array())), 3)
            0.0
            >>> m.close()

            ```

    See Also:
        hsv_composite: The same three bands read as hue/saturation/value instead.
        digitalearth.base.stretch.channel_limits: Derives the ``limits`` this accepts.
    """
    require_three_bands("rgb_composite", bands)
    self._composite(
        "rgb_composite",
        dataset,
        bands,
        mask_nodata,
        limits,
        opts,
        name=name,
        visible=visible,
    )
    return self

points(features, *, column=None, scheme=None, k=5, cmap=None, size=None, opacity=None, size_column=None, name=None, visible=True, **opts) #

Plot a pyramids FeatureCollection of points, coloured and sized by a column (ScatterGlyph).

Parameters:

Name Type Description Default
features Any

A pyramids FeatureCollection of point geometries, or a path or URL to one; reprojected to the display CRS. Only a path-backed layer can be written down.

required
column str | None

The column whose values colour the points; None (default) colours by the collection's own numeric value where it carries one, and draws one flat colour otherwise. The Core spelling, the same one :meth:choropleth and the web/interactive tiers use (#332).

None
scheme Any | None

How column is classified — None (default) is a continuous ramp, a named scheme ("quantiles", "equal_interval", "fisher_jenks", …) cuts it into k classes, and "categorical" gives every distinct value its own colour. Reaches ScatterGlyph's classify group, the same path the field and polygon builders use.

None
k int

Number of classes a named scheme is cut into; ignored when scheme is None or "categorical".

5
cmap Any | None

The colormap the points are coloured through; None leaves cleopatra's default.

None
size float | None

The marker's visual size, spelled the same way on every backend (#251); None leaves cleopatra's default. Reaches ScatterGlyph as its own point_size.

None
opacity float | None

How opaque the markers are, in [0, 1]. The spelling :data:~digitalearth.base.spec.encoding.CHANNELS and the Core contract use (#332); None (default) sets no opacity at all, and matplotlib's own alpha is what it arrives as.

None
size_column str | None

Optional column name whose values set the per-point marker size. Pair it with size_legend=True (and optionally size_limits / size_scale) to draw a size legend. None (default) uses a single uniform marker size — set that size with size (which every backend spells the same way).

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the figure is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the axes (#327).

True
**opts Any

Further ScatterGlyph styling kwargs (size_limits, size_scale, size_legend, size_legend_values, …). :func:~digitalearth.static.render.compat._fold_marker_size is the one place that knows cleopatra's constructor calls the marker size point_size.

{}

Returns:

Type Description
Self

This map (chainable). The drawn artist is reached with

Self

meth:~digitalearth.static.core.scene.Scene.artist — map.artist() for the layer just

Self

drawn, or map.artist(layer_id) by name — and a layer the display CRS could not place

Self

drew nothing, so it is absent from the figure and refused there. See

Self

meth:~digitalearth.static.builders.raster.RasterMixin.field for why the return value is the

Self

map rather than the artist (ST-20).

Raises:

Type Description
KeyError

if column or size_column names no feature attribute — the refusal names Map.points() and lists the columns the features do have (via :func:_require_column).

ValueError

if scheme is given with no column to classify — a scheme classifies a column, so one with nothing to classify is refused rather than silently dropped (#331); or if color is a matplotlib.colors.Normalize or cleopatra ColorScaling but the features carry no numeric value for it to scale; a colour scaling needs values, so it is refused rather than dropped.

Source code in src/digitalearth/static/builders/vector.py
@_skips_off_limb
def points(
    self,
    features: Any,
    *,
    column: str | None = None,
    scheme: Any | None = None,
    k: int = 5,
    cmap: Any | None = None,
    size: float | None = None,
    opacity: float | None = None,
    size_column: str | None = None,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Plot a pyramids ``FeatureCollection`` of points, coloured and sized by a column (``ScatterGlyph``).

    Args:
        features: A pyramids ``FeatureCollection`` of point geometries, or a path or URL to one;
            reprojected to the display CRS. Only a path-backed layer can be written down.
        column: The column whose values colour the points; ``None`` (default) colours by the
            collection's own numeric value where it carries one, and draws one flat colour otherwise.
            The Core spelling, the same one :meth:`choropleth` and the web/interactive tiers use (#332).
        scheme: How ``column`` is classified — ``None`` (default) is a continuous ramp, a named scheme
            (``"quantiles"``, ``"equal_interval"``, ``"fisher_jenks"``, …) cuts it into ``k`` classes,
            and ``"categorical"`` gives every distinct value its own colour. Reaches ``ScatterGlyph``'s
            classify group, the same path the field and polygon builders use.
        k: Number of classes a named ``scheme`` is cut into; ignored when ``scheme`` is ``None`` or
            ``"categorical"``.
        cmap: The colormap the points are coloured through; ``None`` leaves cleopatra's default.
        size: The marker's visual size, spelled the same way on every backend (#251); ``None`` leaves
            cleopatra's default. Reaches ``ScatterGlyph`` as its own ``point_size``.
        opacity: How opaque the markers are, in ``[0, 1]``. The spelling
            :data:`~digitalearth.base.spec.encoding.CHANNELS` and the Core contract use (#332);
            ``None`` (default) sets no opacity at all, and matplotlib's own ``alpha`` is what it
            arrives as.
        size_column: Optional column name whose values set the per-point marker size. Pair it with
            ``size_legend=True`` (and optionally ``size_limits`` / ``size_scale``) to draw a size
            legend. ``None`` (default) uses a single uniform marker size — set that size with
            ``size`` (which every backend spells the same way).
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the figure is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden, so a switcher reading the figure agrees with the axes (#327).
        **opts: Further ``ScatterGlyph`` styling kwargs (``size_limits``, ``size_scale``,
            ``size_legend``, ``size_legend_values``, …).
            :func:`~digitalearth.static.render.compat._fold_marker_size` is the one place that knows
            cleopatra's constructor calls the marker size ``point_size``.

    Returns:
        This map (chainable). The drawn artist is reached with
        :meth:`~digitalearth.static.core.scene.Scene.artist` — ``map.artist()`` for the layer just
        drawn, or ``map.artist(layer_id)`` by name — and a layer the display CRS could not place
        drew nothing, so it is absent from the figure and refused there. See
        :meth:`~digitalearth.static.builders.raster.RasterMixin.field` for why the return value is the
        map rather than the artist (ST-20).

    Raises:
        KeyError: if ``column`` or ``size_column`` names no feature attribute — the refusal names
            ``Map.points()`` and lists the columns the features do have (via :func:`_require_column`).
        ValueError: if ``scheme`` is given with no ``column`` to classify — a scheme classifies a
            column, so one with nothing to classify is refused rather than silently dropped (#331); or
            if ``color`` is a ``matplotlib.colors.Normalize`` or cleopatra ``ColorScaling`` but the
            features carry no numeric value for it to scale; a colour *scaling* needs values, so it is
            refused rather than dropped.

    """
    if scheme is not None and not column:
        # A scheme classifies a column, so one with no column to classify is a dropped styling request —
        # the silent-ignore this package has removed everywhere else, and the refusal the interactive
        # tier already gives for the same call (#331, #332).
        raise ValueError(
            f"{_POINTS_CALLER}: scheme= classifies column=, which was not given; "
            "name the column to classify, or drop scheme="
        )
    if cmap is not None:
        opts["cmap"] = cmap
    if scheme is not None:
        # The classify group ScatterGlyph reads: scheme cuts the values into k classes, the same path
        # the field and polygon builders take.
        opts["scheme"], opts["k"] = scheme, k
    if size is not None:
        opts["size"] = size
    if opacity is not None:
        # Named `opacity` here and `alpha` where it reaches matplotlib, as on choropleth.
        opts["alpha"] = opacity
    self._draw(
        LayerRecord(
            "points",
            source=features,
            name=name,
            visible=visible,
            symbology=Symbology(
                props={
                    "via": "scatter",
                    "column": column,
                    "size_column": size_column,
                }
            ),
            opts=opts,
        )
    )
    return self

grid_points(dataset, *, name=None, visible=True, **opts) #

Plot raster cell centres as points coloured by value (pyramids to_xyz → ScatterGlyph).

Parameters:

Name Type Description Default
dataset Any

A pyramids Dataset, or a path or URL to one (reprojected to the display CRS first). Only a path-backed layer can be written down.

required
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the figure is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the axes (#327).

True
**opts Any

Styling kwargs, filtered to ScatterGlyph's accepted options. size sets the marker size — the cross-backend spelling, folded onto cleopatra's own point_size constructor keyword by the one place that knows about it.

{}

Returns:

Type Description
Self

This map (chainable). The drawn artist is reached with

Self

meth:~digitalearth.static.core.scene.Scene.artist — map.artist() for the layer just

Self

drawn, or map.artist(layer_id) by name — and a layer the display CRS could not place

Self

drew nothing, so it is absent from the figure and refused there. See

Self

meth:~digitalearth.static.builders.raster.RasterMixin.field for why the return value is the

Self

map rather than the artist (ST-20).

Examples:

  • Scatter the raster's valid cell centres and count the resulting layer:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from pyramids.dataset import Dataset
    >>> from digitalearth.static import Map
    >>> ds = Dataset.read_file("examples/data/acc4000.tif")
    >>> m = Map(crs=ds.epsg)
    >>> _ = m.grid_points(ds)
    >>> len(m.layers)
    1
    >>> m.close()
    

Raises:

Type Description
TypeError

when dataset is not a raster or a reference to one. A bare numpy array is refused here where :meth:~digitalearth.static.builders.raster.RasterMixin.field takes one: the cell centres come from pyramids' to_xyz, which reads a geo-transform an array does not carry.

Source code in src/digitalearth/static/builders/vector.py
def grid_points(
    self,
    dataset: Any,
    *,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Plot raster cell centres as points coloured by value (pyramids ``to_xyz`` → ``ScatterGlyph``).

    Args:
        dataset: A pyramids ``Dataset``, or a path or URL to one (reprojected to the display CRS
            first). Only a path-backed layer can be written down.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the figure is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden, so a switcher reading the figure agrees with the axes (#327).
        **opts: Styling kwargs, filtered to ``ScatterGlyph``'s accepted options. ``size``
            sets the marker size — the cross-backend spelling, folded onto cleopatra's own
            ``point_size`` constructor keyword by the one place that knows about it.

    Returns:
        This map (chainable). The drawn artist is reached with
        :meth:`~digitalearth.static.core.scene.Scene.artist` — ``map.artist()`` for the layer just
        drawn, or ``map.artist(layer_id)`` by name — and a layer the display CRS could not place
        drew nothing, so it is absent from the figure and refused there. See
        :meth:`~digitalearth.static.builders.raster.RasterMixin.field` for why the return value is the
        map rather than the artist (ST-20).

    Examples:
        - Scatter the raster's valid cell centres and count the resulting layer:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from pyramids.dataset import Dataset
            >>> from digitalearth.static import Map
            >>> ds = Dataset.read_file("examples/data/acc4000.tif")
            >>> m = Map(crs=ds.epsg)
            >>> _ = m.grid_points(ds)
            >>> len(m.layers)
            1
            >>> m.close()

            ```

    Raises:
        TypeError: when `dataset` is not a raster or a reference to one. A bare numpy array is refused
            here where :meth:`~digitalearth.static.builders.raster.RasterMixin.field` takes one: the cell
            centres come from pyramids' ``to_xyz``, which reads a geo-transform an array does not carry.
    """
    require_drawable(dataset, caller="Map.grid_points()", accepts=("raster",))
    record = LayerRecord(
        "points",
        source=dataset,
        name=name,
        visible=visible,
        symbology=Symbology(props={"via": "grid_points"}),
        opts=opts,
    )
    try:
        self._draw(record)
    except OffLimbError:
        self._skipped_off_limb("grid_points")
    return self

grid_cells(dataset, band=DEFAULT_BAND, *, name=None, visible=True, **opts) #

Draw raster cells as value-coloured polygons (pyramids to_geodataframe → PolygonGlyph).

Parameters:

Name Type Description Default
dataset Any

A pyramids Dataset, or a path or URL to one (reprojected to the display CRS first). Only a path-backed layer can be written down.

required
band int

1-based band whose values colour the cells.

DEFAULT_BAND
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the figure is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the axes (#327).

True
**opts Any

The caller's own engine keywords, handed to PolygonGlyph as passed and held beside the layer rather than recorded in it (see the class docstring). PolygonGlyph refuses a name it does not know rather than dropping it. A scheme (including scheme="categorical", keyed by a swatch legend) is honoured the same way :meth:choropleth describes — see _polygon_layer.

{}

Returns:

Type Description
Self

This map (chainable). The drawn artist is reached with

Self

meth:~digitalearth.static.core.scene.Scene.artist — map.artist() for the layer just

Self

drawn, or map.artist(layer_id) by name — and a layer the display CRS could not place

Self

drew nothing, so it is absent from the figure and refused there. See

Self

meth:~digitalearth.static.builders.raster.RasterMixin.field for why the return value is the

Self

map rather than the artist (ST-20).

Raises:

Type Description
TypeError

when dataset is not a raster or a reference to one. A bare numpy array is refused here where :meth:~digitalearth.static.builders.raster.RasterMixin.field takes one: the cell polygons come from pyramids' to_geodataframe, which reads a geo-transform an array does not carry.

ValueError

from PolygonGlyph for a keyword in **opts it does not accept, naming the ones it does. The layer is dropped from the description again before it propagates.

Examples:

  • Draw one polygon per raster cell and confirm the count equals rows*columns:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from pyramids.dataset import Dataset
    >>> from digitalearth.static import Map
    >>> ds = Dataset.read_file("examples/data/acc4000.tif")
    >>> m = Map(crs=ds.epsg)
    >>> _ = m.grid_cells(ds, name="cells")
    >>> cells = m.artist("cells")
    >>> len(cells.get_paths()) == ds.rows * ds.columns
    True
    >>> m.close()
    
Source code in src/digitalearth/static/builders/vector.py
def grid_cells(
    self,
    dataset: Any,
    band: int = DEFAULT_BAND,
    *,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Draw raster cells as value-coloured polygons (pyramids ``to_geodataframe`` → ``PolygonGlyph``).

    Args:
        dataset: A pyramids ``Dataset``, or a path or URL to one (reprojected to the display CRS
            first). Only a path-backed layer can be written down.
        band: 1-based band whose values colour the cells.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the figure is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden, so a switcher reading the figure agrees with the axes (#327).
        **opts: The caller's own engine keywords, handed to ``PolygonGlyph`` as passed and held beside
            the layer rather than recorded in it (see the class docstring). ``PolygonGlyph`` refuses a
            name it does not know rather than dropping it. A ``scheme`` (including
            ``scheme="categorical"``, keyed by a swatch legend) is honoured the same way :meth:`choropleth`
            describes — see ``_polygon_layer``.

    Returns:
        This map (chainable). The drawn artist is reached with
        :meth:`~digitalearth.static.core.scene.Scene.artist` — ``map.artist()`` for the layer just
        drawn, or ``map.artist(layer_id)`` by name — and a layer the display CRS could not place
        drew nothing, so it is absent from the figure and refused there. See
        :meth:`~digitalearth.static.builders.raster.RasterMixin.field` for why the return value is the
        map rather than the artist (ST-20).

    Raises:
        TypeError: when `dataset` is not a raster or a reference to one. A bare numpy array is refused
            here where :meth:`~digitalearth.static.builders.raster.RasterMixin.field` takes one: the cell
            polygons come from pyramids' ``to_geodataframe``, which reads a geo-transform an array does
            not carry.
        ValueError: from ``PolygonGlyph`` for a keyword in ``**opts`` it does not accept, naming the
            ones it does. The layer is dropped from the description again before it propagates.

    Examples:
        - Draw one polygon per raster cell and confirm the count equals rows*columns:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from pyramids.dataset import Dataset
            >>> from digitalearth.static import Map
            >>> ds = Dataset.read_file("examples/data/acc4000.tif")
            >>> m = Map(crs=ds.epsg)
            >>> _ = m.grid_cells(ds, name="cells")
            >>> cells = m.artist("cells")
            >>> len(cells.get_paths()) == ds.rows * ds.columns
            True
            >>> m.close()

            ```
    """
    require_drawable(dataset, caller="Map.grid_cells()", accepts=("raster",))
    record = LayerRecord(
        # A raster's cells always carry their band's values, so this layer is always a choropleth —
        # `_polygon_kind` is named here for the same reason the outline builders name it: what makes a
        # polygon layer one kind or the other is whether its polygons are filled by a value.
        _polygon_kind(band),
        source=dataset,
        name=name,
        visible=visible,
        symbology=Symbology(props={"via": "grid_cells", "band": band}),
        opts=opts,
    )
    try:
        self._draw(record)
    except OffLimbError:
        self._skipped_off_limb("grid_cells")
    return self

lines(features, *, column=None, scheme=None, k=5, cmap=None, width=None, color=None, opacity=None, name=None, visible=True, **opts) #

Draw line features — rivers, roads, tracks, reach networks (pyramids lines → FlowGlyph).

The Core contract's lines, with the web tier's keywords: a constant colour, or a colour per feature from column (classified by scheme/k), and a width that is either one number or a column. MultiLineString features draw one path per part, each carrying its feature's values. :meth:sankey draws the same geometry as a flow map, with flow defaults.

Parameters:

Name Type Description Default
features Any

A pyramids FeatureCollection of LineString/MultiLineString geometries, or a path or URL to one (reprojected to the display CRS). Only a path-backed layer can be written down.

required
column str | None

Numeric column whose value colours each line; None (default) draws one colour.

None
scheme Any | None

A classification scheme cutting column into k classes ("quantiles", "equal_interval", …); None (default) is a continuous ramp.

None
k int

Number of classes for scheme.

5
cmap Any | None

The colormap column is coloured through; None leaves cleopatra's default.

None
width float | str | None

Line width in points — a positive number — or the name of a numeric column whose values scale each line's width (between width_limits, a FlowGlyph option). None leaves cleopatra's width.

None
color Any | None

The colour of every line when column is None — any matplotlib colour. A built ColorScaling or Normalize is instead the colour scaling of column, as it is on every other static builder. A string that is not a colour is refused rather than passed on, with column= named as what takes a column's name.

None
opacity float | None

Layer opacity, 0 transparent to 1 opaque.

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the figure is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the axes (#327).

True
**opts Any

Further FlowGlyph options (width_limits, width_scale, draw_order, glow, …).

{}

Returns:

Type Description
Self

This map (chainable). The drawn artist is reached with

Self

meth:~digitalearth.static.core.scene.Scene.artist — map.artist() for the layer just

Self

drawn, or map.artist(layer_id) by name — and a layer the display CRS could not place

Self

drew nothing, so it is absent from the figure and refused there. See

Self

meth:~digitalearth.static.builders.raster.RasterMixin.field for why the return value is the

Self

map rather than the artist (ST-20).

Raises:

Type Description
ValueError

if features is empty or contains non-line geometry; if width is not a positive finite number (a line has no negative thickness); if color is a string that is not a matplotlib colour — the refusal names column= as the keyword that takes a column's name; if color is a matplotlib.colors.Normalize or cleopatra ColorScaling while column is None — a colour scaling has no values to act on without a column, so it is refused rather than dropped; or if column or a column width names a column that does not hold numbers, which a ramp and a width scale both need.

KeyError

if column or a column width names no feature attribute — the refusal names Map.lines(), the keyword and the column, and lists the columns there are.

Examples:

  • Colour reaches by discharge, classified into three classes, with one width:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import geopandas as gpd
    >>> from shapely.geometry import LineString
    >>> from pyramids.feature import FeatureCollection
    >>> from digitalearth import Map
    >>> reaches = FeatureCollection(gpd.GeoDataFrame(
    ...     {"discharge": [10.0, 40.0, 25.0]},
    ...     geometry=[LineString([(0, 0), (1, 1)]), LineString([(1, 1), (2, 1)]),
    ...               LineString([(2, 1), (3, 2)])],
    ...     crs="EPSG:4326",
    ... ))
    >>> with Map(crs=4326) as m:
    ...     _ = m.lines(reaches, column="discharge", scheme="equal_interval", k=3, width=2.0)
    ...     lc = m.artist()
    ...     lc.get_array().tolist(), sorted({float(w) for w in lc.get_linewidths()})
    ...     m.figure_spec.layers.get(m.layer_ids[-1]).kind
    ([10.0, 40.0, 25.0], [2.0])
    'lines'
    
  • One colour, widths scaled by a column:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import geopandas as gpd
    >>> from shapely.geometry import LineString
    >>> from pyramids.feature import FeatureCollection
    >>> from digitalearth import Map
    >>> roads = FeatureCollection(gpd.GeoDataFrame(
    ...     {"lanes": [1, 4]},
    ...     geometry=[LineString([(0, 0), (1, 0)]), LineString([(0, 1), (1, 1)])],
    ...     crs="EPSG:4326",
    ... ))
    >>> with Map(crs=4326) as m:
    ...     _ = m.lines(roads, width="lanes", color="dimgray")
    ...     widths = m.artist().get_linewidths()
    >>> bool(widths[1] > widths[0])
    True
    
  • A width a line cannot have, a column name under color=, and a text column under column= are each refused by name — and the colour refusal points at the keyword that does take a column's name:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import geopandas as gpd
    >>> from shapely.geometry import LineString
    >>> from pyramids.feature import FeatureCollection
    >>> from digitalearth import Map
    >>> roads = FeatureCollection(gpd.GeoDataFrame(
    ...     {"name": ["a", "b"], "lanes": [1.0, 4.0]},
    ...     geometry=[LineString([(0, 0), (1, 0)]), LineString([(0, 1), (1, 1)])],
    ...     crs="EPSG:4326",
    ... ))
    >>> m = Map(crs=4326)
    >>> for wrong in ({"width": -2.0}, {"color": "lanes"}, {"column": "name"}):
    ...     try:
    ...         m.lines(roads, **wrong)
    ...     except ValueError as error:
    ...         print(str(error)[:63])
    Map.lines() needs width= as a positive number of points, or the
    Map.lines() needs color= as one matplotlib colour for every lin
    Map.lines() needs column='name' to name a column of numbers, an
    >>> m.close()
    
  • A column name these features do not carry is named under the keyword it was given under, with the columns they do carry listed:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import geopandas as gpd
    >>> from shapely.geometry import LineString
    >>> from pyramids.feature import FeatureCollection
    >>> from digitalearth import Map
    >>> roads = FeatureCollection(gpd.GeoDataFrame(
    ...     {"name": ["a", "b"], "lanes": [1.0, 4.0]},
    ...     geometry=[LineString([(0, 0), (1, 0)]), LineString([(0, 1), (1, 1)])],
    ...     crs="EPSG:4326",
    ... ))
    >>> m = Map(crs=4326)
    >>> for wrong in ({"column": "flow"}, {"width": "order"}):
    ...     try:
    ...         m.lines(roads, **wrong)
    ...     except KeyError as error:
    ...         print(error.args[0])
    Map.lines(): column='flow' is not a property of these features; available: ['lanes', 'name']
    Map.lines(): width='order' is not a property of these features; available: ['lanes', 'name']
    >>> m.close()
    
See Also

sankey: the same geometry drawn as a flow map.

Source code in src/digitalearth/static/builders/vector.py
@_skips_off_limb
def lines(
    self,
    features: Any,
    *,
    column: str | None = None,
    scheme: Any | None = None,
    k: int = 5,
    cmap: Any | None = None,
    width: float | str | None = None,
    color: Any | None = None,
    opacity: float | None = None,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Draw line features — rivers, roads, tracks, reach networks (pyramids lines → ``FlowGlyph``).

    The Core contract's ``lines``, with the web tier's keywords: a constant colour, or a colour per
    feature from ``column`` (classified by ``scheme``/``k``), and a width that is either one number or a
    column. ``MultiLineString`` features draw one path per part, each carrying its feature's values.
    :meth:`sankey` draws the same geometry as a flow map, with flow defaults.

    Args:
        features: A pyramids ``FeatureCollection`` of ``LineString``/``MultiLineString`` geometries, or a
            path or URL to one (reprojected to the display CRS). Only a path-backed layer can be written
            down.
        column: Numeric column whose value colours each line; ``None`` (default) draws one colour.
        scheme: A classification scheme cutting ``column`` into ``k`` classes (``"quantiles"``,
            ``"equal_interval"``, …); ``None`` (default) is a continuous ramp.
        k: Number of classes for ``scheme``.
        cmap: The colormap ``column`` is coloured through; ``None`` leaves cleopatra's default.
        width: Line width in points — a positive number — or the name of a numeric column whose values
            scale each line's width (between ``width_limits``, a ``FlowGlyph`` option). ``None``
            leaves cleopatra's width.
        color: The colour of every line when ``column`` is ``None`` — any matplotlib colour. A built
            ``ColorScaling`` or ``Normalize`` is instead the colour *scaling* of ``column``, as it is on
            every other static builder. A string that is not a colour is refused rather than passed on,
            with ``column=`` named as what takes a column's name.
        opacity: Layer opacity, 0 transparent to 1 opaque.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the figure is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden, so a switcher reading the figure agrees with the axes (#327).
        **opts: Further ``FlowGlyph`` options (``width_limits``, ``width_scale``, ``draw_order``,
            ``glow``, …).

    Returns:
        This map (chainable). The drawn artist is reached with
        :meth:`~digitalearth.static.core.scene.Scene.artist` — ``map.artist()`` for the layer just
        drawn, or ``map.artist(layer_id)`` by name — and a layer the display CRS could not place
        drew nothing, so it is absent from the figure and refused there. See
        :meth:`~digitalearth.static.builders.raster.RasterMixin.field` for why the return value is the
        map rather than the artist (ST-20).

    Raises:
        ValueError: if ``features`` is empty or contains non-line geometry; if ``width`` is not a
            positive finite number (a line has no negative thickness); if ``color`` is a string that
            is not a matplotlib colour — the refusal names ``column=`` as the keyword that takes a
            column's name; if ``color`` is a ``matplotlib.colors.Normalize`` or cleopatra
            ``ColorScaling`` while ``column`` is ``None`` — a colour *scaling* has no values to act on
            without a column, so it is refused rather than dropped; or if ``column`` or a column
            ``width`` names a column that does not hold numbers, which a ramp and a width scale both need.
        KeyError: if ``column`` or a column ``width`` names no feature attribute — the refusal names
            ``Map.lines()``, the keyword and the column, and lists the columns there are.

    Examples:
        - Colour reaches by discharge, classified into three classes, with one width:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import geopandas as gpd
            >>> from shapely.geometry import LineString
            >>> from pyramids.feature import FeatureCollection
            >>> from digitalearth import Map
            >>> reaches = FeatureCollection(gpd.GeoDataFrame(
            ...     {"discharge": [10.0, 40.0, 25.0]},
            ...     geometry=[LineString([(0, 0), (1, 1)]), LineString([(1, 1), (2, 1)]),
            ...               LineString([(2, 1), (3, 2)])],
            ...     crs="EPSG:4326",
            ... ))
            >>> with Map(crs=4326) as m:
            ...     _ = m.lines(reaches, column="discharge", scheme="equal_interval", k=3, width=2.0)
            ...     lc = m.artist()
            ...     lc.get_array().tolist(), sorted({float(w) for w in lc.get_linewidths()})
            ...     m.figure_spec.layers.get(m.layer_ids[-1]).kind
            ([10.0, 40.0, 25.0], [2.0])
            'lines'

            ```
        - One colour, widths scaled by a column:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import geopandas as gpd
            >>> from shapely.geometry import LineString
            >>> from pyramids.feature import FeatureCollection
            >>> from digitalearth import Map
            >>> roads = FeatureCollection(gpd.GeoDataFrame(
            ...     {"lanes": [1, 4]},
            ...     geometry=[LineString([(0, 0), (1, 0)]), LineString([(0, 1), (1, 1)])],
            ...     crs="EPSG:4326",
            ... ))
            >>> with Map(crs=4326) as m:
            ...     _ = m.lines(roads, width="lanes", color="dimgray")
            ...     widths = m.artist().get_linewidths()
            >>> bool(widths[1] > widths[0])
            True

            ```
        - A width a line cannot have, a column name under ``color=``, and a text column under
          ``column=`` are each refused by name — and the colour refusal points at the keyword that does
          take a column's name:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import geopandas as gpd
            >>> from shapely.geometry import LineString
            >>> from pyramids.feature import FeatureCollection
            >>> from digitalearth import Map
            >>> roads = FeatureCollection(gpd.GeoDataFrame(
            ...     {"name": ["a", "b"], "lanes": [1.0, 4.0]},
            ...     geometry=[LineString([(0, 0), (1, 0)]), LineString([(0, 1), (1, 1)])],
            ...     crs="EPSG:4326",
            ... ))
            >>> m = Map(crs=4326)
            >>> for wrong in ({"width": -2.0}, {"color": "lanes"}, {"column": "name"}):
            ...     try:
            ...         m.lines(roads, **wrong)
            ...     except ValueError as error:
            ...         print(str(error)[:63])
            Map.lines() needs width= as a positive number of points, or the
            Map.lines() needs color= as one matplotlib colour for every lin
            Map.lines() needs column='name' to name a column of numbers, an
            >>> m.close()

            ```
        - A column name these features do not carry is named under the keyword it was given under,
          with the columns they do carry listed:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import geopandas as gpd
            >>> from shapely.geometry import LineString
            >>> from pyramids.feature import FeatureCollection
            >>> from digitalearth import Map
            >>> roads = FeatureCollection(gpd.GeoDataFrame(
            ...     {"name": ["a", "b"], "lanes": [1.0, 4.0]},
            ...     geometry=[LineString([(0, 0), (1, 0)]), LineString([(0, 1), (1, 1)])],
            ...     crs="EPSG:4326",
            ... ))
            >>> m = Map(crs=4326)
            >>> for wrong in ({"column": "flow"}, {"width": "order"}):
            ...     try:
            ...         m.lines(roads, **wrong)
            ...     except KeyError as error:
            ...         print(error.args[0])
            Map.lines(): column='flow' is not a property of these features; available: ['lanes', 'name']
            Map.lines(): width='order' is not a property of these features; available: ['lanes', 'name']
            >>> m.close()

            ```

    See Also:
        sankey: the same geometry drawn as a flow map.
    """
    if width is not None and not isinstance(width, str):
        # A scalar width reached the collection exactly as written, negatives included
        # (`get_linewidths() == [-2.0]`), and zero drew lines of no width at all (review L4).
        if _as_finite(width, "width", _LINES_CALLER) <= 0.0:
            raise ValueError(
                f"{_LINES_CALLER} needs width= as a positive number of points, or the name of a "
                f"column to scale the widths by; got {width!r}"
            )
    line_color = _resolve_line_colour(color, column, opts)
    if cmap is not None:
        opts["cmap"] = cmap
    if scheme is not None:
        opts["scheme"] = scheme
        opts["k"] = k
    self._draw(
        LayerRecord(
            "lines",
            source=features,
            name=name,
            visible=visible,
            symbology=Symbology(
                props={
                    "via": "lines",
                    "column": column,
                    "width": width,
                    "color": line_color,
                    "opacity": None if opacity is None else float(opacity),
                }
            ),
            opts=opts,
        )
    )
    return self

polygons(features, *, column=None, scheme=None, k=5, cmap=None, opacity=None, name=None, visible=True, **opts) #

Draw polygons — outlines, or a fill coloured by column (pyramids FeatureCollection).

Without column this draws outlines with no fill (PolygonGlyph outline mode); with one it fills them coloured by that attribute, the same render :meth:choropleth draws — the Core declares polygons with the full colour vocabulary, so the two are one builder here as on the other tiers (#332).

Parameters:

Name Type Description Default
features Any

A pyramids FeatureCollection of polygons, or a path or URL to one (reprojected to the display CRS). Only a path-backed layer can be written down.

required
column str | None

The column whose values fill the polygons; None (default) draws unfilled outlines. The Core spelling, the same one :meth:choropleth and the web/interactive tiers use.

None
scheme Any | None

How column is classified — None (default) is a continuous ramp, a named scheme ("quantiles", "equal_interval", …) cuts it into k classes, and "categorical" gives every distinct value its own colour. Ignored when column is None.

None
k int

Number of classes a named scheme is cut into; ignored when scheme is None or "categorical".

5
cmap Any | None

The colormap the fill is drawn with; None leaves cleopatra's default.

None
opacity float | None

How opaque the layer is, in [0, 1]. The spelling :data:~digitalearth.base.spec.encoding.CHANNELS and the Core contract use (#332); None (default) sets no opacity at all, and matplotlib's own alpha is what it arrives as.

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the figure is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the axes (#327).

True
**opts Any

Styling kwargs, filtered to PolygonGlyph's accepted options.

{}

Returns:

Type Description
Self

This map (chainable). The drawn artist is reached with

Self

meth:~digitalearth.static.core.scene.Scene.artist — map.artist() for the layer just

Self

drawn, or map.artist(layer_id) by name — and a layer the display CRS could not place

Self

drew nothing, so it is absent from the figure and refused there. See

Self

meth:~digitalearth.static.builders.raster.RasterMixin.field for why the return value is the

Self

map rather than the artist (ST-20).

Raises:

Type Description
ValueError

if scheme is given with no column to classify — a scheme classifies a column, so one with nothing to classify is refused rather than silently ignored (#331); or if color is a matplotlib.colors.Normalize or cleopatra ColorScaling while column is None — an outline layer draws a uniform fill with no values to scale, so a colour scaling is refused; pass column= to colour polygons by a column.

KeyError

if column names no feature attribute — the refusal names choropleth() and lists the columns the features do have (via :func:_require_column). A filled polygons layer draws through the choropleth recipe, so a non-numeric column on a continuous or graduated ramp raises ValueError from the same recipe, also naming choropleth().

Source code in src/digitalearth/static/builders/vector.py
@_skips_off_limb
def polygons(
    self,
    features: Any,
    *,
    column: str | None = None,
    scheme: Any | None = None,
    k: int = 5,
    cmap: Any | None = None,
    opacity: float | None = None,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Draw polygons — outlines, or a fill coloured by ``column`` (pyramids ``FeatureCollection``).

    Without ``column`` this draws outlines with no fill (``PolygonGlyph`` outline mode); with one it
    fills them coloured by that attribute, the same render :meth:`choropleth` draws — the Core declares
    ``polygons`` with the full colour vocabulary, so the two are one builder here as on the other tiers
    (#332).

    Args:
        features: A pyramids ``FeatureCollection`` of polygons, or a path or URL to one
            (reprojected to the display CRS). Only a path-backed layer can be written down.
        column: The column whose values fill the polygons; ``None`` (default) draws unfilled outlines.
            The Core spelling, the same one :meth:`choropleth` and the web/interactive tiers use.
        scheme: How ``column`` is classified — ``None`` (default) is a continuous ramp, a named scheme
            (``"quantiles"``, ``"equal_interval"``, …) cuts it into ``k`` classes, and ``"categorical"``
            gives every distinct value its own colour. Ignored when ``column`` is ``None``.
        k: Number of classes a named ``scheme`` is cut into; ignored when ``scheme`` is ``None`` or
            ``"categorical"``.
        cmap: The colormap the fill is drawn with; ``None`` leaves cleopatra's default.
        opacity: How opaque the layer is, in ``[0, 1]``. The spelling
            :data:`~digitalearth.base.spec.encoding.CHANNELS` and the Core contract use (#332);
            ``None`` (default) sets no opacity at all, and matplotlib's own ``alpha`` is what it
            arrives as.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the figure is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden, so a switcher reading the figure agrees with the axes (#327).
        **opts: Styling kwargs, filtered to ``PolygonGlyph``'s accepted options.

    Returns:
        This map (chainable). The drawn artist is reached with
        :meth:`~digitalearth.static.core.scene.Scene.artist` — ``map.artist()`` for the layer just
        drawn, or ``map.artist(layer_id)`` by name — and a layer the display CRS could not place
        drew nothing, so it is absent from the figure and refused there. See
        :meth:`~digitalearth.static.builders.raster.RasterMixin.field` for why the return value is the
        map rather than the artist (ST-20).

    Raises:
        ValueError: if ``scheme`` is given with no ``column`` to classify — a scheme classifies a
            column, so one with nothing to classify is refused rather than silently ignored (#331); or
            if ``color`` is a ``matplotlib.colors.Normalize`` or cleopatra ``ColorScaling`` while
            ``column`` is ``None`` — an outline layer draws a uniform fill with no values to scale, so a
            colour *scaling* is refused; pass ``column=`` to colour polygons by a column.
        KeyError: if ``column`` names no feature attribute — the refusal names ``choropleth()`` and
            lists the columns the features do have (via :func:`_require_column`). A filled ``polygons``
            layer draws through the ``choropleth`` recipe, so a non-numeric ``column`` on a continuous or
            graduated ramp raises ``ValueError`` from the same recipe, also naming ``choropleth()``.
    """
    if scheme is not None and not column:
        # A scheme classifies a column, so one with no column to classify is a dropped styling request:
        # an outline-only `polygons` layer silently ignored it. Refuse it by name, as `points` and the
        # interactive tier do (#331, #332), rather than drawing plain outlines and saying nothing.
        raise ValueError(
            f"{_POLYGONS_CALLER}: scheme= classifies column=, which was not given; "
            "name the column to classify, or drop scheme="
        )
    if cmap is not None:
        opts["cmap"] = cmap
    if opacity is not None:
        opts["alpha"] = opacity
    if column is None:
        _refuse_colour_norm(
            opts.get("color"),
            _POLYGONS_CALLER,
            "polygons() draws a uniform fill with no values to scale — pass column= to "
            "colour polygons by a column.",
        )
        self._draw(
            LayerRecord(
                _polygon_kind(
                    None
                ),  # outlines only, whatever the collection carries
                source=features,
                name=name,
                visible=visible,
                symbology=Symbology(props={"via": "shapes"}),
                opts=opts,
            )
        )
        return self
    # A filled polygon layer is a choropleth: it records the same kind and is drawn by the same recipe.
    self._draw(
        LayerRecord(
            _polygon_kind(column),
            source=features,
            name=name,
            visible=visible,
            symbology=Symbology(
                props={
                    "via": "choropleth",
                    "column": column,
                    "scheme": scheme,
                    "k": k,
                }
            ),
            opts=opts,
        )
    )
    return self

choropleth(features, column, *, scheme=None, k=5, cmap=None, opacity=None, name=None, visible=True, **opts) #

Fill polygons coloured by a feature attribute (pyramids FeatureCollection → PolygonGlyph).

Parameters:

Name Type Description Default
features Any

A pyramids FeatureCollection of polygons, or a path or URL to one (reprojected to the display CRS). Only a path-backed layer can be written down.

required
column str

Name of the column whose values colour the polygons — numeric for a continuous or graduated scale, or any nominal labels (strings, region codes, …) under scheme="categorical".

required
scheme Any | None

How the values are classified. None (default) is a continuous ramp; a named scheme ("quantiles", "fisher_jenks", "equal_interval", …) or an explicit sequence of bin edges is graduated into k classes; "categorical" gives every distinct value its own colour (an unordered attribute such as a land-use class or region name — k does not apply, and vmin/vmax/levels/color_scale are ignored), keyed by a swatch legend rather than a colorbar. Spelled the same way, with the same default, on every backend: scheme=None is a continuous ramp everywhere, so the same call classifies identically on all four tiers. Either kind of classification leaves a missing value (NaN/None/pd.NA) outside every class, so those features are drawn a neutral grey — not dropped, and not painted as the lowest class. A continuous ramp has no classes and is left to matplotlib.

None
k int

Number of classes a named scheme is cut into (ignored when scheme is None or "categorical").

5
opacity float | None

How opaque the fill is, in [0, 1]. This is the spelling CHANNELS (in digitalearth.base.spec.encoding) and the Core contract use, so the same channel is written the same way wherever it is offered (#332). Measured, choropleth names it on all three 2-D tiers — static, web and interactive; the 3-D tier names it only on volume, not on its polygon builder extruded_polygons. matplotlib's own alpha is what it arrives as. None (default) sets no opacity at all, which is not the same as 1.0: measured, opacity=None leaves artist.get_alpha() at None — the colormap's own alpha channel still in force — while opacity=1.0 sets it to 1.0.

None
cmap Any | None

The colormap the fill is drawn with, forwarded to PolygonGlyph exactly as a cmap= in **opts always was. Named in the signature because the Core declares it as a keyword of choropleth on every tier, and a keyword that works but is not written down is one a caller has to read the source to find (#324).

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the figure is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the axes (#327).

True
**opts Any

Styling kwargs forwarded to PolygonGlyph. For a categorical scheme, cmap should be a qualitative (ListedColormap) map — "tab10" (the default), "Set2", "Paired", … A continuous LinearSegmentedColormap ("coolwarm", "RdBu") is sampled at evenly-spaced points so the categories stay distinct; a perceptual ListedColormap ("viridis", "plasma") is accepted but reads poorly (its first n of 256 entries are near-identical shades). The colours are identical to the web/interactive tiers either way.

{}

Returns:

Type Description
Self

This map (chainable). The drawn artist is reached with

Self

meth:~digitalearth.static.core.scene.Scene.artist — map.artist() for the layer just

Self

drawn, or map.artist(layer_id) by name — and a layer the display CRS could not place

Self

drew nothing, so it is absent from the figure and refused there. See

Self

meth:~digitalearth.static.builders.raster.RasterMixin.field for why the return value is the

Self

map rather than the artist (ST-20).

Raises:

Type Description
KeyError

if column names no feature attribute — the refusal names choropleth() and lists the columns the features do have (via :func:_require_column).

Examples:

  • Colour buffered point features by their fid column and count the drawn polygons:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from pyramids.feature import FeatureCollection
    >>> from digitalearth.static import Map
    >>> fc = FeatureCollection.read_file("tests/data/points.geojson")
    >>> fc["geometry"] = fc.geometry.buffer(500.0)
    >>> m = Map(crs=fc.epsg)
    >>> _ = m.choropleth(fc, column="fid", name="zones")
    >>> len(m.artist("zones").get_paths()) >= len(fc)
    True
    >>> m.close()
    
  • Colour by an unordered attribute — one colour per distinct class, keyed by a swatch legend:
    >>> fc["zone"] = ["urban", "rural"] * (len(fc) // 2) + ["urban"] * (len(fc) % 2)
    >>> m = Map(crs=fc.epsg)
    >>> _ = m.choropleth(fc, column="zone", scheme="categorical", name="zoning")
    >>> from matplotlib.colors import BoundaryNorm
    >>> norm = m.artist("zoning").norm
    >>> isinstance(norm, BoundaryNorm)  # discrete class codes, not a continuous scale
    True
    >>> [t.get_text() for t in m.layers[-1][0].category_legend.get_texts()]
    ['rural', 'urban']
    >>> m.close()
    
Source code in src/digitalearth/static/builders/vector.py
@_skips_off_limb
def choropleth(
    self,
    features: Any,
    column: str,
    *,
    scheme: Any | None = None,
    k: int = 5,
    cmap: Any | None = None,
    opacity: float | None = None,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Fill polygons coloured by a feature attribute (pyramids ``FeatureCollection`` → ``PolygonGlyph``).

    Args:
        features: A pyramids ``FeatureCollection`` of polygons, or a path or URL to one
            (reprojected to the display CRS). Only a path-backed layer can be written down.
        column: Name of the column whose values colour the polygons — numeric for a continuous or
            graduated scale, or any nominal labels (strings, region codes, …) under
            ``scheme="categorical"``.
        scheme: How the values are classified. ``None`` (default) is a **continuous** ramp; a named
            scheme (``"quantiles"``, ``"fisher_jenks"``, ``"equal_interval"``, …) or an explicit
            sequence of bin edges is graduated into ``k`` classes; ``"categorical"`` gives every
            distinct value its own colour (an unordered attribute such as a land-use class or region
            name — ``k`` does not apply, and ``vmin``/``vmax``/``levels``/``color_scale`` are ignored),
            keyed by a swatch legend rather than a colorbar. Spelled the same way, with the same
            default, on every backend: ``scheme=None`` is a continuous ramp everywhere, so the same
            call classifies identically on all four tiers. Either kind of classification leaves a
            missing value (``NaN``/``None``/``pd.NA``) outside every class, so those features are
            drawn a neutral grey — not dropped, and not painted as the lowest class. A continuous
            ramp has no classes and is left to matplotlib.
        k: Number of classes a named ``scheme`` is cut into (ignored when ``scheme`` is ``None`` or
            ``"categorical"``).
        opacity: How opaque the fill is, in ``[0, 1]``. This is the spelling `CHANNELS` (in
            `digitalearth.base.spec.encoding`) and the Core contract use, so the same channel is
            written the same way wherever it is offered (#332). Measured, `choropleth` names it on
            all three 2-D tiers — static, web and interactive; the 3-D tier names it only on
            `volume`, not on its polygon builder `extruded_polygons`.
            matplotlib's own ``alpha`` is what it arrives as. ``None`` (default) sets no opacity at
            all, which is not the same as ``1.0``: measured, `opacity=None` leaves
            `artist.get_alpha()` at `None` — the colormap's own alpha channel still in force —
            while `opacity=1.0` sets it to `1.0`.
        cmap: The colormap the fill is drawn with, forwarded to ``PolygonGlyph`` exactly as a
            ``cmap=`` in ``**opts`` always was. Named in the signature because the Core declares it
            as a keyword of ``choropleth`` on every tier, and a keyword that works but is not
            written down is one a caller has to read the source to find (#324).
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the figure is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden, so a switcher reading the figure agrees with the axes (#327).
        **opts: Styling kwargs forwarded to ``PolygonGlyph``. For a categorical scheme, ``cmap`` should
            be a **qualitative** (``ListedColormap``) map — ``"tab10"`` (the default), ``"Set2"``,
            ``"Paired"``, … A continuous ``LinearSegmentedColormap`` (``"coolwarm"``, ``"RdBu"``) is
            sampled at evenly-spaced points so the categories stay distinct; a perceptual
            ``ListedColormap`` (``"viridis"``, ``"plasma"``) is accepted but reads poorly (its first
            *n* of 256 entries are near-identical shades). The colours are identical to the
            web/interactive tiers either way.

    Returns:
        This map (chainable). The drawn artist is reached with
        :meth:`~digitalearth.static.core.scene.Scene.artist` — ``map.artist()`` for the layer just
        drawn, or ``map.artist(layer_id)`` by name — and a layer the display CRS could not place
        drew nothing, so it is absent from the figure and refused there. See
        :meth:`~digitalearth.static.builders.raster.RasterMixin.field` for why the return value is the
        map rather than the artist (ST-20).

    Raises:
        KeyError: if ``column`` names no feature attribute — the refusal names ``choropleth()`` and
            lists the columns the features do have (via :func:`_require_column`).

    Examples:
        - Colour buffered point features by their ``fid`` column and count the drawn polygons:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from pyramids.feature import FeatureCollection
            >>> from digitalearth.static import Map
            >>> fc = FeatureCollection.read_file("tests/data/points.geojson")
            >>> fc["geometry"] = fc.geometry.buffer(500.0)
            >>> m = Map(crs=fc.epsg)
            >>> _ = m.choropleth(fc, column="fid", name="zones")
            >>> len(m.artist("zones").get_paths()) >= len(fc)
            True
            >>> m.close()

            ```
        - Colour by an unordered attribute — one colour per distinct class, keyed by a swatch legend:
            ```python
            >>> fc["zone"] = ["urban", "rural"] * (len(fc) // 2) + ["urban"] * (len(fc) % 2)
            >>> m = Map(crs=fc.epsg)
            >>> _ = m.choropleth(fc, column="zone", scheme="categorical", name="zoning")
            >>> from matplotlib.colors import BoundaryNorm
            >>> norm = m.artist("zoning").norm
            >>> isinstance(norm, BoundaryNorm)  # discrete class codes, not a continuous scale
            True
            >>> [t.get_text() for t in m.layers[-1][0].category_legend.get_texts()]
            ['rural', 'urban']
            >>> m.close()

            ```
    """
    if cmap is not None:
        # Straight back into the caller's keywords: this is where `cmap=` has always travelled, so
        # naming it in the signature documents the keyword without moving it.
        opts["cmap"] = cmap
    # The channel is named `opacity` here and `alpha` where it reaches matplotlib, so it travels on
    # under the engine's own spelling — exactly where a caller's `alpha=` always went.
    if opacity is not None:
        opts["alpha"] = opacity
    self._draw(
        LayerRecord(
            # A column is required, so the polygons are always filled by a value: a choropleth.
            _polygon_kind(column),
            source=features,
            name=name,
            visible=visible,
            symbology=Symbology(
                props={
                    "via": "choropleth",
                    "column": column,
                    "scheme": scheme,
                    "k": k,
                }
            ),
            # The classification is folded into the glyph's keywords by the drawer, so what the figure
            # records is the call the caller made; their own engine keywords travel beside it.
            opts=opts,
        )
    )
    return self

hexbin(features, column=None, *, reduce=DEFAULT_HEXBIN_REDUCE, gridsize=50, min_count=None, name=None, visible=True, **opts) #

Aggregate points onto a hexagonal lattice and colour each cell (pyramids points → HexbinGlyph).

The discrete counterpart of :meth:kde: with no column each cell is coloured by how many points fell in it, and with one by the reduce of their values — a number read straight off the colour key, with none of the over-plotting a dense scatter has. The points are reprojected to the display CRS first and the lattice is laid there, so the cells are regular on the map rather than equal-area on the ground. The layer is a choropleth of the aggregate, as :meth:quadtree's is.

Parameters:

Name Type Description Default
features Any

A pyramids FeatureCollection of point geometries, or a path or URL to one (reprojected to the display CRS). Only a path-backed layer can be written down.

required
column str | None

Numeric column aggregated per cell, or None (default) to count the points.

None
reduce Any

How a cell's values aggregate: "mean" (default), "sum", "min", "max", "std", "count", or a function of an array. A named reducer is written into the figure; a function is held beside the layer, and a figure read back elsewhere falls back to "mean". Ignored without a column.

DEFAULT_HEXBIN_REDUCE
gridsize Any

Hexagons across the binned window — a whole number, or an (nx, ny) pair of them. One cell across is the smallest lattice there is, so the counts must be positive.

50
min_count int | None

Leave out cells with fewer points than this, as a whole number of points. None (default) leaves out the empty cells of a count map — which cleopatra would otherwise draw as zeros across the whole window — and is cleopatra's own default with a column.

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the figure is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the axes (#327).

True
**opts Any

Further HexbinGlyph options and the shared styling (cmap, vmin, vmax, scheme, k, color_scale, edge_color, line_width, extent, …).

{}

Returns:

Type Description
Self

This map (chainable). The drawn artist is reached with

Self

meth:~digitalearth.static.core.scene.Scene.artist — map.artist() for the layer just

Self

drawn, or map.artist(layer_id) by name — and a layer the display CRS could not place

Self

drew nothing, so it is absent from the figure and refused there. See

Self

meth:~digitalearth.static.builders.raster.RasterMixin.field for why the return value is the

Self

map rather than the artist (ST-20).

Raises:

Type Description
ValueError

if features is empty or holds non-point geometry; if gridsize is not a positive whole number (or a pair of them), or min_count is not a non-negative whole number — both are checked in the builder, since unchecked they reach matplotlib's hexbin and come back as arithmetic naming neither the method nor the argument; or if column names a column that does not hold numbers, which the reducer needs.

KeyError

if column names no feature attribute — the refusal names hexbin(), the keyword and the column, and lists the columns the features do have.

Examples:

  • Count the points per cell; three coincident points are one cell holding 3:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import geopandas as gpd
    >>> from shapely.geometry import Point
    >>> from pyramids.feature import FeatureCollection
    >>> from digitalearth import Map
    >>> wells = FeatureCollection(gpd.GeoDataFrame(
    ...     {"depth": [2.0, 4.0, 6.0, 100.0]},
    ...     geometry=[Point(0, 0), Point(0, 0), Point(0, 0), Point(8, 8)],
    ...     crs="EPSG:4326",
    ... ))
    >>> m = Map(crs=4326)
    >>> _ = m.hexbin(wells, gridsize=4, name="counts")
    >>> sorted(m.artist("counts").get_array().tolist())
    [1.0, 3.0]
    >>> m.close()
    
  • Aggregate a column instead; the origin cell is the mean of 2, 4 and 6:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import geopandas as gpd
    >>> from shapely.geometry import Point
    >>> from pyramids.feature import FeatureCollection
    >>> from digitalearth import Map
    >>> wells = FeatureCollection(gpd.GeoDataFrame(
    ...     {"depth": [2.0, 4.0, 6.0, 100.0]},
    ...     geometry=[Point(0, 0), Point(0, 0), Point(0, 0), Point(8, 8)],
    ...     crs="EPSG:4326",
    ... ))
    >>> m = Map(crs=4326)
    >>> _ = m.hexbin(wells, "depth", reduce="mean", gridsize=4, name="depths")
    >>> sorted(m.artist("depths").get_array().tolist())
    [4.0, 100.0]
    >>> m.figure_spec.layers.get(m.layer_ids[-1]).symbology.props["via"]
    'hexbin'
    >>> m.close()
    
  • A lattice nothing could be binned onto is refused here, naming the argument, rather than surfacing as matplotlib arithmetic several frames down:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import geopandas as gpd
    >>> from shapely.geometry import Point
    >>> from pyramids.feature import FeatureCollection
    >>> from digitalearth import Map
    >>> wells = FeatureCollection(gpd.GeoDataFrame(
    ...     {"depth": [2.0, 4.0]},
    ...     geometry=[Point(0, 0), Point(8, 8)],
    ...     crs="EPSG:4326",
    ... ))
    >>> m = Map(crs=4326)
    >>> for lattice in ({"gridsize": 0}, {"gridsize": 4, "min_count": -1}):
    ...     try:
    ...         m.hexbin(wells, **lattice)
    ...     except ValueError as error:
    ...         print(error)
    hexbin() needs gridsize= as a whole number >= 1; got 0
    hexbin() needs min_count= as a whole number >= 0; got -1
    >>> m.close()
    
  • A column these features do not carry is named with the columns they do, and one that holds text is refused for what the reducer cannot do with it:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import geopandas as gpd
    >>> from shapely.geometry import Point
    >>> from pyramids.feature import FeatureCollection
    >>> from digitalearth import Map
    >>> wells = FeatureCollection(gpd.GeoDataFrame(
    ...     {"depth": [2.0, 4.0], "site": ["north", "south"]},
    ...     geometry=[Point(0, 0), Point(8, 8)],
    ...     crs="EPSG:4326",
    ... ))
    >>> m = Map(crs=4326)
    >>> try:
    ...     m.hexbin(wells, "dpeth", gridsize=4)
    ... except KeyError as error:
    ...     print(error.args[0])
    hexbin(): column='dpeth' is not a property of these features; available: ['depth', 'site']
    >>> try:
    ...     m.hexbin(wells, "site", gridsize=4)
    ... except ValueError as error:
    ...     print(error)
    hexbin() needs column='site' to name a column of numbers, and it holds str values that are not numbers
    >>> m.close()
    
See Also

kde: the smoothed density of the same points. quadtree: points aggregated into adaptive square cells.

Source code in src/digitalearth/static/builders/vector.py
@_skips_off_limb
def hexbin(
    self,
    features: Any,
    column: str | None = None,
    *,
    reduce: Any = DEFAULT_HEXBIN_REDUCE,
    gridsize: Any = 50,
    min_count: int | None = None,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Aggregate points onto a hexagonal lattice and colour each cell (pyramids points → ``HexbinGlyph``).

    The discrete counterpart of :meth:`kde`: with no ``column`` each cell is coloured by how many points
    fell in it, and with one by the ``reduce`` of their values — a number read straight off the colour
    key, with none of the over-plotting a dense scatter has. The points are reprojected to the display
    CRS first and the lattice is laid there, so the cells are regular on the map rather than equal-area
    on the ground. The layer is a ``choropleth`` of the aggregate, as :meth:`quadtree`'s is.

    Args:
        features: A pyramids ``FeatureCollection`` of point geometries, or a path or URL to one
            (reprojected to the display CRS). Only a path-backed layer can be written down.
        column: Numeric column aggregated per cell, or ``None`` (default) to count the points.
        reduce: How a cell's values aggregate: ``"mean"`` (default), ``"sum"``, ``"min"``, ``"max"``,
            ``"std"``, ``"count"``, or a function of an array. A named reducer is written into the
            figure; a function is held beside the layer, and a figure read back elsewhere falls back to
            ``"mean"``. Ignored without a ``column``.
        gridsize: Hexagons across the binned window — a whole number, or an ``(nx, ny)`` pair of
            them. One cell across is the smallest lattice there is, so the counts must be positive.
        min_count: Leave out cells with fewer points than this, as a whole number of points.
            ``None`` (default) leaves out the empty cells of a count map — which cleopatra would
            otherwise draw as zeros across the whole window — and is cleopatra's own default with a
            ``column``.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the figure is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden, so a switcher reading the figure agrees with the axes (#327).
        **opts: Further ``HexbinGlyph`` options and the shared styling (``cmap``, ``vmin``, ``vmax``,
            ``scheme``, ``k``, ``color_scale``, ``edge_color``, ``line_width``, ``extent``, …).

    Returns:
        This map (chainable). The drawn artist is reached with
        :meth:`~digitalearth.static.core.scene.Scene.artist` — ``map.artist()`` for the layer just
        drawn, or ``map.artist(layer_id)`` by name — and a layer the display CRS could not place
        drew nothing, so it is absent from the figure and refused there. See
        :meth:`~digitalearth.static.builders.raster.RasterMixin.field` for why the return value is the
        map rather than the artist (ST-20).

    Raises:
        ValueError: if ``features`` is empty or holds non-point geometry; if ``gridsize`` is not a
            positive whole number (or a pair of them), or ``min_count`` is not a non-negative whole
            number — both are checked in the builder, since unchecked they reach matplotlib's
            ``hexbin`` and come back as arithmetic naming neither the method nor the argument; or if
            ``column`` names a column that does not hold numbers, which the reducer needs.
        KeyError: if ``column`` names no feature attribute — the refusal names ``hexbin()``, the
            keyword and the column, and lists the columns the features do have.

    Examples:
        - Count the points per cell; three coincident points are one cell holding 3:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import geopandas as gpd
            >>> from shapely.geometry import Point
            >>> from pyramids.feature import FeatureCollection
            >>> from digitalearth import Map
            >>> wells = FeatureCollection(gpd.GeoDataFrame(
            ...     {"depth": [2.0, 4.0, 6.0, 100.0]},
            ...     geometry=[Point(0, 0), Point(0, 0), Point(0, 0), Point(8, 8)],
            ...     crs="EPSG:4326",
            ... ))
            >>> m = Map(crs=4326)
            >>> _ = m.hexbin(wells, gridsize=4, name="counts")
            >>> sorted(m.artist("counts").get_array().tolist())
            [1.0, 3.0]
            >>> m.close()

            ```
        - Aggregate a column instead; the origin cell is the mean of 2, 4 and 6:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import geopandas as gpd
            >>> from shapely.geometry import Point
            >>> from pyramids.feature import FeatureCollection
            >>> from digitalearth import Map
            >>> wells = FeatureCollection(gpd.GeoDataFrame(
            ...     {"depth": [2.0, 4.0, 6.0, 100.0]},
            ...     geometry=[Point(0, 0), Point(0, 0), Point(0, 0), Point(8, 8)],
            ...     crs="EPSG:4326",
            ... ))
            >>> m = Map(crs=4326)
            >>> _ = m.hexbin(wells, "depth", reduce="mean", gridsize=4, name="depths")
            >>> sorted(m.artist("depths").get_array().tolist())
            [4.0, 100.0]
            >>> m.figure_spec.layers.get(m.layer_ids[-1]).symbology.props["via"]
            'hexbin'
            >>> m.close()

            ```
        - A lattice nothing could be binned onto is refused here, naming the argument, rather than
          surfacing as matplotlib arithmetic several frames down:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import geopandas as gpd
            >>> from shapely.geometry import Point
            >>> from pyramids.feature import FeatureCollection
            >>> from digitalearth import Map
            >>> wells = FeatureCollection(gpd.GeoDataFrame(
            ...     {"depth": [2.0, 4.0]},
            ...     geometry=[Point(0, 0), Point(8, 8)],
            ...     crs="EPSG:4326",
            ... ))
            >>> m = Map(crs=4326)
            >>> for lattice in ({"gridsize": 0}, {"gridsize": 4, "min_count": -1}):
            ...     try:
            ...         m.hexbin(wells, **lattice)
            ...     except ValueError as error:
            ...         print(error)
            hexbin() needs gridsize= as a whole number >= 1; got 0
            hexbin() needs min_count= as a whole number >= 0; got -1
            >>> m.close()

            ```
        - A ``column`` these features do not carry is named with the columns they do, and one that
          holds text is refused for what the reducer cannot do with it:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import geopandas as gpd
            >>> from shapely.geometry import Point
            >>> from pyramids.feature import FeatureCollection
            >>> from digitalearth import Map
            >>> wells = FeatureCollection(gpd.GeoDataFrame(
            ...     {"depth": [2.0, 4.0], "site": ["north", "south"]},
            ...     geometry=[Point(0, 0), Point(8, 8)],
            ...     crs="EPSG:4326",
            ... ))
            >>> m = Map(crs=4326)
            >>> try:
            ...     m.hexbin(wells, "dpeth", gridsize=4)
            ... except KeyError as error:
            ...     print(error.args[0])
            hexbin(): column='dpeth' is not a property of these features; available: ['depth', 'site']
            >>> try:
            ...     m.hexbin(wells, "site", gridsize=4)
            ... except ValueError as error:
            ...     print(error)
            hexbin() needs column='site' to name a column of numbers, and it holds str values that are not numbers
            >>> m.close()

            ```

    See Also:
        kde: the smoothed density of the same points.
        quadtree: points aggregated into adaptive square cells.
    """
    gridsize, min_count = _hexbin_lattice(gridsize, min_count)
    held_reduce = None if isinstance(reduce, str) else reduce
    self._draw(
        LayerRecord(
            "choropleth",
            source=features,
            name=name,
            visible=visible,
            symbology=Symbology(
                props={
                    "via": "hexbin",
                    "column": column,
                    "reduce": reduce if isinstance(reduce, str) else None,
                    "gridsize": gridsize,
                    "min_count": min_count,
                }
            ),
            opts=opts,
            key=held_reduce,
        )
    )
    return self

quiver(u_dataset, v_dataset, *, name=None, visible=True, **kwargs) #

Draw a vector field as arrows (VectorGlyph kind="quiver").

Parameters:

Name Type Description Default
u_dataset Any

pyramids Dataset of the u (eastward) component, or a path or URL to one. Only a path-backed layer can be written down — and a u/v pair is not one of those yet, because a layer names one source and a field needs two.

required
v_dataset Any

pyramids Dataset of the v (northward) component, or a path or URL to one.

required
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the figure is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the drawing (#327).

True
**kwargs Any

Forwarded to :meth:_vector — band is the one named argument; the rest is the caller's own VectorGlyph styling, split between the layer's description and the scene (see the class docstring).

{}

Returns:

Type Description
Self

This map (chainable). The drawn artist is reached with

Self

meth:~digitalearth.static.core.scene.Scene.artist — map.artist() for the layer just

Self

drawn, or map.artist(layer_id) by name — and a layer the display CRS could not place

Self

drew nothing, so it is absent from the figure and refused there. See

Self

meth:~digitalearth.static.builders.raster.RasterMixin.field for why the return value is the

Self

map rather than the artist (ST-20).

Raises:

Type Description
ValueError

from VectorGlyph for a styling keyword it does not accept, or when a component is named by an empty string.

FileNotFoundError

when a component's path names nothing.

KeyError

when no resolver is registered for a component's URL scheme.

Source code in src/digitalearth/static/builders/vector.py
def quiver(
    self,
    u_dataset: Any,
    v_dataset: Any,
    *,
    name: str | None = None,
    visible: bool = True,
    **kwargs: Any,
) -> Self:
    """Draw a vector field as arrows (``VectorGlyph`` ``kind="quiver"``).

    Args:
        u_dataset: pyramids ``Dataset`` of the u (eastward) component, or a path or URL to one.
            Only a path-backed layer can be written down — and a u/v pair is not one of those yet,
            because a layer names one source and a field needs two.
        v_dataset: pyramids ``Dataset`` of the v (northward) component, or a path or URL to one.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the figure is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden, so a switcher reading the figure agrees with the drawing (#327).
        **kwargs: Forwarded to :meth:`_vector` — ``band`` is the one named argument; the rest is the
            caller's own ``VectorGlyph`` styling, split between the layer's description and the scene
            (see the class docstring).

    Returns:
        This map (chainable). The drawn artist is reached with
        :meth:`~digitalearth.static.core.scene.Scene.artist` — ``map.artist()`` for the layer just
        drawn, or ``map.artist(layer_id)`` by name — and a layer the display CRS could not place
        drew nothing, so it is absent from the figure and refused there. See
        :meth:`~digitalearth.static.builders.raster.RasterMixin.field` for why the return value is the
        map rather than the artist (ST-20).

    Raises:
        ValueError: from ``VectorGlyph`` for a styling keyword it does not accept, or when a component
            is named by an empty string.
        FileNotFoundError: when a component's path names nothing.
        KeyError: when no resolver is registered for a component's URL scheme.
    """
    self._vector(
        u_dataset, v_dataset, kind="quiver", name=name, visible=visible, **kwargs
    )
    return self

streamplot(u_dataset, v_dataset, *, name=None, visible=True, **kwargs) #

Draw a vector field as streamlines (VectorGlyph kind="streamplot").

Parameters:

Name Type Description Default
u_dataset Any

pyramids Dataset of the u (eastward) component, or a path or URL to one. Only a path-backed layer can be written down — and a u/v pair is not one of those yet, because a layer names one source and a field needs two.

required
v_dataset Any

pyramids Dataset of the v (northward) component, or a path or URL to one.

required
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the figure is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the drawing (#327).

True
**kwargs Any

Forwarded to :meth:_vector — band is the one named argument; the rest is the caller's own VectorGlyph styling, split between the layer's description and the scene (see the class docstring).

{}

Returns:

Type Description
Self

This map (chainable). The drawn artist is reached with

Self

meth:~digitalearth.static.core.scene.Scene.artist — map.artist() for the layer just

Self

drawn, or map.artist(layer_id) by name — and a layer the display CRS could not place

Self

drew nothing, so it is absent from the figure and refused there. See

Self

meth:~digitalearth.static.builders.raster.RasterMixin.field for why the return value is the

Self

map rather than the artist (ST-20).

Raises:

Type Description
ValueError

from VectorGlyph for a styling keyword it does not accept, or when a component is named by an empty string.

FileNotFoundError

when a component's path names nothing.

KeyError

when no resolver is registered for a component's URL scheme.

Source code in src/digitalearth/static/builders/vector.py
def streamplot(
    self,
    u_dataset: Any,
    v_dataset: Any,
    *,
    name: str | None = None,
    visible: bool = True,
    **kwargs: Any,
) -> Self:
    """Draw a vector field as streamlines (``VectorGlyph`` ``kind="streamplot"``).

    Args:
        u_dataset: pyramids ``Dataset`` of the u (eastward) component, or a path or URL to one.
            Only a path-backed layer can be written down — and a u/v pair is not one of those yet,
            because a layer names one source and a field needs two.
        v_dataset: pyramids ``Dataset`` of the v (northward) component, or a path or URL to one.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the figure is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden, so a switcher reading the figure agrees with the drawing (#327).
        **kwargs: Forwarded to :meth:`_vector` — ``band`` is the one named argument; the rest is the
            caller's own ``VectorGlyph`` styling, split between the layer's description and the scene
            (see the class docstring).

    Returns:
        This map (chainable). The drawn artist is reached with
        :meth:`~digitalearth.static.core.scene.Scene.artist` — ``map.artist()`` for the layer just
        drawn, or ``map.artist(layer_id)`` by name — and a layer the display CRS could not place
        drew nothing, so it is absent from the figure and refused there. See
        :meth:`~digitalearth.static.builders.raster.RasterMixin.field` for why the return value is the
        map rather than the artist (ST-20).

    Raises:
        ValueError: from ``VectorGlyph`` for a styling keyword it does not accept, or when a component
            is named by an empty string.
        FileNotFoundError: when a component's path names nothing.
        KeyError: when no resolver is registered for a component's URL scheme.
    """
    self._vector(
        u_dataset,
        v_dataset,
        kind="streamplot",
        name=name,
        visible=visible,
        **kwargs,
    )
    return self

labels(features, column, *, text_size=DEFAULT_LABEL_TEXT_SIZE, color=DEFAULT_LABEL_COLOR, halo_color=DEFAULT_LABEL_HALO_COLOR, halo_width=DEFAULT_LABEL_HALO_WIDTH, offset=None, crs=None, name=None, visible=True, **opts) #

Label every feature with the text in column — one string per feature, from an attribute.

The static third of order 27's text layers (ST-16, #345). WebMap.labels shipped first and the labels kind was registered with it, so a caller could label a collection on a web map and not on a static one; :meth:~digitalearth.static.builders.decoration.DecorationMixin.text is no substitute, since it places one string at one coordinate.

The keywords are WebMap.labels's wherever the two tiers can mean the same thing, which is the point of the Core contract — one spelling per concept:

  • text_size, color — the same, with the same defaults, so one call gives one picture. It is text_size and never size: size is the visual size of a marker on every other builder, and a keyword cannot mean both. matplotlib's own fontsize/size are refused here rather than quietly overwritten.
  • halo_color, halo_width — MapLibre's text halo is matplotlib's path_effects stroke: the same idea, a different spelling, so the keywords carry across and this builder builds the stroke. halo_width=0 draws no halo, and a caller's own path_effects= replaces it.
  • offset — carried, and converted. MapLibre measures it in ems with y pointing down; matplotlib in points with y pointing up. Both are resolved in the drawer, so offset=(0, -1.2) lifts a label off its point by 1.2 of its own text size on either tier.
  • allow_overlap — not carried, and refused rather than accepted. It asks MapLibre's symbol layer to keep colliding labels; matplotlib has no collision index to ask, and draws every label wherever it lands. The tier declares that under label_collision in :data:~digitalearth.static.capabilities.CAPABILITIES, and the refusal quotes that declaration, so the answer a caller gets and the answer a dispatcher reads are one sentence. A crowded column is thinned by filtering the features before drawing them.
  • crs — the Core keyword for this name, and here it has a job the web tier has no use for: it says what a collection declaring no CRS is measured in, which is the one case pyramids cannot reproject. It is never ignored — against a collection with its own CRS it either agrees or is refused (see :func:_labelled_features).

Points are labelled at the point; a line or a polygon at its centroid, which is the fallback every other reader of vector geometry in this package uses. A feature whose value is missing, and one on the far side of a globe, are simply not labelled.

Parameters:

Name Type Description Default
features Any

A pyramids FeatureCollection (or a path or URL to one), of any geometry. Only a path-backed layer can be written down.

required
column str

The attribute the label text is read from. Checked when the features are opened, because a path-referenced layer has none to check at the call.

required
text_size float

Text size in points. Named for the text rather than size, which is a marker's size everywhere else.

DEFAULT_LABEL_TEXT_SIZE
color str

Text colour.

DEFAULT_LABEL_COLOR
halo_color str

Colour of the outline drawn behind the glyphs, which is what keeps a label legible over a raster field or a basemap.

DEFAULT_LABEL_HALO_COLOR
halo_width float

Halo width in points; 0 draws none.

DEFAULT_LABEL_HALO_WIDTH
offset Any | None

(x, y) offset in ems — multiples of text_size — with y down, as MapLibre measures it; e.g. (0, -1.2) to lift the label off its point. None centres it.

None
crs Any

What the features' coordinates are measured in, for a collection that declares none. None (default) reads the collection's own.

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the figure is suffixed -2, -3, … (#321). Unlike :meth:~digitalearth.static.builders.decoration.DecorationMixin.text, it is not also read as a font family — see :func:draw_labels.

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the axes (#327).

True
**opts Any

Forwarded to Axes.annotate (fontname, fontweight, rotation, ha, va, zorder, …), the plain ones described beside the layer as on every other builder.

{}

Returns:

Type Description
Self

This map (chainable). The drawn artist is reached with

Self

meth:~digitalearth.static.core.scene.Scene.artist — map.artist() for the layer just

Self

drawn, or map.artist(layer_id) by name — and a layer the display CRS could not place

Self

drew nothing, so it is absent from the figure and refused there. See

Self

meth:~digitalearth.static.builders.raster.RasterMixin.field for why the return value is the

Self

map rather than the artist (ST-20).

Raises:

Type Description
KeyError

when column is not one of the features' attributes, naming the ones that are.

TypeError

when features is not a vector layer, naming this call and the type.

ValueError

for a column that is not a non-empty name; for a text_size, halo_width or offset a figure could not be written with; for a negative halo_width; for one of the keywords in :data:_LABEL_REFUSED_OPTS; for an empty collection; or when the CRS question above cannot be answered.

Examples:

  • Label each feature with its fid, and count the annotations drawn:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from pyramids.feature import FeatureCollection
    >>> from digitalearth.static import Map
    >>> places = FeatureCollection.read_file("tests/data/points.geojson")
    >>> with Map(crs=places.epsg) as canvas:
    ...     _ = canvas.labels(places, "fid", text_size=9.0, name="names")
    ...     len(canvas.artist("names")) == len(places)
    True
    
See Also

digitalearth.static.builders.decoration.DecorationMixin.text: one string at one coordinate. digitalearth.static.builders.decoration.DecorationMixin.annotate: one string, with an arrow to a point.

Source code in src/digitalearth/static/builders/vector.py
@_skips_off_limb
def labels(
    self,
    features: Any,
    column: str,
    *,
    text_size: float = DEFAULT_LABEL_TEXT_SIZE,
    color: str = DEFAULT_LABEL_COLOR,
    halo_color: str = DEFAULT_LABEL_HALO_COLOR,
    halo_width: float = DEFAULT_LABEL_HALO_WIDTH,
    offset: Any | None = None,
    crs: Any = None,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Label every feature with the text in ``column`` — one string per feature, from an attribute.

    The static third of order 27's text layers (ST-16, #345). ``WebMap.labels`` shipped first and the
    ``labels`` kind was registered with it, so a caller could label a collection on a web map and not on a
    static one; :meth:`~digitalearth.static.builders.decoration.DecorationMixin.text` is no substitute, since
    it places **one** string at **one** coordinate.

    The keywords are ``WebMap.labels``'s wherever the two tiers can mean the same thing, which is the point
    of the Core contract — one spelling per concept:

    * ``text_size``, ``color`` — the same, with the same defaults, so one call gives one picture. It is
      ``text_size`` and never ``size``: ``size`` is the visual size of a *marker* on every other builder,
      and a keyword cannot mean both. matplotlib's own ``fontsize``/``size`` are refused here rather than
      quietly overwritten.
    * ``halo_color``, ``halo_width`` — MapLibre's text halo is matplotlib's ``path_effects`` stroke: the
      same idea, a different spelling, so the keywords carry across and this builder builds the stroke.
      ``halo_width=0`` draws no halo, and a caller's own ``path_effects=`` replaces it.
    * ``offset`` — carried, and converted. MapLibre measures it in **ems** with y pointing *down*;
      matplotlib in points with y pointing up. Both are resolved in the drawer, so ``offset=(0, -1.2)``
      lifts a label off its point by 1.2 of its own text size on either tier.
    * ``allow_overlap`` — **not** carried, and refused rather than accepted. It asks MapLibre's symbol
      layer to keep colliding labels; matplotlib has no collision index to ask, and draws every label
      wherever it lands. The tier declares that under ``label_collision`` in
      :data:`~digitalearth.static.capabilities.CAPABILITIES`, and the refusal quotes that declaration, so
      the answer a caller gets and the answer a dispatcher reads are one sentence. A crowded column is
      thinned by filtering the features before drawing them.
    * ``crs`` — the Core keyword for this name, and here it has a job the web tier has no use for: it says
      what a collection declaring **no** CRS is measured in, which is the one case pyramids cannot
      reproject. It is never ignored — against a collection with its own CRS it either agrees or is
      refused (see :func:`_labelled_features`).

    Points are labelled at the point; a line or a polygon at its centroid, which is the fallback every
    other reader of vector geometry in this package uses. A feature whose value is missing, and one on the
    far side of a globe, are simply not labelled.

    Args:
        features: A pyramids ``FeatureCollection`` (or a path or URL to one), of any geometry. Only a
            path-backed layer can be written down.
        column: The attribute the label text is read from. Checked when the features are opened, because
            a path-referenced layer has none to check at the call.
        text_size: Text size in points. Named for the text rather than ``size``, which is a marker's size
            everywhere else.
        color: Text colour.
        halo_color: Colour of the outline drawn behind the glyphs, which is what keeps a label legible
            over a raster field or a basemap.
        halo_width: Halo width in points; ``0`` draws none.
        offset: ``(x, y)`` offset in ems — multiples of ``text_size`` — with y **down**, as MapLibre
            measures it; e.g. ``(0, -1.2)`` to lift the label off its point. ``None`` centres it.
        crs: What the features' coordinates are measured in, for a collection that declares none.
            ``None`` (default) reads the collection's own.
        name: The caller's own name for the layer, used as its id and its label; ``None`` (default)
            generates one from the kind, and a name already on the figure is suffixed ``-2``, ``-3``, …
            (#321). Unlike :meth:`~digitalearth.static.builders.decoration.DecorationMixin.text`, it is
            **not** also read as a font family — see :func:`draw_labels`.
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it hidden, so a
            switcher reading the figure agrees with the axes (#327).
        **opts: Forwarded to ``Axes.annotate`` (``fontname``, ``fontweight``, ``rotation``, ``ha``,
            ``va``, ``zorder``, …), the plain ones described beside the layer as on every other builder.

    Returns:
        This map (chainable). The drawn artist is reached with
        :meth:`~digitalearth.static.core.scene.Scene.artist` — ``map.artist()`` for the layer just
        drawn, or ``map.artist(layer_id)`` by name — and a layer the display CRS could not place
        drew nothing, so it is absent from the figure and refused there. See
        :meth:`~digitalearth.static.builders.raster.RasterMixin.field` for why the return value is the
        map rather than the artist (ST-20).

    Raises:
        KeyError: when ``column`` is not one of the features' attributes, naming the ones that are.
        TypeError: when ``features`` is not a vector layer, naming this call and the type.
        ValueError: for a ``column`` that is not a non-empty name; for a ``text_size``, ``halo_width`` or
            ``offset`` a figure could not be written with; for a negative ``halo_width``; for one of the
            keywords in :data:`_LABEL_REFUSED_OPTS`; for an empty collection; or when the CRS question
            above cannot be answered.

    Examples:
        - Label each feature with its ``fid``, and count the annotations drawn:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from pyramids.feature import FeatureCollection
            >>> from digitalearth.static import Map
            >>> places = FeatureCollection.read_file("tests/data/points.geojson")
            >>> with Map(crs=places.epsg) as canvas:
            ...     _ = canvas.labels(places, "fid", text_size=9.0, name="names")
            ...     len(canvas.artist("names")) == len(places)
            True

            ```

    See Also:
        digitalearth.static.builders.decoration.DecorationMixin.text: one string at one coordinate.
        digitalearth.static.builders.decoration.DecorationMixin.annotate: one string, with an arrow to a point.
    """
    # At the call as well as in the drawer, because the drawer settles the CRS question before it reaches
    # `_vector_input`'s guard — and an array would be refused for declaring no CRS rather than for being
    # an array, which is the wrong answer to the right question.
    require_drawable(features, caller=_LABELS_CALLER, accepts=("vector",))
    refused = sorted(set(opts).intersection(_LABEL_REFUSED_OPTS))
    if refused:
        reasons = "; ".join(
            f"{key}=: {_LABEL_REFUSED_OPTS[key]}" for key in refused
        )
        raise ValueError(f"{_LABELS_CALLER} does not take {refused} — {reasons}")
    if not isinstance(column, str) or not column.strip():
        raise ValueError(
            f"{_LABELS_CALLER} needs column= as the name of an attribute to read the text from; "
            f"got {column!r}"
        )
    text_size = _as_finite(text_size, "text_size", _LABELS_CALLER)
    halo_width = _as_finite(halo_width, "halo_width", _LABELS_CALLER)
    if halo_width < 0:
        raise ValueError(
            f"{_LABELS_CALLER} needs halo_width= as a width, so zero or more; got {halo_width!r}"
        )
    self._draw(
        LayerRecord(
            "labels",
            source=features,
            name=name,
            visible=visible,
            symbology=Symbology(
                props={
                    "via": "labels",
                    "column": column,
                    "text_size": text_size,
                    "color": color,
                    "halo_color": halo_color,
                    "halo_width": halo_width,
                    # A list, not the caller's tuple: a figure is written to JSON, which has no tuple, so
                    # a described tuple comes back as a list and the two symbologies stop comparing equal
                    # (`travels_in_a_figure`).
                    "offset": _label_offset(offset),
                    # In the shared CRS spelling, as `Map.text(crs=)` records one: a caller may hand in a
                    # CRS object, which a figure written to JSON has no form for.
                    "crs": crs_to_json(crs, "Map.labels(crs=)"),
                }
            ),
            opts=opts,
        )
    )
    return self

set_bounds(bounds=None, *, padding=0.0) #

Frame the figure on a region, or on everything it draws — the Core contract's framing method.

Parameters:

Name Type Description Default
bounds Bounds | Sequence[float] | None

A :class:~digitalearth.base.spec.bounds.Bounds in any CRS — it is reprojected to the display CRS, which is the point of passing one — or a bare (west, south, east, north) sequence taken to be in the display CRS already. That is bbox order: the order Bounds holds its own four numbers in, the order :meth:~digitalearth.base.spec.bounds.Bounds.as_bbox writes and :meth:~digitalearth.base.spec.bounds.Bounds.from_bbox reads, and the order the interactive and web tiers' set_bounds take. Prefer Bounds even so — it states the CRS as well as the ordering, instead of leaving either to position and assumption.

None (the default) fits the figure to its data: the union of what the panel's data layers cover, measured from the artists they actually put on the axes. Only the data band counts — a basemap, a graticule and a coastline are drawn around the subject rather than being it, and a global coastline would otherwise answer every such call with the world. A layer built hidden does not count either.

None
padding float

Breathing room around the frame, as a fraction of its own span — 0.05 leaves a 5% margin on every side. It applies to a rectangle you name exactly as it applies to a fitted one. Note the units are this tier's: a figure is framed in data coordinates here, so a proportion of the span is the only padding that means anything, where the web tier's padding is a number of screen pixels.

0.0

Returns:

Type Description
Self

This map, so the call chains (Map(crs=3857).set_bounds(bounds).coastlines()). The Core

Self

declares returns="self" for this name, and every tier that has it answers that way — the

Self

static, interactive and web tiers; the 3-D tier declares the name pending, in

Self

base.contract.PENDING["3d"], as *"Scene3D.domain() frames the camera on a named region or a

Self

box; the Core-spelled set_bounds(bounds, padding) is not yet adopted here"*. That tier frames to

Self

an extent through Scene3D.domain() (its domain feature) rather than through a set_bounds of

Self

this shape, so "set_bounds" in CAPABILITIES.absent is False — and so is

Self

"domain" in CAPABILITIES.absent, now that domain is a declared feature rather than an absent

Self

one. The spelling this tier used to carry returned None, so one line worked on one tier and

Self

raised on another.

Raises:

Type Description
ValueError

if the sequence form does not hold exactly four values; if bounds=None and the figure draws nothing with an extent, because silently doing nothing is indistinguishable from the call being dropped; or, from Bounds, for a non-finite edge or a padding below -0.5, which would turn the frame inside out. Also when the map carries a graticule whose stored step would draw more than :data:MAX_GRATICULE_LINES lines across the view this call frames — a fine step legal on a small view is over budget once the view is enlarged (review H1). The reframe is atomic: such a refusal restores the view this call tried to set, so the map is left exactly as it was rather than framed on the new view with the old grid (review R2-M1).

Warns:

Type Description
UserWarning

naming every degree a labelled graticule's re-label cannot place in the view this call has just framed — graticule()'s own warning, reaching the caller from here because this is the call that moved the view out from under the labels. Measured on Map(crs=3413): a 30-degree grid built unframed carries 18 degrees, and framing it on [-3e6, -3e6, 3e6, 3e6] leaves 5 and names the 8 the polar projection puts outside that square. matplotlib raises one of its own for a singular limit, as the note below says.

Notes

A flipped pair is honoured in the sequence form: an east west of its west inverts the x axis, which is how matplotlib expresses invert_xaxis through the limits, and padding grows such an axis outwards rather than inwards. :attr:viewport reports the region either way round: a Bounds refuses corners the wrong way round, and the direction an axis runs in is a property of the axes rather than of the region shown.

The sequence used to be read as matplotlib's own [xmin, xmax, ymin, ymax], which is the order the axes limits are set in and the order the method carried under its old name. It was the only spelling in the package that read four bare numbers that way, so one call framed two different rectangles across the 2-D tiers; the matplotlib ordering is reachable from Bounds alone now, through :meth:~digitalearth.base.spec.bounds.Bounds.as_mpl.

A graticule is re-cut and re-labelled against the view this call leaves behind, because its lines are cut to the view and a degree label is positioned in the view it is read off, and a flat map has no render-time pass to revisit either (:meth:_relabel_graticule, reviews R2-M2 and #393). The lines are re-cut even when the grid is bare (labels=False), since they depend on the view whether or not they carry degrees. This is therefore the one call that redraws a graticule layer without graticule() being written, so it carries that method's placement warning — see Warns.

What :attr:viewport reports is read back off the axes once the limits are set, so it is the rectangle the figure is holding rather than the one that was asked for. The two differ for a frame of zero span — a fit onto a single point, or padding=-0.5, the bottom of the legal range: matplotlib refuses a singular limit and expands it (by 5% of the value, warning as it goes), and the region reported is that expanded one. It is read at framing time and not re-read, so a later builder that autoscales the axes moves the picture without moving what this reports.

Examples:

  • A rectangle in another CRS is converted, so the frame lands where the data is:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map
    >>> from digitalearth.base.spec import Bounds
    >>> m = Map(crs=3857)
    >>> _ = m.set_bounds(Bounds(0.0, 0.0, 1.0, 1.0, crs=4326))
    >>> round(m.ax.get_xlim()[1])
    111319
    >>> m.close()
    
  • The bare sequence is (west, south, east, north), in the display CRS, and the view reports it back in the order it was written:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map
    >>> m = Map(crs=3857)
    >>> _ = m.set_bounds([0.0, 0.0, 100.0, 50.0])
    >>> [float(v) for v in m.ax.get_xlim()], [float(v) for v in m.ax.get_ylim()]
    ([0.0, 100.0], [0.0, 50.0])
    >>> m.viewport.bounds.as_bbox()
    [0.0, 0.0, 100.0, 50.0]
    >>> m.close()
    
  • padding grows the frame by a fraction of its span:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map
    >>> m = Map(crs=3857)
    >>> _ = m.set_bounds([0.0, 0.0, 10.0, 10.0], padding=0.1)
    >>> [float(v) for v in m.ax.get_xlim()]
    [-1.0, 11.0]
    >>> m.close()
    
Source code in src/digitalearth/static/builders/projection.py
def set_bounds(
    self,
    bounds: Bounds | Sequence[float] | None = None,
    *,
    padding: float = 0.0,
) -> Self:
    """Frame the figure on a region, or on everything it draws — the Core contract's framing method.

    Args:
        bounds: A :class:`~digitalearth.base.spec.bounds.Bounds` in **any** CRS — it is reprojected to
            the display CRS, which is the point of passing one — or a bare
            ``(west, south, east, north)`` sequence taken to be in the display CRS already. That is bbox
            order: the order `Bounds` holds its own four numbers in, the order
            :meth:`~digitalearth.base.spec.bounds.Bounds.as_bbox` writes and
            :meth:`~digitalearth.base.spec.bounds.Bounds.from_bbox` reads, and the order the interactive
            and web tiers' ``set_bounds`` take. Prefer `Bounds` even so — it states the CRS as well as
            the ordering, instead of leaving either to position and assumption.

            ``None`` (the default) **fits the figure to its data**: the union of what the panel's data
            layers cover, measured from the artists they actually put on the axes. Only the ``data``
            band counts — a basemap, a graticule and a coastline are drawn around the subject rather
            than being it, and a global coastline would otherwise answer every such call with the world.
            A layer built hidden does not count either.
        padding: Breathing room around the frame, as a fraction of its own span — ``0.05`` leaves a 5%
            margin on every side. It applies to a rectangle you name exactly as it applies to a fitted
            one. Note the **units are this tier's**: a figure is framed in data coordinates here, so a
            proportion of the span is the only padding that means anything, where the web tier's
            ``padding`` is a number of screen pixels.

    Returns:
        This map, so the call chains (``Map(crs=3857).set_bounds(bounds).coastlines()``). The Core
        declares `returns="self"` for this name, and every tier that has it answers that way — the
        static, interactive and web tiers; the 3-D tier declares the name **pending**, in
        `base.contract.PENDING["3d"]`, as *"Scene3D.domain() frames the camera on a named region or a
        box; the Core-spelled set_bounds(bounds, padding) is not yet adopted here"*. That tier frames to
        an extent through `Scene3D.domain()` (its `domain` feature) rather than through a `set_bounds` of
        this shape, so `"set_bounds" in CAPABILITIES.absent` is `False` — and so is
        `"domain" in CAPABILITIES.absent`, now that `domain` is a declared feature rather than an absent
        one. The spelling this tier used to carry returned `None`, so one line worked on one tier and
        raised on another.

    Raises:
        ValueError: if the sequence form does not hold exactly four values; if ``bounds=None`` and the
            figure draws nothing with an extent, because silently doing nothing is indistinguishable
            from the call being dropped; or, from `Bounds`, for a non-finite edge or a ``padding``
            below ``-0.5``, which would turn the frame inside out. Also when the map carries a
            graticule whose stored step would draw more than
            :data:`MAX_GRATICULE_LINES` lines across the view this call frames — a fine step legal on a
            small view is over budget once the view is enlarged (review H1). The reframe is **atomic**:
            such a refusal restores the view this call tried to set, so the map is left exactly as it
            was rather than framed on the new view with the old grid (review R2-M1).

    Warns:
        UserWarning: naming every degree a **labelled graticule**'s re-label cannot place in the view
            this call has just framed — ``graticule()``'s own warning, reaching the caller from here
            because this is the call that moved the view out from under the labels. Measured on
            ``Map(crs=3413)``: a 30-degree grid built unframed carries 18 degrees, and framing it on
            ``[-3e6, -3e6, 3e6, 3e6]`` leaves 5 and names the 8 the polar projection puts outside that
            square. matplotlib raises one of its own for a singular limit, as the note below says.

    Notes:
        A **flipped** pair is honoured in the sequence form: an ``east`` west of its ``west`` inverts the
        x axis, which is how matplotlib expresses ``invert_xaxis`` through the limits, and ``padding``
        grows such an axis outwards rather than inwards. :attr:`viewport` reports the *region* either way
        round: a `Bounds` refuses corners the wrong way round, and the direction an axis runs in is a
        property of the axes rather than of the region shown.

        The sequence used to be read as matplotlib's own ``[xmin, xmax, ymin, ymax]``, which is the order
        the axes limits are set in and the order the method carried under its old name. It was the only
        spelling in the package that read four bare numbers that way, so one call framed two different
        rectangles across the 2-D tiers; the matplotlib ordering is reachable from `Bounds` alone now,
        through :meth:`~digitalearth.base.spec.bounds.Bounds.as_mpl`.

        A **graticule** is re-cut and re-labelled against the view this call leaves behind, because its
        lines are cut to the view and a degree label is positioned in the view it is read off, and a
        flat map has no render-time pass to revisit either (:meth:`_relabel_graticule`, reviews R2-M2
        and #393). The lines are re-cut even when the grid is bare (``labels=False``), since they depend
        on the view whether or not they carry degrees. This is therefore the one call that redraws a
        graticule layer without ``graticule()`` being written, so it carries that method's placement
        warning — see *Warns*.

        What :attr:`viewport` reports is read **back off the axes** once the limits are set, so it is the
        rectangle the figure is holding rather than the one that was asked for. The two differ for a frame
        of zero span — a fit onto a single point, or ``padding=-0.5``, the bottom of the legal range:
        matplotlib refuses a singular limit and expands it (by 5% of the value, warning as it goes), and
        the region reported is that expanded one. It is read at framing time and not re-read, so a later
        builder that autoscales the axes moves the picture without moving what this reports.

    Examples:
        - A rectangle in another CRS is converted, so the frame lands where the data is:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map
            >>> from digitalearth.base.spec import Bounds
            >>> m = Map(crs=3857)
            >>> _ = m.set_bounds(Bounds(0.0, 0.0, 1.0, 1.0, crs=4326))
            >>> round(m.ax.get_xlim()[1])
            111319
            >>> m.close()

            ```
        - The bare sequence is ``(west, south, east, north)``, in the display CRS, and the view reports it
          back in the order it was written:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map
            >>> m = Map(crs=3857)
            >>> _ = m.set_bounds([0.0, 0.0, 100.0, 50.0])
            >>> [float(v) for v in m.ax.get_xlim()], [float(v) for v in m.ax.get_ylim()]
            ([0.0, 100.0], [0.0, 50.0])
            >>> m.viewport.bounds.as_bbox()
            [0.0, 0.0, 100.0, 50.0]
            >>> m.close()

            ```
        - ``padding`` grows the frame by a fraction of its span:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map
            >>> m = Map(crs=3857)
            >>> _ = m.set_bounds([0.0, 0.0, 10.0, 10.0], padding=0.1)
            >>> [float(v) for v in m.ax.get_xlim()]
            [-1.0, 11.0]
            >>> m.close()

            ```
    """
    frame = self._frame_asked(bounds, padding)
    xmin, xmax, ymin, ymax = frame.limits()
    # The view this call is about to replace, kept so the reframe is atomic. Re-cutting the graticule
    # (`_relabel_graticule`) can refuse — a fine stored step is over budget once the view is enlarged
    # (review H1) — and that refusal must not leave the map framed on the new view with the old grid
    # still on it: the limits move *before* the re-cut, so without this a caught error left the two
    # disagreeing (review R2-M1). On a refusal the view this call tried to set is rolled back and the
    # error re-raised, so the map is exactly as the call found it.
    previous_xlim = self.ax.get_xlim()
    previous_ylim = self.ax.get_ylim()
    previous_bounds = self._frame_bounds
    self.ax.set_xlim(xmin, xmax)
    self.ax.set_ylim(ymin, ymax)
    # Read back, not `frame.box`: matplotlib will not hold a singular limit and expands one as it is set,
    # so a zero-span frame — a fit onto one point, or `padding=-0.5` — was recorded as a rectangle the
    # axes was not holding and the figure never showed (review R2-M10).
    self._frame_bounds = self._frame_held(frame.box.crs)
    try:
        self._relabel_graticule()
    except BaseException:
        self.ax.set_xlim(*previous_xlim)
        self.ax.set_ylim(*previous_ylim)
        self._frame_bounds = previous_bounds
        raise
    return self

set_domain(domain=None) #

Set the axes extent from a named region or bbox, reprojected to the display CRS via pyramids.

Parameters:

Name Type Description Default
domain DomainLike | None

A registered region name (e.g. "Europe"), an explicit (west, south, east, north) bbox in EPSG:4326, or None to fall back to the domain passed at construction. A no-op when neither resolves to a domain.

None

Returns:

Type Description
Self

This map, so the call chains like :meth:set_bounds, which it frames through. **The no-op

Self

path answers the map as well**: a call with nothing to resolve frames nothing, and a chain

Self

must survive it (L6).

Raises:

Type Description
ValueError

if a caller-supplied bbox has its corners the wrong way round — including one crossing the antimeridian, which a single rectangle cannot express.

Examples:

  • In a geographic CRS the axes limits equal the named region's bounds:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth.static import Map
    >>> m = Map(crs=4326)
    >>> _ = m.set_domain("europe")
    >>> [float(v) for v in m.ax.get_xlim()]
    [-25.0, 45.0]
    >>> [float(v) for v in m.ax.get_ylim()]
    [34.0, 72.0]
    >>> m.close()
    
Source code in src/digitalearth/static/builders/projection.py
def set_domain(self, domain: DomainLike | None = None) -> Self:
    """Set the axes extent from a named region or bbox, reprojected to the display CRS via pyramids.

    Args:
        domain: A registered region name (e.g. ``"Europe"``), an explicit ``(west, south, east, north)``
            bbox in EPSG:4326, or ``None`` to fall back to the domain passed at construction. A no-op
            when neither resolves to a domain.

    Returns:
        This map, so the call chains like :meth:`set_bounds`, which it frames through. **The no-op
        path answers the map as well**: a call with nothing to resolve frames nothing, and a chain
        must survive it (L6).

    Raises:
        ValueError: if a caller-supplied bbox has its corners the wrong way round — including one
            crossing the antimeridian, which a single rectangle cannot express.

    Examples:
        - In a geographic CRS the axes limits equal the named region's bounds:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth.static import Map
            >>> m = Map(crs=4326)
            >>> _ = m.set_domain("europe")
            >>> [float(v) for v in m.ax.get_xlim()]
            [-25.0, 45.0]
            >>> [float(v) for v in m.ax.get_ylim()]
            [34.0, 72.0]
            >>> m.close()

            ```
    """
    bbox = resolve_domain(domain if domain is not None else self.domain)
    if bbox is None:
        return self
    # A resolved domain is always EPSG:4326 (see `static/domains.py`), which is exactly the assumption
    # a bare 4-tuple used to carry implicitly. Bounds makes it a value, and does the warp through pyramids.
    try:
        box = Bounds.from_bbox(bbox, crs=4326)
    except ValueError as error:
        # Bounds refuses corners the wrong way round, and its message names only the numbers. A caller
        # who wrote a bbox crossing the antimeridian needs to hear which argument and which ordering.
        raise ValueError(
            f"set_domain got a bbox whose corners are the wrong way round: {tuple(bbox)}. It takes "
            "(west, south, east, north) in EPSG:4326, and cannot express a region crossing the "
            f"antimeridian — split it into two, or set the extent directly ({error})"
        ) from error
    return self.set_bounds(box.to_crs(self.crs))

graticule(lon_step=None, lat_step=None, *, spacing=None, labels=None, name=None, visible=None) #

Add a lon/lat graticule to the map, with its degrees labelled.

A second call replaces the first — the map holds one set of graticule lines, so it draws one graticule — and the description follows: the layer keeps its id and its place in the tree and only what the replacing call named changes. Describing the second call as a second layer would say the map draws two grids where it draws one — and that is also why a name on a replacing call names nothing: the layer already has its id, and taking a new one would break every caller holding the old one.

One rule for the rest of the arguments: a replacing call keeps every option it does not name. A call that names a spacing is asking for a spacing, not for a hidden grid to come back (visible, review R-L5), nor for the degrees of a deliberately bare grid to come back (labels), nor for the step it did not mention to be re-cut at the default (lon_step / lat_step) — the last two used to fall back to their construction defaults, which relabelled and re-cut grids in silence (round 1, M7). spacing is the one argument that overrides what the grid carries without being asked twice, because it names both steps by definition. The frame still outranks all of it: labels=True on a globe is refused whatever the grid it replaces carried.

Which frame draws it, and when. On a flat map — the default — the lines and their labels go on the axes as this call runs. On a globe=True map they are drawn later, by the projection frame (render()/save()/show()), because a globe's grid has to be clipped at the limb with everything else. Before #221 the flat map had no such pass, so this call computed a grid, stored it, and drew nothing at all while the figure described a layer that was drawn.

A later framing call re-cuts and re-labels it. The lines are cut to the view and the degrees are placed in it, so a grid drawn before :meth:set_bounds, :meth:set_domain or :meth:set_global is redrawn by that call against the view it leaves behind (:meth:_relabel_graticule) — the lines are re-cut to the new region and the labels re-placed in it (#393). Until #393 the lines spanned the world whatever the view, so only the labels moved; now a fine grid on a small region draws the handful of lines that region holds rather than the world's. Until R2-M2 the labels were placed once: graticule(spacing=30.0) followed by set_domain("europe") left all 18 degrees outside the axes and off the canvas without a word, and the reverse order of the same two calls drew three. A bare (labels=False) grid is re-cut too — its lines depend on the view even though it carries no degrees — but its degrees do not come back, the rule a replacing call here already follows.

Parameters:

Name Type Description Default
lon_step float | None

Meridian spacing in degrees; None (default) means :data:DEFAULT_GRATICULE_STEP on the call that creates the graticule, and the step the grid already carries on a replacing one. Any of the three must be a finite number greater than zero — 0, a negative, nan and inf are each refused by the keyword that carried them (see Raises).

None
lat_step float | None

Parallel spacing in degrees, the same way round.

None
spacing float | None

One step for both, for a caller who wants a square grid; it overrides the two above, and warns when it does, because a call that names all three has had two of its own arguments thrown away (review R2-L3). The same keyword the web and interactive tiers take, so one call draws one grid on every tier that draws a graticule at all (#324). The values are each engine's own: this tier generates its meridians, so any positive step draws, and so does the web tier — while the interactive tier draws Natural Earth's pre-cut layers and honours only 1, 5, 10, 15, 20 and 30. spacing=7.5 draws here and raises there (review R-L10).

None
labels bool | None

Whether each line carries its degree — "30°E", "60°N", the web tier's own spelling. None (the default) labels the frames that can be labelled, which is every flat map and no globe — and on a replacing call means whatever the grid already carries, so restyling a bare grid leaves it bare; True asks for them and raises on a globe, where there is no edge to hang a degree on (see Raises); False draws the lines bare. Each label sits on its own line, just inside the lower edge of the view for a meridian and the left edge for a parallel, and a degree the display CRS cannot place there is named in a warning rather than dropped in silence.

None
name str | None

The caller's own name for the layer, used as its id and its label on the call that creates it; None (default) generates one from the kind (#321). A replacing call cannot rename the layer, so one that names a different name warns rather than dropping it in silence (review R2-L3).

None
visible bool | None

Whether the graticule is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the axes (#327). None (default) leaves the flag as it is: on the call that creates the layer that means drawn, and on a replacing call it means whatever the caller last chose, so restyling a hidden graticule does not put it back on screen (review R-L5).

None

Returns:

Name Type Description
Self

This map, so the call chains like every other layer builder on the tier

Self

(m.graticule(spacing=30.0).set_global()). It registers graticule-1 and draws, which

Self

makes it a builder by every other test here; it used to hand back nothing, which broke the

Self

chain on the one tier whose visible/name contract is the most elaborate (L6).

Self

The grid itself is reached by id, and a graticule is the layer where the two spellings differ.

Self

Scene.artist(layer_id) hands back what the drawer computed — the list of projected

Self

polylines, 18 of them at the default spacing on an unframed (world) view, as (N, 2) arrays —

Self

because that is this drawer's value, and it answers that way even on a globe whose lines are not

Self

on the axes yet. What is on the axes is Renderer.drawn[layer_id].artists, and it is a

Self

different shape per frame. A flat map carries one LineCollection for the whole grid plus one

Self

Text per labelled line. Both the polylines and the labels track the view since #393: a

Self

framed view cuts the lines to the region it holds and places a degree on each line it can,

Self

whichever order the framing call and this one are written in. Measured on Map(crs=4326), both

orders Self
Self

```

Self

unframed, spacing=30 polylines=18 LineCollection=1 Text=18

Self

framed THEN graticule, spacing=30 polylines= 9 LineCollection=1 Text=6

Self

graticule THEN framed, spacing=30 polylines= 9 LineCollection=1 Text=6

Self

unframed, spacing=60 polylines= 9 LineCollection=1 Text=10

Self

framed THEN graticule, spacing=60 polylines= 5 LineCollection=1 Text=3

Self

graticule THEN framed, spacing=60 polylines= 5 LineCollection=1 Text=3

Self

labels=False, unframed polylines=18 LineCollection=1

Self

labels=False, framed (either order) polylines= 9 LineCollection=1

Self

```

Self

("framed" is [-35, -5, 35, 65].) The two orders agree: a framing call re-cuts and re-labels a

Self

grid drawn before it to the same view a grid drawn after it is cut to. Before #393 the polyline

Self

counts did not clip — a framed grid carried the world's 18 (or 9) lines — and before R2-M2 the

Self

two orders' label counts differed, the second row of each pair carrying the first row's labels,

Self

placed against a view the figure had already left.

Self

A globe's grid is instead drawn by apply_projection_frame as one Line2D per

Self

polyline (measured: 18, and 0 artists before render()). set_visible and remove_layer act

Self

on that second list, so both reach every frame's grid. Neither spelling raises for a graticule

Self

this call built — the KeyError Scene.artist documents is for an id the figure does not hold.

Warns:

Type Description
UserWarning

when spacing is given beside either step, which discards the step; when a replacing call names a name the layer does not already carry, which is discarded because the id is the one thing a replacement cannot change (review R2-L3); and when a degree label cannot be placed, which names it.

Raises:

Type Description
ValueError

for labels=True on a globe=True map, which cannot carry them — see :meth:_labels_asked; and for a step that is not a finite number of degrees greater than zero, naming the keyword that carried it — see :func:_checked_step. 0 used to divide by zero inside the projection, nan and inf to come back as arange: cannot compute length, and a negative step to describe a layer and draw an empty grid for it without a word (review R2-L4). Both refusals land before anything is described, so they cost the figure nothing.

Exception

whatever computing the grid raises, after the description has been put back as it was. A figure must not name a layer that was not drawn, and a refused replacement must not restyle the graticule the map is still drawing (round 2, M1).

Examples:

  • A flat map's grid is one collection, and every line in view carries its degree:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map
    >>> m = Map(crs=4326)
    >>> _ = m.set_bounds([-35.0, -5.0, 35.0, 65.0])
    >>> _ = m.graticule(spacing=30.0)
    >>> sorted({text.get_text() for text in m.ax.texts})
    ['0°', '30°E', '30°N', '30°W', '60°N']
    >>> m.close()
    
  • The lines can be drawn bare:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map
    >>> m = Map(crs=4326)
    >>> _ = m.graticule(spacing=60.0, labels=False)
    >>> len(m.ax.texts)
    0
    >>> m.close()
    
  • A replacing call keeps what it does not name: the grid is re-cut at 60 degrees and stays bare, and its parallels keep the step only the first call named:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map
    >>> m = Map(crs=4326)
    >>> _ = m.set_bounds([-35.0, -5.0, 35.0, 65.0])
    >>> _ = m.graticule(lon_step=30.0, lat_step=45.0, labels=False)
    >>> _ = m.graticule(lon_step=60.0)
    >>> props = m._layer_tree.get(m._graticule_id).symbology.props
    >>> (props["lon_step"], props["lat_step"], props["labels"])
    (60.0, 45.0, False)
    >>> len(m.ax.texts)
    0
    >>> m.close()
    
  • A globe draws the grid unlabelled, and refuses labels=True rather than dropping them quietly — the default labels=None is what lets one line serve both frames:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map
    >>> globe = Map(crs=4326, globe=True)
    >>> _ = globe.graticule(spacing=30.0)
    >>> len(globe.ax.texts)
    0
    >>> globe.graticule(spacing=30.0, labels=True)  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: graticule(labels=True) cannot place degree labels on a globe frame...
    >>> globe.close()
    
  • A degree the frame cannot place is named in a warning, not silently missing: a polar projection framed on a square puts most meridians' anchors outside the view:
    >>> import warnings
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map
    >>> m = Map(crs=3413)
    >>> _ = m.set_bounds([-3.0e6, -3.0e6, 3.0e6, 3.0e6])
    >>> with warnings.catch_warnings(record=True) as caught:
    ...     warnings.simplefilter("always")
    ...     _ = m.graticule(spacing=30.0)
    >>> message = str(caught[0].message)
    >>> message.split(":")[0]
    'graticule() could not place 8 degree label(s)'
    >>> "150°W" in message, "120°E" in message
    (True, True)
    >>> len(m.ax.texts)
    6
    >>> m.close()
    
Source code in src/digitalearth/static/builders/projection.py
def graticule(
    self,
    lon_step: float | None = None,
    lat_step: float | None = None,
    *,
    spacing: float | None = None,
    labels: bool | None = None,
    name: str | None = None,
    visible: bool | None = None,
) -> Self:
    """Add a lon/lat graticule to the map, with its degrees labelled.

    A second call **replaces** the first — the map holds one set of graticule lines, so it draws one
    graticule — and the description follows: the layer keeps its id and its place in the tree and only
    what the replacing call named changes. Describing the second call as a second layer would say the
    map draws two grids where it draws one — and that is also why a ``name`` on a *replacing* call
    names nothing: the layer already has its id, and taking a new one would break every caller holding
    the old one.

    **One rule for the rest of the arguments: a replacing call keeps every option it does not name.**
    A call that names a spacing is asking for a spacing, not for a hidden grid to come back
    (``visible``, review R-L5), nor for the degrees of a deliberately bare grid to come back
    (``labels``), nor for the step it did not mention to be re-cut at the default (``lon_step`` /
    ``lat_step``) — the last two used to fall back to their construction defaults, which relabelled
    and re-cut grids in silence (round 1, M7). ``spacing`` is the one argument that overrides what the
    grid carries without being asked twice, because it names both steps by definition. The frame still
    outranks all of it: ``labels=True`` on a globe is refused whatever the grid it replaces carried.

    **Which frame draws it, and when.** On a flat map — the default — the lines and their labels go on
    the axes as this call runs. On a ``globe=True`` map they are drawn later, by the projection frame
    (``render()``/``save()``/``show()``), because a globe's grid has to be clipped at the limb with
    everything else. Before #221 the *flat* map had no such pass, so this call computed a grid, stored
    it, and drew nothing at all while the figure described a layer that was drawn.

    **A later framing call re-cuts and re-labels it.** The lines are cut to the view and the degrees
    are placed in it, so a grid drawn before :meth:`set_bounds`, :meth:`set_domain` or
    :meth:`set_global` is redrawn by that call against the view it leaves behind
    (:meth:`_relabel_graticule`) — the lines are re-cut to the new region and the labels re-placed in
    it (#393). Until #393 the lines spanned the world whatever the view, so only the labels moved; now a
    fine grid on a small region draws the handful of lines that region holds rather than the world's.
    Until R2-M2 the labels were placed once: ``graticule(spacing=30.0)`` followed by
    ``set_domain("europe")`` left all 18 degrees outside the axes and off the canvas without a word,
    and the reverse order of the same two calls drew three. A bare (``labels=False``) grid is re-cut
    too — its lines depend on the view even though it carries no degrees — but its degrees do not come
    back, the rule a *replacing* call here already follows.

    Args:
        lon_step: Meridian spacing in degrees; ``None`` (default) means
            :data:`DEFAULT_GRATICULE_STEP` on the call that **creates** the graticule, and the step
            the grid already carries on a *replacing* one. Any of the three must be a finite number
            greater than zero — ``0``, a negative, ``nan`` and ``inf`` are each refused by the keyword
            that carried them (see *Raises*).
        lat_step: Parallel spacing in degrees, the same way round.
        spacing: One step for both, for a caller who wants a square grid; it overrides the two
            above, and **warns** when it does, because a call that names all three has had two of
            its own arguments thrown away (review R2-L3). The same **keyword** the web and
            interactive tiers take, so one call draws one grid on every tier that draws a graticule
            at all (#324). The **values** are each engine's own: this tier generates its meridians,
            so any positive step draws, and so does the web tier — while the interactive tier draws
            Natural Earth's pre-cut layers and honours only ``1``, ``5``, ``10``, ``15``, ``20`` and
            ``30``. ``spacing=7.5`` draws here and raises there (review R-L10).
        labels: Whether each line carries its degree — ``"30°E"``, ``"60°N"``, the web tier's own
            spelling. ``None`` (the default) labels the frames that can be labelled, which is every
            flat map and no globe — and on a *replacing* call means whatever the grid already
            carries, so restyling a bare grid leaves it bare; ``True`` asks for them and **raises** on
            a globe, where there is no edge to hang a degree on (see *Raises*); ``False`` draws the
            lines bare. Each label sits on
            its own line, just inside the lower edge of the view for a meridian and the left edge for a
            parallel, and a degree the display CRS cannot place there is **named in a warning** rather
            than dropped in silence.
        name: The caller's own name for the layer, used as its id and its label on the call that
            **creates** it; ``None`` (default) generates one from the kind (#321). A *replacing*
            call cannot rename the layer, so one that names a different name **warns** rather than
            dropping it in silence (review R2-L3).
        visible: Whether the graticule is drawn. ``False`` builds it hidden **and** describes it
            hidden, so a switcher reading the figure agrees with the axes (#327). ``None`` (default)
            leaves the flag as it is: on the call that creates the layer that means drawn, and on a
            *replacing* call it means whatever the caller last chose, so restyling a hidden graticule
            does not put it back on screen (review R-L5).

    Returns:
        This map, so the call chains like every other layer builder on the tier
        (``m.graticule(spacing=30.0).set_global()``). It registers ``graticule-1`` and draws, which
        makes it a builder by every other test here; it used to hand back nothing, which broke the
        chain on the one tier whose `visible`/`name` contract is the most elaborate (L6).

        The grid itself is reached by id, and a graticule is the layer where the two spellings differ.
        `Scene.artist(layer_id)` hands back **what the drawer computed** — the list of projected
        polylines, 18 of them at the default spacing on an unframed (world) view, as `(N, 2)` arrays —
        because that is this drawer's value, and it answers that way even on a globe whose lines are not
        on the axes yet. What is *on* the axes is `Renderer.drawn[layer_id].artists`, and it is a
        different shape per frame. A flat map carries one `LineCollection` for the whole grid plus one
        `Text` per **labelled line**. Both the polylines and the labels track the *view* since #393: a
        framed view cuts the lines to the region it holds and places a degree on each line it can,
        whichever order the framing call and this one are written in. Measured on `Map(crs=4326)`, both
        orders:

        ```
        unframed, spacing=30                  polylines=18  LineCollection=1  Text=18
        framed THEN graticule, spacing=30     polylines= 9  LineCollection=1  Text=6
        graticule THEN framed, spacing=30     polylines= 9  LineCollection=1  Text=6
        unframed, spacing=60                  polylines= 9  LineCollection=1  Text=10
        framed THEN graticule, spacing=60     polylines= 5  LineCollection=1  Text=3
        graticule THEN framed, spacing=60     polylines= 5  LineCollection=1  Text=3
        labels=False, unframed                polylines=18  LineCollection=1
        labels=False, framed (either order)   polylines= 9  LineCollection=1
        ```

        ("framed" is `[-35, -5, 35, 65]`.) The two orders agree: a framing call re-cuts and re-labels a
        grid drawn before it to the same view a grid drawn after it is cut to. Before #393 the polyline
        counts did not clip — a framed grid carried the world's 18 (or 9) lines — and before R2-M2 the
        two orders' label counts differed, the second row of each pair carrying the first row's labels,
        placed against a view the figure had already left.

        A globe's grid is instead drawn by `apply_projection_frame` as one `Line2D` per
        polyline (measured: 18, and 0 artists before `render()`). `set_visible` and `remove_layer` act
        on that second list, so both reach every frame's grid. Neither spelling raises for a graticule
        this call built — the `KeyError` `Scene.artist` documents is for an id the figure does not hold.

    Warns:
        UserWarning: when ``spacing`` is given beside either step, which discards the step; when a
            *replacing* call names a ``name`` the layer does not already carry, which is discarded
            because the id is the one thing a replacement cannot change (review R2-L3); and when a
            degree label cannot be placed, which names it.

    Raises:
        ValueError: for ``labels=True`` on a ``globe=True`` map, which cannot carry them — see
            :meth:`_labels_asked`; and for a step that is not a finite number of degrees greater than
            zero, naming the keyword that carried it — see :func:`_checked_step`. ``0`` used to divide
            by zero inside the projection, ``nan`` and ``inf`` to come back as ``arange: cannot
            compute length``, and a **negative** step to describe a layer and draw an empty grid for
            it without a word (review R2-L4). Both refusals land before anything is described, so they
            cost the figure nothing.
        Exception: whatever computing the grid raises, after the description has been put back as it
            was. A figure must not name a layer that was not drawn, and a refused *replacement* must
            not restyle the graticule the map is still drawing (round 2, M1).

    Examples:
        - A flat map's grid is one collection, and every line in view carries its degree:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map
            >>> m = Map(crs=4326)
            >>> _ = m.set_bounds([-35.0, -5.0, 35.0, 65.0])
            >>> _ = m.graticule(spacing=30.0)
            >>> sorted({text.get_text() for text in m.ax.texts})
            ['0°', '30°E', '30°N', '30°W', '60°N']
            >>> m.close()

            ```
        - The lines can be drawn bare:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map
            >>> m = Map(crs=4326)
            >>> _ = m.graticule(spacing=60.0, labels=False)
            >>> len(m.ax.texts)
            0
            >>> m.close()

            ```
        - A replacing call keeps what it does not name: the grid is re-cut at 60 degrees and stays
          bare, and its parallels keep the step only the first call named:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map
            >>> m = Map(crs=4326)
            >>> _ = m.set_bounds([-35.0, -5.0, 35.0, 65.0])
            >>> _ = m.graticule(lon_step=30.0, lat_step=45.0, labels=False)
            >>> _ = m.graticule(lon_step=60.0)
            >>> props = m._layer_tree.get(m._graticule_id).symbology.props
            >>> (props["lon_step"], props["lat_step"], props["labels"])
            (60.0, 45.0, False)
            >>> len(m.ax.texts)
            0
            >>> m.close()

            ```
        - A globe draws the grid unlabelled, and **refuses** `labels=True` rather than dropping them
          quietly — the default `labels=None` is what lets one line serve both frames:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map
            >>> globe = Map(crs=4326, globe=True)
            >>> _ = globe.graticule(spacing=30.0)
            >>> len(globe.ax.texts)
            0
            >>> globe.graticule(spacing=30.0, labels=True)  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: graticule(labels=True) cannot place degree labels on a globe frame...
            >>> globe.close()

            ```
        - A degree the frame cannot place is **named in a warning**, not silently missing: a polar
          projection framed on a square puts most meridians' anchors outside the view:
            ```python
            >>> import warnings
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map
            >>> m = Map(crs=3413)
            >>> _ = m.set_bounds([-3.0e6, -3.0e6, 3.0e6, 3.0e6])
            >>> with warnings.catch_warnings(record=True) as caught:
            ...     warnings.simplefilter("always")
            ...     _ = m.graticule(spacing=30.0)
            >>> message = str(caught[0].message)
            >>> message.split(":")[0]
            'graticule() could not place 8 degree label(s)'
            >>> "150°W" in message, "120°E" in message
            (True, True)
            >>> len(m.ax.texts)
            6
            >>> m.close()

            ```
    """
    # Read before anything is described: a replacing call keeps every option it does not name, and
    # the layer it replaces is the only record of what those options were.
    carried = _GraticuleSteps.held_by(self._graticule_held())
    steps = _GraticuleSteps.asked(
        lon_step,
        lat_step,
        spacing,
        self._labels_asked(labels, carried),
        carried,
        window=None if self.globe else _view_window(self),
    )
    edit = self._describe_graticule(steps.symbology(), name=name, visible=visible)
    # Described first, then drawn — but through the renderer directly rather than through
    # `Scene._draw`, because a second call replaces the layer it already has rather than adding one,
    # and the funnel only knows how to add. The undo the funnel owns is therefore spelled by the edit,
    # which is the only thing that knows which of the two shapes this call took.
    try:
        self._renderer.draw_layer(self.figure_spec, edit.held)
    except BaseException:
        edit.undo(self)
        raise
    return self

basemap(provider=None, *, api_key=None, preset=None, name=None, visible=True, **kwargs) #

Add an XYZ-tile basemap to the axes via cleopatra's GeoMixin.add_tiles in the display CRS.

provider is passed through to cleopatra unchanged — a provider name or an xyzservices.TileProvider — with two additions. The name of a keyed basemap preset (see :mod:digitalearth.base.basemaps) is resolved here into a configured provider, with its credential read from the environment and its coverage checked against the map's domain first. And the four cross-tier basemap names (:data:~digitalearth.base.basemaps.DEFAULT_BASEMAP_PROVIDER among them) are translated into the xyzservices paths that request the same tiles the interactive and web tiers do — including when provider is omitted, which means the shared default here just as it does there, rather than cleopatra's own OpenStreetMap.Mapnik (#247).

Parameters:

Name Type Description Default
provider Any

A cleopatra/xyzservices provider name, an xyzservices.TileProvider, a cleopatra.basemap.ogc WMSProvider/WMTSProvider, one of the cross-tier names ("CartoLight"/"CartoDark"/"CartoVoyager"/"OSM"), a keyed preset name such as "Planet.NICFI", or None for :data:~digitalearth.base.basemaps.DEFAULT_BASEMAP_PROVIDER. An OGC provider is recorded in the figure field by field, minus its extra_params, so a figure read back through Map.from_figure or to_backend(spec, "matplotlib") asks the same service — unauthenticated, since the credential does not travel. Another tier cannot replay a static basemap layer at all, OGC or named; see docs/reference/basemaps.md.

None
api_key str | None

Credential for a keyed preset; None reads the preset's environment variable.

None
preset dict | None

The keyed preset's own keywords, as a dict (for NICFI: date, flavour, mosaic). A dict rather than loose keywords because **kwargs here belongs to add_tiles, and the three tiers take presets the same way.

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the figure is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the axes (#327).

True
**kwargs Any

Forwarded to add_tiles.

{}

Returns:

Type Description
Self

This map (chainable). What :meth:~digitalearth.static.core.scene.Scene.artist answers for this

Self

layer's id is the axes, because cleopatra's add_tiles draws onto them and hands them

Self

back rather than naming what it added (its own Returns: reads *"matplotlib.axes.Axes: The

Self

same axes, for chaining"*) — the same situation as the Natural-Earth layers on a flat map, and

Self

the same wording. The tile AxesImage is the layer's all the same, which is what

Self

meth:~digitalearth.static.core.scene.Scene.set_visible and

Self

meth:~digitalearth.static.core.scene.Scene.remove_layer reach; no public accessor names it

Self

(round 2, M5 — the claim this replaces said artist did, and

Self

tests/static/test_basemap_tile_artist.py is where that is measured against the real

Self

engine). Tiles that cannot be fetched raise rather than answering None, and the layer is

Self

dropped from the description with them.

Raises:

Type Description
ValueError

when a keyed preset is unknown, its credential is unavailable, when a preset or an api_key is passed to an ordinary provider, when a preset keyword is passed loose instead of in preset, or when the extent being drawn — the declared domain if there is one, else the current axes limits — lies entirely outside the coverage. Two more come from cleopatra as the tiles are fetched, and are refusals of this call all the same: Axes have no data extent. Plot data before adding a basemap. when nothing has framed the axes yet (a declared domain alone does not — it is applied at render time), and Unknown tile provider: '<provider>'... for a name neither this tier's table nor xyzservices holds. In every case the layer is not left in the description.

TypeError

when a preset keyword is missing or misspelled, naming the preset and its keywords.

Examples:

  • A keyed preset resolves its own provider and credential:
    >>> from digitalearth import Map                       # doctest: +SKIP
    >>> tiled = Map(domain=(-60, -5, -55, 0)).basemap(     # doctest: +SKIP
    ...     "Planet.NICFI", preset={"date": "2024-01", "flavour": "visual"}
    ... )                                                  # doctest: +SKIP
    >>> tiled.artist("basemap-1")                          # doctest: +SKIP
    
  • A preset keyword passed loose is refused by name, and nothing is described:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map
    >>> with Map() as m:
    ...     try:
    ...         m.basemap("OSM", date="2024-01")
    ...     except ValueError as error:
    ...         print(str(error).split(";")[0])
    ...     m.layer_ids
    basemap() takes preset keywords in preset={...}, not loose
    []
    
  • Tiles need a framed extent to cover, so a basemap on an untouched axes is refused rather than drawn blank:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map
    >>> with Map() as m:
    ...     try:
    ...         m.basemap()
    ...     except ValueError as error:
    ...         print(error)
    ...     m.layer_ids
    Axes have no data extent. Plot data before adding a basemap.
    []
    
See Also

digitalearth.base.basemaps: the keyed-preset definitions this resolves.

Source code in src/digitalearth/static/builders/decoration.py
def basemap(
    self,
    provider: Any = None,
    *,
    api_key: str | None = None,
    preset: dict | None = None,
    name: str | None = None,
    visible: bool = True,
    **kwargs: Any,
) -> Self:
    """Add an XYZ-tile basemap to the axes via cleopatra's ``GeoMixin.add_tiles`` in the display CRS.

    ``provider`` is passed through to cleopatra unchanged — a provider name or an
    ``xyzservices.TileProvider`` — with two additions. The name of a **keyed** basemap preset (see
    :mod:`digitalearth.base.basemaps`) is resolved here into a configured provider, with its credential
    read from the environment and its coverage checked against the map's domain first. And the four
    cross-tier basemap names (:data:`~digitalearth.base.basemaps.DEFAULT_BASEMAP_PROVIDER` among them)
    are translated into the ``xyzservices`` paths that request the same tiles the interactive and web
    tiers do — including when ``provider`` is omitted, which means the shared default here just as it
    does there, rather than cleopatra's own ``OpenStreetMap.Mapnik`` (#247).

    Args:
        provider: A cleopatra/``xyzservices`` provider name, an ``xyzservices.TileProvider``, a
            ``cleopatra.basemap.ogc`` ``WMSProvider``/``WMTSProvider``, one of the cross-tier names
            (``"CartoLight"``/``"CartoDark"``/``"CartoVoyager"``/``"OSM"``), a keyed preset name such as
            ``"Planet.NICFI"``, or ``None`` for
            :data:`~digitalearth.base.basemaps.DEFAULT_BASEMAP_PROVIDER`. An OGC provider is recorded in
            the figure field by field, minus its ``extra_params``, so a figure read back through
            ``Map.from_figure`` or ``to_backend(spec, "matplotlib")`` asks the same service —
            unauthenticated, since the credential does not travel. Another *tier* cannot replay a
            static basemap layer at all, OGC or named; see ``docs/reference/basemaps.md``.
        api_key: Credential for a keyed preset; ``None`` reads the preset's environment variable.
        preset: The keyed preset's own keywords, as a dict (for NICFI: ``date``, ``flavour``,
            ``mosaic``). A dict rather than loose keywords because ``**kwargs`` here belongs to
            ``add_tiles``, and the three tiers take presets the same way.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the figure is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden, so a switcher reading the figure agrees with the axes (#327).
        **kwargs: Forwarded to ``add_tiles``.

    Returns:
        This map (chainable). What :meth:`~digitalearth.static.core.scene.Scene.artist` answers for this
        layer's id is **the axes**, because cleopatra's ``add_tiles`` draws onto them and hands them
        back rather than naming what it added (its own ``Returns:`` reads *"matplotlib.axes.Axes: The
        same axes, for chaining"*) — the same situation as the Natural-Earth layers on a flat map, and
        the same wording. The tile ``AxesImage`` is the layer's all the same, which is what
        :meth:`~digitalearth.static.core.scene.Scene.set_visible` and
        :meth:`~digitalearth.static.core.scene.Scene.remove_layer` reach; no public accessor names it
        (round 2, M5 — the claim this replaces said ``artist`` did, and
        ``tests/static/test_basemap_tile_artist.py`` is where that is measured against the real
        engine). Tiles that cannot be fetched raise rather than answering ``None``, and the layer is
        dropped from the description with them.

    Raises:
        ValueError: when a keyed preset is unknown, its credential is unavailable, when a `preset`
            or an `api_key` is passed to an ordinary provider, when a preset keyword is passed loose
            instead of in `preset`, or when the extent being drawn — the declared `domain` if there
            is one, else the current axes limits — lies entirely outside the coverage. Two more come
            from cleopatra as the tiles are fetched, and are refusals of this call all the same:
            `Axes have no data extent. Plot data before adding a basemap.` when nothing has framed the
            axes yet (a declared `domain` alone does not — it is applied at render time), and
            `Unknown tile provider: '<provider>'...` for a name neither this tier's table nor
            `xyzservices` holds. In every case the layer is not left in the description.
        TypeError: when a preset keyword is missing or misspelled, naming the preset and its keywords.

    Examples:
        - A keyed preset resolves its own provider and credential:
            ```python
            >>> from digitalearth import Map                       # doctest: +SKIP
            >>> tiled = Map(domain=(-60, -5, -55, 0)).basemap(     # doctest: +SKIP
            ...     "Planet.NICFI", preset={"date": "2024-01", "flavour": "visual"}
            ... )                                                  # doctest: +SKIP
            >>> tiled.artist("basemap-1")                          # doctest: +SKIP

            ```
        - A preset keyword passed loose is refused by name, and nothing is described:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map
            >>> with Map() as m:
            ...     try:
            ...         m.basemap("OSM", date="2024-01")
            ...     except ValueError as error:
            ...         print(str(error).split(";")[0])
            ...     m.layer_ids
            basemap() takes preset keywords in preset={...}, not loose
            []

            ```
        - Tiles need a framed extent to cover, so a basemap on an untouched axes is refused rather
          than drawn blank:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map
            >>> with Map() as m:
            ...     try:
            ...         m.basemap()
            ...     except ValueError as error:
            ...         print(error)
            ...     m.layer_ids
            Axes have no data extent. Plot data before adding a basemap.
            []

            ```

    See Also:
        digitalearth.base.basemaps: the keyed-preset definitions this resolves.
    """
    loose = sorted(set(kwargs) & PRESET_KEYWORDS)
    if loose:
        # These would otherwise reach add_tiles and fail there, or worse, be accepted and ignored.
        raise ValueError(
            f"basemap() takes preset keywords in preset={{...}}, not loose; move {loose} into it — "
            f"basemap({provider!r}, preset={{{loose[0]!r}: ...}})"
        )
    if not is_keyed_basemap(provider):
        if preset:
            raise ValueError(
                f"basemap({provider!r}) takes no preset keywords; {sorted(preset)} apply only to a "
                f"keyed preset such as 'Planet.NICFI'"
            )
        if api_key is not None:
            # Dropping it silently would leave a caller believing they had authenticated.
            raise ValueError(
                f"basemap({provider!r}) takes no api_key; it is a token-free source. Credentials apply "
                f"only to a keyed preset such as 'Planet.NICFI'"
            )
    return self._describe_basemap(
        provider, preset, api_key, kwargs, name=name, visible=visible
    )

coastlines(resolution='110m', *, name=None, visible=True, **kwargs) #

Overlay Natural-Earth coastlines (cleopatra.basemap.reference "coastline" layer).

Parameters:

Name Type Description Default
resolution str

Natural-Earth resolution — "110m" (default), "50m" or "10m".

'110m'
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the figure is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the drawing (#327).

True
**kwargs Any

Style overrides laid over this layer's Natural-Earth defaults (:data:_NATURAL_EARTH_STYLE). A plain one — color, linewidth, alpha — is written into the layer's description as well, so a figure drawn on another scene keeps it; a dash tuple or an engine object is held beside the layer alone, and that scene falls back to the Natural-Earth default for it.

{}

Returns:

Type Description
Self

This map (chainable). The coastline is reached through

Self

meth:~digitalearth.static.core.scene.Scene.artist, by this layer's id (round-1 L6): on a globe a

Self

list of Line2D, one per run the limb split the layer into (measured: 57 at 110m through

Self

an orthographic projection); on a flat map the axes, because cleopatra's add_features

Self

draws onto them and hands them back rather than naming what it drew (see

Self

func:draw_natural_earth).

Examples:

  • The reference layers chain, and on a flat map each one's artist is the axes they were drawn onto:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map
    >>> with Map(crs=4326) as m:
    ...     m.coastlines().borders().rivers() is m
    ...     m.layer_ids
    ...     m.artist("coastlines-1") is m.ax
    True
    ['coastlines-1', 'borders-1', 'rivers-1']
    True
    
  • On a globe the limb splits the layer, so the artist is a list of polylines:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map, projections
    >>> with Map(crs=projections.orthographic(0, 0), globe=True) as m:
    ...     lines = m.coastlines("110m", color="black").artist("coastlines-1")
    ...     len(lines) > 1
    ...     type(lines[0]).__name__
    True
    'Line2D'
    
See Also

borders: the same line path for country boundaries. land: the filled counterpart.

Source code in src/digitalearth/static/builders/decoration.py
def coastlines(
    self,
    resolution: str = "110m",
    *,
    name: str | None = None,
    visible: bool = True,
    **kwargs: Any,
) -> Self:
    """Overlay Natural-Earth coastlines (``cleopatra.basemap.reference`` ``"coastline"`` layer).

    Args:
        resolution: Natural-Earth resolution — ``"110m"`` (default), ``"50m"`` or ``"10m"``.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the figure is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden, so a switcher reading the figure agrees with the drawing (#327).
        **kwargs: Style overrides laid over this layer's Natural-Earth defaults
            (:data:`_NATURAL_EARTH_STYLE`). A plain one — ``color``, ``linewidth``, ``alpha`` — is
            written into the layer's description as well, so a figure drawn on another scene keeps it;
            a dash tuple or an engine object is held beside the layer alone, and that scene falls back
            to the Natural-Earth default for it.

    Returns:
        This map (chainable). The coastline is reached through
        :meth:`~digitalearth.static.core.scene.Scene.artist`, by this layer's id (round-1 L6): on a globe a
        **list** of `Line2D`, one per run the limb split the layer into (measured: 57 at 110m through
        an orthographic projection); on a flat map **the axes**, because cleopatra's `add_features`
        draws onto them and hands them back rather than naming what it drew (see
        :func:`draw_natural_earth`).

    Examples:
        - The reference layers chain, and on a flat map each one's artist is the axes they were drawn
          onto:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map
            >>> with Map(crs=4326) as m:
            ...     m.coastlines().borders().rivers() is m
            ...     m.layer_ids
            ...     m.artist("coastlines-1") is m.ax
            True
            ['coastlines-1', 'borders-1', 'rivers-1']
            True

            ```
        - On a globe the limb splits the layer, so the artist is a **list** of polylines:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map, projections
            >>> with Map(crs=projections.orthographic(0, 0), globe=True) as m:
            ...     lines = m.coastlines("110m", color="black").artist("coastlines-1")
            ...     len(lines) > 1
            ...     type(lines[0]).__name__
            True
            'Line2D'

            ```

    See Also:
        borders: the same line path for country boundaries.
        land: the filled counterpart.
    """
    return self._natural_earth(
        "coastline", resolution, zorder=2.5, name=name, visible=visible, **kwargs
    )

nightshade(when, *, refraction=DEFAULT_REFRACTION, n=DEFAULT_TERMINATOR_SAMPLES, name=None, visible=True, **style) #

Shade the night side of the day/night terminator at one instant.

The terminator is computed by cleopatra (cleopatra.basemap.solar, a low-precision solar position good to well under a degree) and projected into the display CRS through pyramids. A night region that holds a pole is shaded to the pole on a flat map, and a globe shades only its visible hemisphere. On an axes nothing has framed yet, the map is fitted to the shade and then pulled back inside the display CRS's own extent, so a projection that places the pole far outside its map (EPSG:3031 puts it 1.4e10 m out) still frames the region it covers; a framed view is kept.

Parameters:

Name Type Description Default
when Any

The instant, as a datetime or ISO 8601 text. One with no time zone is UTC. The figure records it as UTC ISO text, so a figure read back draws the same shade.

required
refraction float

The solar altitude, in degrees, that defines the terminator — -0.83 (default) for sunrise and sunset, -6/-12/-18 for the civil, nautical and astronomical twilight lines. Must lie in (-90, 0].

DEFAULT_REFRACTION
n int

Samples along the terminator. On a globe there is no terminator polygon to sample — the shade is filled from a display grid — so n sets that grid's resolution in proportion instead: the default draws a 400-sample side, and a quarter of the default draws a 100-sample side, measured at about 0.01 s against about 0.16 s for the shade itself. Both are small beside the globe's own projection frame, which costs about 1.7 s and is computed once per globe whatever n is, so it dominates a first render either way. Either way n is the one knob for the shade's fidelity, and the figure records it — where before it was recorded and then ignored on a globe.

DEFAULT_TERMINATOR_SAMPLES
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the figure is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the axes (#327).

True
**style Any

Forwarded to the PolyCollection (facecolor/color, alpha, zorder, …). The default is black at alpha=0.35. facecolor and color are the same keyword here, and None in either means "not given", so the default is drawn — it is not passed through to matplotlib's cycle colour, which drew a night shade in blue (round 4, L8). alpha=0 is honoured as the invisible shade it asks for, not read as unset. A globe fills a contourf rather than a polygon, so it draws no outline: edgecolor (and linewidth/linestyle with it) is resolved — an invalid colour is refused on either frame — and then dropped there, where a flat map draws it.

{}

Returns:

Type Description
Self

This map (chainable). The shade's PolyCollection — on a globe, the filled ContourSet it

Self

is drawn as there — is reached through :meth:~digitalearth.static.core.scene.Scene.artist, by this

Self

layer's id (round-1 L6). A globe whose visible side holds no night draws nothing and registers

Self

no layer, which is what the None this used to answer with said.

Raises:

Type Description
ValueError

when refraction is outside (-90, 0], when n is not a whole number of at least 4 — the fewest that describe a ring — or when when is text that is not ISO 8601. The layer is not described. Both the refraction and the n refusal are made here, in the builder, so they answer the same way on a flat map and on a globe: cleopatra's own live in add_nightshade and the terminator sampler, which only the flat path calls, and a globe used to take either value silently (round 3, L7 for n; round 4, M2 for refraction).

TypeError

when when is neither a datetime nor text.

Examples:

  • At the March equinox at noon UTC the antimeridian is at midnight and Greenwich at noon:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from datetime import datetime, timezone
    >>> from digitalearth import Map
    >>> m = Map(crs=4326)
    >>> night = m.nightshade(
    ...     datetime(2026, 3, 20, 12, tzinfo=timezone.utc), name="night"
    ... ).artist("night")
    >>> [any(p.contains_point(xy) for p in night.get_paths()) for xy in ((170, 0), (0, 0))]
    [True, False]
    >>> m.figure_spec.layers.get("night").kind
    'nightshade'
    >>> m.close()
    
  • The twilight lines are the same call with another refraction; the figure records it:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map
    >>> m = Map(crs=3857)
    >>> _ = m.nightshade("2026-06-21T12:00:00", refraction=-6.0, alpha=0.2)
    >>> props = m.figure_spec.layers.get(m.layer_ids[-1]).symbology.props
    >>> props["when"], props["refraction"]
    ('2026-06-21T12:00:00+00:00', -6.0)
    >>> m.close()
    
  • color=None is the "not given" matplotlib reads it as, so the default black is drawn rather than the first cycle colour; alpha=0 is the invisible shade it asks for:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map
    >>> with Map(crs=4326) as m:
    ...     shade = m.nightshade(
    ...         "2026-12-21T12:00:00+00:00", color=None, name="black"
    ...     ).artist("black")
    ...     [tuple(round(float(c), 2) for c in face) for face in shade.get_facecolor()]
    ...     faint = m.nightshade(
    ...         "2026-12-21T12:00:00+00:00", alpha=0, name="clear"
    ...     ).artist("clear")
    ...     [tuple(round(float(c), 2) for c in face) for face in faint.get_facecolor()]
    [(0.0, 0.0, 0.0, 0.35)]
    [(0.0, 0.0, 0.0, 0.0)]
    
  • A refraction above the horizon is refused by name on a globe as on a flat map, so one keyword answers one way whatever frame it is drawn on:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map
    >>> for globe in (False, True):
    ...     with Map(crs=4326, globe=globe) as m:
    ...         try:
    ...             m.nightshade("2026-12-21T12:00:00+00:00", refraction=10.0)
    ...         except ValueError as error:
    ...             print(str(error).split(" degrees")[0])
    nightshade() needs refraction= in (-90, 0]
    nightshade() needs refraction= in (-90, 0]
    
See Also

tissot: the other overlay cleopatra's solar module draws.

Source code in src/digitalearth/static/builders/decoration.py
def nightshade(
    self,
    when: Any,
    *,
    refraction: float = DEFAULT_REFRACTION,
    n: int = DEFAULT_TERMINATOR_SAMPLES,
    name: str | None = None,
    visible: bool = True,
    **style: Any,
) -> Self:
    """Shade the night side of the day/night terminator at one instant.

    The terminator is computed by cleopatra (``cleopatra.basemap.solar``, a low-precision solar position
    good to well under a degree) and projected into the display CRS through pyramids. A night region that
    holds a pole is shaded to the pole on a flat map, and a globe shades only its visible hemisphere. On
    an axes nothing has framed yet, the map is fitted to the shade and then pulled back inside the
    display CRS's own extent, so a projection that places the pole far outside its map (EPSG:3031 puts
    it ``1.4e10`` m out) still frames the region it covers; a framed view is kept.

    Args:
        when: The instant, as a ``datetime`` or ISO 8601 text. One with no time zone is UTC. The figure
            records it as UTC ISO text, so a figure read back draws the same shade.
        refraction: The solar altitude, in degrees, that defines the terminator — ``-0.83`` (default)
            for sunrise and sunset, ``-6``/``-12``/``-18`` for the civil, nautical and astronomical
            twilight lines. Must lie in ``(-90, 0]``.
        n: Samples along the terminator. On a globe there is no terminator polygon to sample — the
            shade is filled from a display grid — so ``n`` sets that grid's resolution in proportion
            instead: the default draws a 400-sample side, and a quarter of the default draws a
            100-sample side, measured at about 0.01 s against about 0.16 s for the shade itself. Both
            are small beside the globe's own projection frame, which costs about 1.7 s and is computed
            once per globe whatever ``n`` is, so it dominates a first render either way. Either way
            ``n`` is the one knob for the shade's fidelity, and the figure records it — where before it
            was recorded and then ignored on a globe.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the figure is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden, so a switcher reading the figure agrees with the axes (#327).
        **style: Forwarded to the ``PolyCollection`` (``facecolor``/``color``, ``alpha``, ``zorder``,
            …). The default is black at ``alpha=0.35``. ``facecolor`` and ``color`` are the same
            keyword here, and ``None`` in either means "not given", so the default is drawn — it is
            **not** passed through to matplotlib's cycle colour, which drew a night shade in blue
            (round 4, L8). ``alpha=0`` is honoured as the invisible shade it asks for, not read as
            unset. A **globe** fills a ``contourf`` rather than a polygon, so it draws no outline:
            ``edgecolor`` (and ``linewidth``/``linestyle`` with it) is resolved — an invalid colour is
            refused on either frame — and then dropped there, where a flat map draws it.

    Returns:
        This map (chainable). The shade's ``PolyCollection`` — on a globe, the filled ``ContourSet`` it
        is drawn as there — is reached through :meth:`~digitalearth.static.core.scene.Scene.artist`, by this
        layer's id (round-1 L6). A globe whose visible side holds no night draws nothing and registers
        no layer, which is what the ``None`` this used to answer with said.

    Raises:
        ValueError: when ``refraction`` is outside ``(-90, 0]``, when ``n`` is not a whole number of at
            least 4 — the fewest that describe a ring — or when ``when`` is text that is not ISO 8601.
            The layer is not described. Both the ``refraction`` and the ``n`` refusal are made here, in
            the builder, so they answer the same way on a flat map and on a globe: cleopatra's own live
            in ``add_nightshade`` and the terminator sampler, which only the flat path calls, and a
            globe used to take either value silently (round 3, L7 for ``n``; round 4, M2 for
            ``refraction``).
        TypeError: when ``when`` is neither a ``datetime`` nor text.

    Examples:
        - At the March equinox at noon UTC the antimeridian is at midnight and Greenwich at noon:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from datetime import datetime, timezone
            >>> from digitalearth import Map
            >>> m = Map(crs=4326)
            >>> night = m.nightshade(
            ...     datetime(2026, 3, 20, 12, tzinfo=timezone.utc), name="night"
            ... ).artist("night")
            >>> [any(p.contains_point(xy) for p in night.get_paths()) for xy in ((170, 0), (0, 0))]
            [True, False]
            >>> m.figure_spec.layers.get("night").kind
            'nightshade'
            >>> m.close()

            ```
        - The twilight lines are the same call with another refraction; the figure records it:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map
            >>> m = Map(crs=3857)
            >>> _ = m.nightshade("2026-06-21T12:00:00", refraction=-6.0, alpha=0.2)
            >>> props = m.figure_spec.layers.get(m.layer_ids[-1]).symbology.props
            >>> props["when"], props["refraction"]
            ('2026-06-21T12:00:00+00:00', -6.0)
            >>> m.close()

            ```
        - ``color=None`` is the "not given" matplotlib reads it as, so the default black is drawn
          rather than the first cycle colour; ``alpha=0`` is the invisible shade it asks for:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map
            >>> with Map(crs=4326) as m:
            ...     shade = m.nightshade(
            ...         "2026-12-21T12:00:00+00:00", color=None, name="black"
            ...     ).artist("black")
            ...     [tuple(round(float(c), 2) for c in face) for face in shade.get_facecolor()]
            ...     faint = m.nightshade(
            ...         "2026-12-21T12:00:00+00:00", alpha=0, name="clear"
            ...     ).artist("clear")
            ...     [tuple(round(float(c), 2) for c in face) for face in faint.get_facecolor()]
            [(0.0, 0.0, 0.0, 0.35)]
            [(0.0, 0.0, 0.0, 0.0)]

            ```
        - A refraction above the horizon is refused by name on a globe as on a flat map, so one
          keyword answers one way whatever frame it is drawn on:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map
            >>> for globe in (False, True):
            ...     with Map(crs=4326, globe=globe) as m:
            ...         try:
            ...             m.nightshade("2026-12-21T12:00:00+00:00", refraction=10.0)
            ...         except ValueError as error:
            ...             print(str(error).split(" degrees")[0])
            nightshade() needs refraction= in (-90, 0]
            nightshade() needs refraction= in (-90, 0]

            ```

    See Also:
        tissot: the other overlay cleopatra's ``solar`` module draws.
    """
    samples = _whole_samples(n, "nightshade()")
    altitude = _terminator_altitude(refraction, "nightshade()")
    moment = _utc_moment(when)
    fill = {
        key: value
        for key, value in style.items()
        if value is not None or key not in _NIGHT_FILL_KEYWORDS
    }
    self._draw(
        LayerRecord(
            "nightshade",
            name=name,
            visible=visible,
            symbology=Symbology(
                props={
                    "via": "nightshade",
                    "when": moment.isoformat(),
                    "refraction": altitude,
                    "n": samples,
                }
            ),
            opts=fill,
        )
    )
    return self

tissot(lons=None, lats=None, *, radius_m=DEFAULT_TISSOT_RADIUS_M, n=DEFAULT_TISSOT_SAMPLES, name=None, visible=True, **style) #

Draw Tissot's indicatrices: circles of one ground radius, shown as the projection distorts them.

Each circle is the set of points radius_m from its centre on the sphere (cleopatra's tissot_circles), projected into the display CRS through pyramids — so a Web Mercator map shows them swelling toward the poles, and an equal-area one shows them keeping their area. A circle the projection cannot place whole, such as one on the far side of a globe, is left out. One straddling the antimeridian is not: it is reconnected across the seam — in degrees on lon/lat axes, in display coordinates once a projection is involved — so it reads as one ring running past the edge of the world. Unreconnected it spanned the whole map instead, its vertices landing at both edges at once (29 of 64 at one edge and the rest at the other, for a 500 km ring at lon 179.5 on Web Mercator). On an axes nothing has framed yet, the map is fitted to the circles; a framed view is kept.

Parameters:

Name Type Description Default
lons Sequence[float] | None

Circle-centre longitudes, in degrees. None (default, with lats also None) draws a world grid every 30 degrees of longitude and latitude, from 60 S to 60 N.

None
lats Sequence[float] | None

Circle-centre latitudes, in degrees, pairing with lons.

None
radius_m float

The ground radius of every circle, in metres (default 500 km).

DEFAULT_TISSOT_RADIUS_M
n int

Vertices per circle.

DEFAULT_TISSOT_SAMPLES
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the figure is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the axes (#327).

True
**style Any

Forwarded to the PolyCollection (edgecolor, facecolor, linewidth, …). The default is an unfilled black outline.

{}

Returns:

Type Description
Self

This map (chainable). The circles' PolyCollection is reached through

Self

meth:~digitalearth.static.core.scene.Scene.artist, by this layer's id (round-1 L6). No circle the

Self

projection could place draws nothing and registers no layer, which is what the None this

Self

used to answer with said.

Raises:

Type Description
ValueError

when only one of lons/lats is given, when either is empty, when they differ in length, or when n is not a whole number of at least 4. All four are refused here, in the builder, by name and before any ring is computed, and the layer is not described. radius_m raises the same type but not from here: cleopatra refuses a distance that is not positive and sub-antipodal from inside the drawer — radius_m must be a positive, sub-antipodal ground radius in metres (0, 20015114) — because that bound is half the mean Earth circumference, cleopatra's own constant to set, and is not restated in this tier. The layer is not described in that case either: a drawer that raises takes its own description with it.

Examples:

  • On Web Mercator a circle at 60 degrees is drawn twice as wide as one at the equator:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth import Map
    >>> m = Map(crs=3857)
    >>> rings = m.tissot(
    ...     [0.0, 0.0], [0.0, 60.0], radius_m=100_000.0, name="rings"
    ... ).artist("rings")
    >>> equator, sixty = (np.ptp(p.vertices[:, 0]) for p in rings.get_paths())
    >>> round(float(sixty / equator), 1)
    2.0
    >>> m.close()
    
  • With no centres, a world grid is drawn and described as one layer:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map
    >>> m = Map(crs=4326)
    >>> len(m.tissot(edgecolor="crimson", name="grid").artist("grid").get_paths())
    60
    >>> m.figure_spec.layers.get("grid").kind
    'tissot'
    >>> m.close()
    
  • A ring at lon 179.5 stays one 500 km circle on Web Mercator: it runs on past the world's own eastern edge (20037508 m) instead of being torn in two across it:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map
    >>> with Map(crs=3857) as m:
    ...     seam = m.tissot(
    ...         lons=[179.5], lats=[0.0], radius_m=500_000.0, name="seam"
    ...     ).artist("seam")
    ...     span = seam.get_paths()[0].vertices[:, 0]
    ...     (round(float(span.min())), round(float(span.max())))
    ...     bool(span.max() > 20037508.0)
    (19481444, 20482253)
    True
    
  • An empty centre list is refused by name, because None already means "every ring was off the map" and the two must not read alike. Either list empty answers the same way: a half-empty pair is what a caller gets when one of two filters came out empty, which is the case the refusal is for:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map
    >>> with Map(crs=4326) as m:
    ...     for pair in (([], []), ([], [0.0]), ([0.0], [])):
    ...         try:
    ...             m.tissot(lons=pair[0], lats=pair[1])
    ...         except ValueError as error:
    ...             print(error)
    tissot() was given no centres to draw; pass lons= and lats=, or neither for the world grid
    tissot() was given no centres to draw; pass lons= and lats=, or neither for the world grid
    tissot() was given no centres to draw; pass lons= and lats=, or neither for the world grid
    
  • Two centre lists of different lengths are refused by this method too, with both counts named, rather than by cleopatra from inside the drawer:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map
    >>> with Map(crs=4326) as m:
    ...     try:
    ...         m.tissot(lons=[0.0, 10.0], lats=[0.0])
    ...     except ValueError as error:
    ...         print(error)
    tissot() takes one lat per lon; got 2 in lons= and 1 in lats=
    
  • n is refused here and radius_m by cleopatra from inside the drawer, so the two messages read differently — but neither leaves a layer behind:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map
    >>> with Map(crs=4326) as m:
    ...     for kwargs in ({"n": 3}, {"radius_m": -1.0}):
    ...         try:
    ...             m.tissot(lons=[0.0], lats=[0.0], **kwargs)
    ...         except ValueError as error:
    ...             print(error)
    ...     m.layer_ids
    tissot() needs n= as a whole number >= 4, the fewest that describe a ring; got 3
    radius_m must be a positive, sub-antipodal ground radius in metres (0, 20015114); got -1.0.
    []
    
See Also

nightshade: the other overlay cleopatra's solar module draws.

Source code in src/digitalearth/static/builders/decoration.py
def tissot(
    self,
    lons: Sequence[float] | None = None,
    lats: Sequence[float] | None = None,
    *,
    radius_m: float = DEFAULT_TISSOT_RADIUS_M,
    n: int = DEFAULT_TISSOT_SAMPLES,
    name: str | None = None,
    visible: bool = True,
    **style: Any,
) -> Self:
    """Draw Tissot's indicatrices: circles of one ground radius, shown as the projection distorts them.

    Each circle is the set of points ``radius_m`` from its centre on the sphere (cleopatra's
    ``tissot_circles``), projected into the display CRS through pyramids — so a Web Mercator map shows
    them swelling toward the poles, and an equal-area one shows them keeping their area. A circle the
    projection cannot place whole, such as one on the far side of a globe, is left out. One straddling
    the antimeridian is *not*: it is reconnected across the seam — in degrees on lon/lat axes, in display
    coordinates once a projection is involved — so it reads as one ring running past the edge of the
    world. Unreconnected it spanned the whole map instead, its vertices landing at both edges at once
    (29 of 64 at one edge and the rest at the other, for a 500 km ring at lon 179.5 on Web Mercator).
    On an axes nothing has framed yet, the map is fitted to the circles; a framed view is kept.

    Args:
        lons: Circle-centre longitudes, in degrees. ``None`` (default, with ``lats`` also ``None``) draws
            a world grid every 30 degrees of longitude and latitude, from 60 S to 60 N.
        lats: Circle-centre latitudes, in degrees, pairing with ``lons``.
        radius_m: The ground radius of every circle, in metres (default 500 km).
        n: Vertices per circle.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the figure is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden, so a switcher reading the figure agrees with the axes (#327).
        **style: Forwarded to the ``PolyCollection`` (``edgecolor``, ``facecolor``, ``linewidth``, …).
            The default is an unfilled black outline.

    Returns:
        This map (chainable). The circles' ``PolyCollection`` is reached through
        :meth:`~digitalearth.static.core.scene.Scene.artist`, by this layer's id (round-1 L6). No circle the
        projection could place draws nothing and registers no layer, which is what the ``None`` this
        used to answer with said.

    Raises:
        ValueError: when only one of ``lons``/``lats`` is given, when **either** is empty, when they
            differ in length, or when ``n`` is not a whole number of at least 4. All four are refused
            here, in the builder, by name and before any ring is computed, and the layer is not
            described. `radius_m` raises the same type but not from here: cleopatra refuses a
            distance that is not positive and sub-antipodal from inside the drawer — `radius_m must be
            a positive, sub-antipodal ground radius in metres (0, 20015114)` — because that bound is
            half the mean Earth circumference, cleopatra's own constant to set, and is not restated in
            this tier. The layer is not described in that case either: a drawer that raises takes its
            own description with it.

    Examples:
        - On Web Mercator a circle at 60 degrees is drawn twice as wide as one at the equator:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth import Map
            >>> m = Map(crs=3857)
            >>> rings = m.tissot(
            ...     [0.0, 0.0], [0.0, 60.0], radius_m=100_000.0, name="rings"
            ... ).artist("rings")
            >>> equator, sixty = (np.ptp(p.vertices[:, 0]) for p in rings.get_paths())
            >>> round(float(sixty / equator), 1)
            2.0
            >>> m.close()

            ```
        - With no centres, a world grid is drawn and described as one layer:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map
            >>> m = Map(crs=4326)
            >>> len(m.tissot(edgecolor="crimson", name="grid").artist("grid").get_paths())
            60
            >>> m.figure_spec.layers.get("grid").kind
            'tissot'
            >>> m.close()

            ```
        - A ring at lon 179.5 stays one 500 km circle on Web Mercator: it runs on past the world's own
          eastern edge (``20037508`` m) instead of being torn in two across it:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map
            >>> with Map(crs=3857) as m:
            ...     seam = m.tissot(
            ...         lons=[179.5], lats=[0.0], radius_m=500_000.0, name="seam"
            ...     ).artist("seam")
            ...     span = seam.get_paths()[0].vertices[:, 0]
            ...     (round(float(span.min())), round(float(span.max())))
            ...     bool(span.max() > 20037508.0)
            (19481444, 20482253)
            True

            ```
        - An empty centre list is refused by name, because ``None`` already means "every ring was off
          the map" and the two must not read alike. **Either** list empty answers the same way: a
          half-empty pair is what a caller gets when one of two filters came out empty, which is the
          case the refusal is for:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map
            >>> with Map(crs=4326) as m:
            ...     for pair in (([], []), ([], [0.0]), ([0.0], [])):
            ...         try:
            ...             m.tissot(lons=pair[0], lats=pair[1])
            ...         except ValueError as error:
            ...             print(error)
            tissot() was given no centres to draw; pass lons= and lats=, or neither for the world grid
            tissot() was given no centres to draw; pass lons= and lats=, or neither for the world grid
            tissot() was given no centres to draw; pass lons= and lats=, or neither for the world grid

            ```
        - Two centre lists of different lengths are refused by this method too, with both counts
          named, rather than by cleopatra from inside the drawer:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map
            >>> with Map(crs=4326) as m:
            ...     try:
            ...         m.tissot(lons=[0.0, 10.0], lats=[0.0])
            ...     except ValueError as error:
            ...         print(error)
            tissot() takes one lat per lon; got 2 in lons= and 1 in lats=

            ```
        - ``n`` is refused here and ``radius_m`` by cleopatra from inside the drawer, so the two
          messages read differently — but neither leaves a layer behind:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map
            >>> with Map(crs=4326) as m:
            ...     for kwargs in ({"n": 3}, {"radius_m": -1.0}):
            ...         try:
            ...             m.tissot(lons=[0.0], lats=[0.0], **kwargs)
            ...         except ValueError as error:
            ...             print(error)
            ...     m.layer_ids
            tissot() needs n= as a whole number >= 4, the fewest that describe a ring; got 3
            radius_m must be a positive, sub-antipodal ground radius in metres (0, 20015114); got -1.0.
            []

            ```

    See Also:
        nightshade: the other overlay cleopatra's ``solar`` module draws.
    """
    samples = _whole_samples(n, "tissot()")
    if (lons is None) != (lats is None):
        raise ValueError(
            "tissot() takes lons= and lats= together, or neither for the world grid"
        )
    if lons is None or lats is None:
        grid_lon, grid_lat = np.meshgrid(_TISSOT_LONS, _TISSOT_LATS)
        lon_list = [float(v) for v in grid_lon.ravel()]
        lat_list = [float(v) for v in grid_lat.ravel()]
    else:
        lon_list = [float(v) for v in np.atleast_1d(np.asarray(lons, dtype=float))]
        lat_list = [float(v) for v in np.atleast_1d(np.asarray(lats, dtype=float))]
        if not lon_list or not lat_list:
            # `None` is this method's answer for "every ring was off-limb", so an empty centre list
            # must not share it: a caller whose list came out empty would read it as the projection's
            # doing. `facet` refuses an empty stack by name for the same reason (round 3, L5). Gated
            # on **either** list, not both: the half-empty pair is the shape a caller gets when one of
            # two filters came out empty, which is the case this refusal was added for, and it used to
            # fall through to cleopatra's shape message instead (round 4, M6).
            raise ValueError(
                "tissot() was given no centres to draw; pass lons= and lats=, or neither for the "
                "world grid"
            )
        if len(lon_list) != len(lat_list):
            # Refused here rather than left to cleopatra's `tissot_circles`, because `Raises` presents
            # it as this method's refusal — so it names this method and the two counts (round 4, M6).
            raise ValueError(
                f"tissot() takes one lat per lon; got {len(lon_list)} in lons= and "
                f"{len(lat_list)} in lats="
            )
    self._draw(
        LayerRecord(
            "tissot",
            name=name,
            visible=visible,
            symbology=Symbology(
                props={
                    "via": "tissot",
                    "lons": lon_list,
                    "lats": lat_list,
                    "radius_m": float(radius_m),
                    "n": samples,
                }
            ),
            opts=style,
        )
    )
    return self

colorbar(layer_id=None, *, label=None, visible=True, **kwargs) #

Show the continuous colour key of a layer.

The Core contract's name for a colour key (#299, #261), and the Core's shape for it — the same call keys a map on any tier. It was colorbar(layer=-1) here until order 24: keyed by position into :attr:layers, so a coastline or a text label added after a raster took the key over, and drawn when called rather than recorded, so a removed layer left its bar behind and a figure written down carried no note that a key had been asked for. The guide is now recorded on the layer's own colour encoding and the bar is drawn from that record.

Parameters:

Name Type Description Default
layer_id str | None

Which layer's key to show. None (the default) takes the topmost layer in draw order that carries a colour encoding — not simply the topmost layer: a coastline, a basemap, a graticule or a text label drawn over a raster is coloured by nothing and cannot take the key over. A layer whose data lay outside the display CRS drew nothing and publishes nothing, so it is skipped too. See :meth:_keyed_layer for why it is the topmost rather than the last added, and for the measurement that separates the two.

None
label str | None

What the bar is called. None (the default) takes the layer's own recorded units — a raster field records the units :func:~digitalearth.base.autostyle.auto_style resolved for its variable — and leaves the bar unlabelled when it has none. A caller's text always wins; pass "" for no label at all.

None
visible bool

False records the guide and draws no bar, so a caller passing a flag through does not have to branch — and takes an already-drawn bar off again. The layer is resolved and checked before the flag is read, so one spelling of a call is not valid only half the time.

True
**kwargs Any

Forwarded to cleopatra.styling.styles.colorbar_legend and on to Figure.colorbar (orientation, shrink, ticks, extend, …). Styling for this call: it is not part of the record, so a bar redrawn from the description — after a restyle, a rollback, or a figure read back — comes back with matplotlib's defaults in its place.

{}

Returns:

Type Description
Self

This scene, so figure decoration reads as one expression. The Core declares returns="self"

Self

for this name and the web and interactive tiers already answer that way; returning the

Self

Colorbar meant m.field(ds).colorbar().legend(...) chained on two tiers and raised on this

Self

one. What the bar is comes back off the layer instead, and off the description rather than

Self

off the engine: get_layer(layer_id).symbology.guide() is the recorded

Self

Guide — its title and whether it is shown — which is the reading that survives being

Self

written out and read back. The matplotlib Colorbar object itself is not on this tier's

Self

public surface.

Raises:

Type Description
KeyError

when layer_id names no layer on this figure, naming the ids that do.

ValueError

when that layer is coloured by nothing, when no layer on the figure is, or when the layer is coloured by category — a categorical fill's norm bins the class codes cleopatra assigned, so a bar over them reads 0, 1, 2 … where the labels belong, and :meth:legend is the key that fits it.

Note

This tier draws as many bars as there are guided layers. matplotlib takes any number of colorbars — which is why :meth:colorbars exists — so three keyed layers are three bars, each stealing width from the axes. The web tier shows exactly one key and a second replaces the first, so a figure ported between the two changes its count; asking for one bar here means keying one layer. Asking twice for the same layer replaces its bar rather than stacking a second.

Examples:

  • Key a field and read the recorded guide back off the layer; the bar is an axes of its own on the figure, and asking twice replaces it rather than stacking a second:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalearth import Map
    >>> depth = Dataset.from_array(
    ...     arr=np.array([[1.0, 2.0], [3.0, 4.0]]),
    ...     geo_ref=GeoReference(geo=(0.0, 1.0, 0.0, 2.0, 0.0, -1.0), epsg=4326),
    ...     no_data_value=-9999.0,
    ... )
    >>> m = Map(crs=4326)
    >>> _ = m.field(depth, name="depth").colorbar(label="m")
    >>> m.get_layer("depth").symbology.guide()
    Guide(show=True, title='m', anchor=None)
    >>> len(m.fig.axes)
    2
    >>> _ = m.colorbar(label="m")
    >>> len(m.fig.axes)
    2
    >>> m.close()
    
  • A categorical fill is refused by name, because a bar over it would read the class codes cleopatra assigned rather than the categories:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import geopandas as gpd
    >>> from shapely.geometry import Polygon
    >>> from digitalearth import Map
    >>> cells = gpd.GeoDataFrame(
    ...     {"use": ["arable", "forest", "urban"]},
    ...     geometry=[Polygon([(i, 0), (i + 1, 0), (i + 1, 1), (i, 1)]) for i in range(3)],
    ...     crs="EPSG:4326",
    ... )
    >>> m = Map(crs=4326)
    >>> _ = m.choropleth(cells, column="use", scheme="categorical", name="use")
    >>> m.colorbar("use")  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: layer 'use' is coloured by category, so a colorbar over it would read the ...
    >>> m.close()
    
Source code in src/digitalearth/static/core/scene.py
def colorbar(
    self,
    layer_id: str | None = None,
    *,
    label: str | None = None,
    visible: bool = True,
    **kwargs: Any,
) -> Self:
    """Show the continuous colour key of a layer.

    The Core contract's name for a colour key (#299, #261), and the Core's shape for it — the same call
    keys a map on any tier. It was ``colorbar(layer=-1)`` here until order 24: keyed **by position** into
    :attr:`layers`, so a coastline or a text label added after a raster took the key over, and drawn when
    called rather than recorded, so a removed layer left its bar behind and a figure written down carried
    no note that a key had been asked for. The guide is now recorded on the layer's own colour encoding
    and the bar is drawn from that record.

    Args:
        layer_id: Which layer's key to show. ``None`` (the default) takes **the topmost layer in draw
            order that carries a colour encoding** — not simply the topmost layer: a coastline, a
            basemap, a graticule or a text label drawn over a raster is coloured by nothing and cannot
            take the key over. A layer whose data lay outside the display CRS drew nothing and publishes
            nothing, so it is skipped too. See :meth:`_keyed_layer` for why it is the topmost rather
            than the last added, and for the measurement that separates the two.
        label: What the bar is called. ``None`` (the default) takes the layer's own recorded units — a
            raster field records the ``units``
            :func:`~digitalearth.base.autostyle.auto_style` resolved for its variable — and leaves the
            bar unlabelled when it has none. A caller's text always wins; pass ``""`` for no label at all.
        visible: ``False`` records the guide and draws no bar, so a caller passing a flag through does
            not have to branch — and takes an already-drawn bar off again. The layer is resolved and
            checked **before** the flag is read, so one spelling of a call is not valid only half the
            time.
        **kwargs: Forwarded to ``cleopatra.styling.styles.colorbar_legend`` and on to
            ``Figure.colorbar`` (``orientation``, ``shrink``, ``ticks``, ``extend``, …). Styling for
            *this* call: it is not part of the record, so a bar redrawn from the description — after a
            restyle, a rollback, or a figure read back — comes back with matplotlib's defaults in its
            place.

    Returns:
        This scene, so figure decoration reads as one expression. The Core declares `returns="self"`
        for this name and the web and interactive tiers already answer that way; returning the
        `Colorbar` meant `m.field(ds).colorbar().legend(...)` chained on two tiers and raised on this
        one. What the bar *is* comes back off the layer instead, and off the description rather than
        off the engine: `get_layer(layer_id).symbology.guide()` is the recorded
        `Guide` — its `title` and whether it is shown — which is the reading that survives being
        written out and read back. The matplotlib `Colorbar` object itself is not on this tier's
        public surface.

    Raises:
        KeyError: when `layer_id` names no layer on this figure, naming the ids that do.
        ValueError: when that layer is coloured by nothing, when no layer on the figure is, or when the
            layer is coloured **by category** — a categorical fill's norm bins the class codes cleopatra
            assigned, so a bar over them reads ``0, 1, 2 …`` where the labels belong, and :meth:`legend`
            is the key that fits it.

    Note:
        **This tier draws as many bars as there are guided layers.** matplotlib takes any number of
        colorbars — which is why :meth:`colorbars` exists — so three keyed layers are three bars, each
        stealing width from the axes. The web tier shows exactly one key and a second replaces the first,
        so a figure ported between the two changes its count; asking for one bar here means keying one
        layer. Asking twice for the *same* layer replaces its bar rather than stacking a second.

    Examples:
        - Key a field and read the recorded guide back off the layer; the bar is an axes of its own
          on the figure, and asking twice replaces it rather than stacking a second:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalearth import Map
            >>> depth = Dataset.from_array(
            ...     arr=np.array([[1.0, 2.0], [3.0, 4.0]]),
            ...     geo_ref=GeoReference(geo=(0.0, 1.0, 0.0, 2.0, 0.0, -1.0), epsg=4326),
            ...     no_data_value=-9999.0,
            ... )
            >>> m = Map(crs=4326)
            >>> _ = m.field(depth, name="depth").colorbar(label="m")
            >>> m.get_layer("depth").symbology.guide()
            Guide(show=True, title='m', anchor=None)
            >>> len(m.fig.axes)
            2
            >>> _ = m.colorbar(label="m")
            >>> len(m.fig.axes)
            2
            >>> m.close()

            ```
        - A categorical fill is refused by name, because a bar over it would read the class codes
          cleopatra assigned rather than the categories:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import geopandas as gpd
            >>> from shapely.geometry import Polygon
            >>> from digitalearth import Map
            >>> cells = gpd.GeoDataFrame(
            ...     {"use": ["arable", "forest", "urban"]},
            ...     geometry=[Polygon([(i, 0), (i + 1, 0), (i + 1, 1), (i, 1)]) for i in range(3)],
            ...     crs="EPSG:4326",
            ... )
            >>> m = Map(crs=4326)
            >>> _ = m.choropleth(cells, column="use", scheme="categorical", name="use")
            >>> m.colorbar("use")  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: layer 'use' is coloured by category, so a colorbar over it would read the ...
            >>> m.close()

            ```
    """
    layer = self._keyed_layer(layer_id, "colorbar")
    # Before the guide is recorded, not from inside the draw: a call this tier cannot answer must leave
    # the layer exactly as it found it, key and all.
    refusal = bar_refusal(layer)
    if refusal is not None:
        raise ValueError(refusal)
    self._record_key(
        layer,
        "colorbar",
        title=self._title_for(layer.id, label),
        visible=visible,
        labels=None,
        **kwargs,
    )
    return self

legend(layer_id=None, *, title=None, labels=None, visible=True, **kwargs) #

Show the keyed colour list of a layer, as one labelled swatch per class.

The Core contract's name for a keyed colour list, in the Core's shape. It took the content itself here until order 24 — legend(colors, labels) — so a caller had to read the drawn swatches off layer.category_legend and hand them back, and the key agreed with the picture only while they did it right. The rows are now derived from the very :class:~digitalearth.base.spec.scale.Scale the layer publishes, through :meth:~digitalearth.base.spec.legend.LegendSpec.from_scale, so a swatch equals the colour that was drawn by construction (#185).

Parameters:

Name Type Description Default
layer_id str | None

Which layer's classes to describe. None (the default) takes the topmost layer in draw order that carries a colour encoding, read exactly as :meth:colorbar reads it.

None
title str | None

The heading above the swatches. None (the default) takes the layer's recorded units, and "" draws no heading.

None
labels Sequence[str] | None

Explicit row labels, replacing the derived ones — for units, or for renaming categories. One per row. None (the default) derives them, and clears labels an earlier call recorded.

None
visible bool

False records the guide and draws nothing, and takes an already-drawn key off again. The layer and the key it would draw are resolved and checked before the flag is read, so one spelling of a call is not valid only half the time: labels that do not number the rows, and a layer publishing no scale to derive rows from, are refused either way (review M1).

True
**kwargs Any

Forwarded to cleopatra.styling.styles.disjoint_legend and on to Axes.legend (loc, ncol, fontsize, …). Styling for this call, not part of the record.

{}

Returns:

Type Description
Self

This scene (chainable) — the Core declares returns="self" for this name. What the key is

Self

called and whether it is shown read back off the layer's own description, as

Self

get_layer(layer_id).symbology.guide(); the matplotlib Legend object itself is not on

Self

this tier's public surface.

Raises:

Type Description
KeyError

when layer_id names no layer on this figure.

ValueError

when that layer is coloured by nothing, when no layer on the figure is, when the layer publishes no scale for rows to be derived from, or when labels does not number the rows — a short list leaves swatches unlabelled and a long one labels swatches nobody drew.

Note

One legend per axes. matplotlib holds a single legend on an axes, so keying a second layer this way replaces the first layer's swatches rather than adding a box beside them — unlike :meth:colorbar, where each layer gets its own strip. The displaced layer's guide is switched off with it, so the figure never describes two swatch keys of which only one can be drawn; legend() on that layer again brings its key back and takes this one off in its turn (review M4) — with a re-derived title and derived rows, because a call that passes no title and no labels derives both, so bringing a displaced key back as it was means repeating them (review L2). What the record keeps while the key is off is what the figure says it was called; it is not fed back into the next call. A categorical fill already draws its own swatch legend through cleopatra; asking here records it on the layer, which is what lets it be titled, relabelled, hidden and removed with the layer.

Examples:

  • Key a categorical fill, then key a second one: the axes holds one legend, the displaced layer's guide is switched off while keeping the title and rows it was given, and taking the key back re-derives both:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import geopandas as gpd
    >>> from shapely.geometry import Polygon
    >>> from digitalearth import Map
    >>> cells = gpd.GeoDataFrame(
    ...     {"use": ["arable", "forest", "urban"]},
    ...     geometry=[Polygon([(i, 0), (i + 1, 0), (i + 1, 1), (i, 1)]) for i in range(3)],
    ...     crs="EPSG:4326",
    ... )
    >>> m = Map(crs=4326)
    >>> for name in ("use", "soil"):
    ...     _ = m.choropleth(cells, column="use", scheme="categorical", name=name)
    >>> _ = m.legend("use", title="Land use", labels=["Arable", "Forest", "Urban"])
    >>> m.get_layer("use").symbology.guide()
    Guide(show=True, title='Land use', anchor=None)
    >>> _ = m.legend("soil", title="Soil")
    >>> m.get_layer("use").symbology.guide()
    Guide(show=False, title='Land use', anchor=None)
    >>> _ = m.legend("use")
    >>> m.get_layer("use").symbology.guide()
    Guide(show=True, title=None, anchor=None)
    >>> m.close()
    
  • Row labels that do not number the rows are refused by name, whatever visible says:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import geopandas as gpd
    >>> from shapely.geometry import Polygon
    >>> from digitalearth import Map
    >>> cells = gpd.GeoDataFrame(
    ...     {"use": ["arable", "forest", "urban"]},
    ...     geometry=[Polygon([(i, 0), (i + 1, 0), (i + 1, 1), (i, 1)]) for i in range(3)],
    ...     crs="EPSG:4326",
    ... )
    >>> m = Map(crs=4326)
    >>> _ = m.choropleth(cells, column="use", scheme="categorical", name="use")
    >>> m.legend("use", labels=["only one"])
    Traceback (most recent call last):
        ...
    ValueError: the key of layer 'use' has 3 rows, so labels= needs 3 labels; got 1
    >>> m.close()
    
Source code in src/digitalearth/static/core/scene.py
def legend(
    self,
    layer_id: str | None = None,
    *,
    title: str | None = None,
    labels: Sequence[str] | None = None,
    visible: bool = True,
    **kwargs: Any,
) -> Self:
    """Show the keyed colour list of a layer, as one labelled swatch per class.

    The Core contract's name for a keyed colour list, in the Core's shape. It took the **content**
    itself here until order 24 — ``legend(colors, labels)`` — so a caller had to read the drawn swatches
    off ``layer.category_legend`` and hand them back, and the key agreed with the picture only while they
    did it right. The rows are now derived from the very
    :class:`~digitalearth.base.spec.scale.Scale` the layer publishes, through
    :meth:`~digitalearth.base.spec.legend.LegendSpec.from_scale`, so a swatch equals the colour that was
    drawn by construction (#185).

    Args:
        layer_id: Which layer's classes to describe. ``None`` (the default) takes the topmost layer in
            draw order that carries a colour encoding, read exactly as :meth:`colorbar` reads it.
        title: The heading above the swatches. ``None`` (the default) takes the layer's recorded units,
            and ``""`` draws no heading.
        labels: Explicit row labels, replacing the derived ones — for units, or for renaming categories.
            One per row. ``None`` (the default) derives them, and clears labels an earlier call recorded.
        visible: ``False`` records the guide and draws nothing, and takes an already-drawn key off again.
            The layer **and the key it would draw** are resolved and checked before the flag is read, so
            one spelling of a call is not valid only half the time: `labels` that do not number the rows,
            and a layer publishing no scale to derive rows from, are refused either way (review M1).
        **kwargs: Forwarded to ``cleopatra.styling.styles.disjoint_legend`` and on to ``Axes.legend``
            (``loc``, ``ncol``, ``fontsize``, …). Styling for this call, not part of the record.

    Returns:
        This scene (chainable) — the Core declares `returns="self"` for this name. What the key is
        called and whether it is shown read back off the layer's own description, as
        `get_layer(layer_id).symbology.guide()`; the matplotlib `Legend` object itself is not on
        this tier's public surface.

    Raises:
        KeyError: when `layer_id` names no layer on this figure.
        ValueError: when that layer is coloured by nothing, when no layer on the figure is, when the
            layer publishes no scale for rows to be derived from, or when `labels` does not number the
            rows — a short list leaves swatches unlabelled and a long one labels swatches nobody drew.

    Note:
        **One legend per axes.** matplotlib holds a single legend on an axes, so keying a second layer
        this way replaces the first layer's swatches rather than adding a box beside them — unlike
        :meth:`colorbar`, where each layer gets its own strip. **The displaced layer's guide is switched
        off with it**, so the figure never describes two swatch keys of which only one can be drawn;
        ``legend()`` on that layer again brings its key back and takes this one off in its turn (review
        M4) — with a re-derived title and derived rows, because a call that passes no ``title`` and no
        ``labels`` derives both, so bringing a displaced key back *as it was* means repeating them
        (review L2). What the record keeps while the key is off is what the figure says it was called;
        it is not fed back into the next call. A categorical fill already draws its own
        swatch legend through cleopatra; asking here records it on the layer, which is what lets it be
        titled, relabelled, hidden and removed with the layer.

    Examples:
        - Key a categorical fill, then key a second one: the axes holds one legend, the displaced
          layer's guide is switched off while keeping the title and rows it was given, and taking
          the key back re-derives both:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import geopandas as gpd
            >>> from shapely.geometry import Polygon
            >>> from digitalearth import Map
            >>> cells = gpd.GeoDataFrame(
            ...     {"use": ["arable", "forest", "urban"]},
            ...     geometry=[Polygon([(i, 0), (i + 1, 0), (i + 1, 1), (i, 1)]) for i in range(3)],
            ...     crs="EPSG:4326",
            ... )
            >>> m = Map(crs=4326)
            >>> for name in ("use", "soil"):
            ...     _ = m.choropleth(cells, column="use", scheme="categorical", name=name)
            >>> _ = m.legend("use", title="Land use", labels=["Arable", "Forest", "Urban"])
            >>> m.get_layer("use").symbology.guide()
            Guide(show=True, title='Land use', anchor=None)
            >>> _ = m.legend("soil", title="Soil")
            >>> m.get_layer("use").symbology.guide()
            Guide(show=False, title='Land use', anchor=None)
            >>> _ = m.legend("use")
            >>> m.get_layer("use").symbology.guide()
            Guide(show=True, title=None, anchor=None)
            >>> m.close()

            ```
        - Row labels that do not number the rows are refused by name, whatever `visible` says:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import geopandas as gpd
            >>> from shapely.geometry import Polygon
            >>> from digitalearth import Map
            >>> cells = gpd.GeoDataFrame(
            ...     {"use": ["arable", "forest", "urban"]},
            ...     geometry=[Polygon([(i, 0), (i + 1, 0), (i + 1, 1), (i, 1)]) for i in range(3)],
            ...     crs="EPSG:4326",
            ... )
            >>> m = Map(crs=4326)
            >>> _ = m.choropleth(cells, column="use", scheme="categorical", name="use")
            >>> m.legend("use", labels=["only one"])
            Traceback (most recent call last):
                ...
            ValueError: the key of layer 'use' has 3 rows, so labels= needs 3 labels; got 1
            >>> m.close()

            ```
    """
    layer = self._keyed_layer(layer_id, "legend")
    self._record_key(
        layer,
        "legend",
        title=self._title_for(layer.id, title),
        visible=visible,
        labels=labels,
        **kwargs,
    )
    return self

move_layer(layer_id, index) #

Move a layer in draw order, by id.

Parameters:

Name Type Description Default
layer_id str

The layer to move.

required
index int

Its position afterwards, counted as a list index is — 0 is the bottom, -1 the top. A layer moves within its band: reordering the data layers is what a layer switcher does, and dragging the basemap over them is not.

required

Returns:

Type Description
Self

This scene (chainable).

Raises:

Type Description
KeyError

if no layer has that id.

IndexError

if the position is outside the figure, or outside the layer's band.

Note

This reaches the picture and not only the description. matplotlib paints the artists of one z-order in the order they were added, so the renderer re-arranges the layers it holds (:meth:~digitalearth.static.render.renderer.Renderer._repaint) — and because that stops at a z-order boundary, it also deals the layers' own z-orders back out along the new order (:func:~digitalearth.static.render.renderer._rank_zorders), which is what moves a point layer under a raster rather than only saying so. The layers keep the z-orders they held between them, so the move stays inside their slice of the stack and nothing outside it shifts; a zorder= a caller gave one of the moved layers is superseded, the move being the later word on where it is painted.

Examples:

  • Two labels, reordered by id:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth.static import Map
    >>> m = Map()
    >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
    >>> _ = m.text(2.35, 48.86, "Paris", name="par")
    >>> m.move_layer("par", 0).layer_ids
    ['par', 'ams']
    >>> m.close()
    
Source code in src/digitalearth/static/core/scene.py
def move_layer(self, layer_id: str, index: int) -> Self:
    """Move a layer in draw order, by id.

    Args:
        layer_id: The layer to move.
        index: Its position afterwards, counted as a list index is — ``0`` is the bottom, ``-1`` the
            top. A layer moves within its band: reordering the data layers is what a layer switcher
            does, and dragging the basemap over them is not.

    Returns:
        This scene (chainable).

    Raises:
        KeyError: if no layer has that id.
        IndexError: if the position is outside the figure, or outside the layer's band.

    Note:
        This reaches the picture and not only the description. matplotlib paints the artists of one
        z-order in the order they were added, so the renderer re-arranges the layers it holds
        (:meth:`~digitalearth.static.render.renderer.Renderer._repaint`) — and because that stops at a z-order
        boundary, it also deals the layers' own z-orders back out along the new order
        (:func:`~digitalearth.static.render.renderer._rank_zorders`), which is what moves a point layer under a
        raster rather than only saying so. The layers keep the z-orders they held between them, so the
        move stays inside their slice of the stack and nothing outside it shifts; a ``zorder=`` a caller
        gave one of the moved layers is superseded, the move being the later word on where it is painted.

    Examples:
        - Two labels, reordered by id:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth.static import Map
            >>> m = Map()
            >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
            >>> _ = m.text(2.35, 48.86, "Paris", name="par")
            >>> m.move_layer("par", 0).layer_ids
            ['par', 'ams']
            >>> m.close()

            ```
    """
    # Asked here rather than left to `LayerTree.move`, so an unknown id is refused in the same words as
    # every other layer-management call on this tier: the tree names itself, the facade names the figure.
    self._require_layer(layer_id)
    self._change(self._figure_with(self._layer_tree.move(layer_id, index)))
    return self

remove_layer(layer_id) #

Take a layer off the figure, by id.

Parameters:

Name Type Description Default
layer_id str

The layer to remove.

required

Returns:

Type Description
Self

This scene (chainable).

Raises:

Type Description
KeyError

if no layer has that id, naming the ids that do — a silent no-op here would look exactly like a layer that refused to go away.

Note

The id goes back to the pool, so a name removed and asked for again is handed back unsuffixed: an id is reserved exactly while the layer is on the figure, which is the lifetime all four tiers share (:func:~digitalearth.base.spec.layer.free_layer_id).

The in-memory data is not forgotten. A figure_spec captured before the removal still names it, and drawing that figure again needs it; :meth:close is where this scene lets its data go.

Examples:

  • A layer added and then removed leaves nothing behind:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth.static import Map
    >>> m = Map()
    >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
    >>> m.remove_layer("ams").layer_ids
    []
    >>> m.close()
    
Source code in src/digitalearth/static/core/scene.py
def remove_layer(self, layer_id: str) -> Self:
    """Take a layer off the figure, by id.

    Args:
        layer_id: The layer to remove.

    Returns:
        This scene (chainable).

    Raises:
        KeyError: if no layer has that id, naming the ids that do — a silent no-op here would look
            exactly like a layer that refused to go away.

    Note:
        The **id** goes back to the pool, so a name removed and asked for again is handed back
        unsuffixed: an id is reserved exactly while the layer is on the figure, which is the lifetime
        all four tiers share (:func:`~digitalearth.base.spec.layer.free_layer_id`).

        The in-memory **data** is not forgotten. A `figure_spec` captured before the removal still names
        it, and drawing that figure again needs it; :meth:`close` is where this scene lets its data go.

    Examples:
        - A layer added and then removed leaves nothing behind:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth.static import Map
            >>> m = Map()
            >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
            >>> m.remove_layer("ams").layer_ids
            []
            >>> m.close()

            ```
    """
    self._require_layer(layer_id)
    self._change(self._figure_with(self._layer_tree.remove(layer_id)))
    # After the change, not before: the drawer reads the key, the keywords and the caller's own artist
    # out of these, so dropping them first would leave the rollback inside `apply` unable to draw the
    # layer it has just taken off.
    self._layer_keys.pop(layer_id, None)
    self._layer_opts.pop(layer_id, None)
    self._held_objects.pop(layer_id, None)
    self._issued_ids.discard(layer_id)
    # The claim on the figure's coordinates goes with the layer that made it, so taking the one
    # index-placed layer off lets a georeferenced one take the axes (see `_require_one_placement`).
    self._layer_placements.pop(layer_id, None)
    return self

replace_layer(layer) #

Swap a layer's description for another, keeping its id and its place in draw order.

This is how a layer is restyled or re-pointed after it has been drawn: a cleopatra glyph bakes its colormap and its class breaks into the artist it built, so the renderer draws the layer again from the new description rather than setting a property on what is there.

Parameters:

Name Type Description Default
layer LayerSpec

The new description. Its id names the layer it replaces.

required

Returns:

Type Description
Self

This scene (chainable).

Raises:

Type Description
CapabilityError

if the replacement names a kind this tier does not draw, naming the kind and the backend that has no drawer for it. Raised off the declaration, before a description is built or the axes is touched. It subclasses ValueError, so a caller catching that catches this.

KeyError

if no layer has that id, naming the ids that do.

ValueError

if layer is not a LayerSpec, or if it draws from data and names no source_id: the drawers read the source out of the figure, and a missing one reaches the drawer as None and fails somewhere it cannot explain.

Examples:

  • A label re-described keeps its id and its place:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from dataclasses import replace
    >>> from digitalearth.static import Map
    >>> m = Map()
    >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
    >>> held = m.get_layer("ams")
    >>> _ = m.replace_layer(replace(held, label="Capital"))
    >>> m.get_layer("ams").label
    'Capital'
    >>> m.close()
    
Source code in src/digitalearth/static/core/scene.py
def replace_layer(self, layer: LayerSpec) -> Self:
    """Swap a layer's description for another, keeping its id and its place in draw order.

    This is how a layer is restyled or re-pointed after it has been drawn: a cleopatra glyph bakes its
    colormap and its class breaks into the artist it built, so the renderer draws the layer again from
    the new description rather than setting a property on what is there.

    Args:
        layer: The new description. Its id names the layer it replaces.

    Returns:
        This scene (chainable).

    Raises:
        CapabilityError: if the replacement names a kind this tier does not draw, naming the kind and the
            backend that has no drawer for it. Raised off the declaration, before a description is built
            or the axes is touched. It subclasses ``ValueError``, so a caller catching that catches this.
        KeyError: if no layer has that id, naming the ids that do.
        ValueError: if `layer` is not a `LayerSpec`, or if it draws from data and names no `source_id`:
            the drawers read the source out of the figure, and a missing one reaches the drawer as
            ``None`` and fails somewhere it cannot explain.

    Examples:
        - A label re-described keeps its id and its place:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from dataclasses import replace
            >>> from digitalearth.static import Map
            >>> m = Map()
            >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
            >>> held = m.get_layer("ams")
            >>> _ = m.replace_layer(replace(held, label="Capital"))
            >>> m.get_layer("ams").label
            'Capital'
            >>> m.close()

            ```
    """
    # By type before by id: `getattr(layer, "id", None)` made the id lookup fail first, so a caller who
    # passed the id where the description belongs was answered "no layer None on this figure" — an id
    # they never wrote, about an argument that was not a description at all (review L1).
    if not isinstance(layer, LayerSpec):
        raise ValueError(
            f"{type(self).__name__}.replace_layer needs a LayerSpec — the new description, not an id; "
            f"got {type(layer).__name__}"
        )
    self._require_layer(layer.id)
    # The first production caller of `Capabilities.require` (D-10). A replacement is the one
    # layer-management call that can name a **new kind**, so it is the one that can ask this tier for
    # something it does not have — and refusing here, off the declaration, refuses before a description
    # is built or the engine is touched. Without it the refusal came from the drawer table, part-way
    # through a reconcile, and said nothing about what the tier declares.
    CAPABILITIES.require(layer.kind, caller="Map.replace_layer")
    if layer.source_id is None and kind_info(layer.kind).takes != "none":
        raise ValueError(
            f"layer {layer.id!r} is a {layer.kind!r} layer, which draws from data, so its replacement "
            f"needs a source_id; got None"
        )
    self._change(self._figure_with(self._layer_tree.replace(layer)))
    return self

set_visible(layer_id, visible=True) #

Show or hide a layer, by id.

The layer stays on the figure and in its description — which is what lets it be switched back on, and what tells a saved figure that the layer is there but not drawn.

Parameters:

Name Type Description Default
layer_id str

The layer to toggle.

required
visible bool

Whether it is drawn.

True

Returns:

Type Description
Self

This scene (chainable).

Raises:

Type Description
KeyError

if no layer has that id, naming the ids that do.

Examples:

  • A hidden layer is still described, and comes back on:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth.static import Map
    >>> m = Map()
    >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
    >>> m.set_visible("ams", False).figure_spec.layers.is_visible("ams")
    False
    >>> m._renderer.is_visible("ams")
    False
    >>> m.set_visible("ams")._renderer.is_visible("ams")
    True
    >>> m.close()
    
Source code in src/digitalearth/static/core/scene.py
def set_visible(self, layer_id: str, visible: bool = True) -> Self:
    """Show or hide a layer, by id.

    The layer stays on the figure and in its description — which is what lets it be switched back on,
    and what tells a saved figure that the layer is there but not drawn.

    Args:
        layer_id: The layer to toggle.
        visible: Whether it is drawn.

    Returns:
        This scene (chainable).

    Raises:
        KeyError: if no layer has that id, naming the ids that do.

    Examples:
        - A hidden layer is still described, and comes back on:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth.static import Map
            >>> m = Map()
            >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
            >>> m.set_visible("ams", False).figure_spec.layers.is_visible("ams")
            False
            >>> m._renderer.is_visible("ams")
            False
            >>> m.set_visible("ams")._renderer.is_visible("ams")
            True
            >>> m.close()

            ```
    """
    self._require_layer(layer_id)
    self._change(
        self._figure_with(self._layer_tree.set_visible(layer_id, bool(visible)))
    )
    return self

animate(stack, *, kind='imshow', fps=DEFAULT_FPS, titles=None, ocean=False, coastlines=False, colorbar=False, cbar_label=None, update='auto', blit=False, **kwargs) #

Animate a stack of rasters over this map, returning a matplotlib :class:FuncAnimation.

Each frame reprojects stack[i] to the display CRS (pyramids), renders it with the kind method (cleopatra), optionally draws the ocean disc / coastlines, and — on a globe — applies the projection frame, so every frame gets the boundary, graticule, and limb-clipping for free. The returned animation is lazy: call anim.save("out.gif", writer=PillowWriter(fps=...)) or display it.

All frames share one colour treatment, so nothing flickers between them. A scalar field takes vmin/vmax from kwargs if given, else measured once over the stack. A composite ("rgb_composite" / "hsv_composite") instead takes one per-channel contrast stretch, frozen once over the stack — without which every frame would re-derive its own 2-98 percentile and the clip would pump. Pass your own limits=[(lo, hi), ...] to override that scan.

A stated center= belongs to that one treatment too. The diverging ramp it asks for is resolved once, over the shared scale, rather than by each frame against its own values: a stack that straddles the centre diverges for the whole clip, and one that does not keeps the sequential ramp and says so once. Deciding it per frame made the ramp flicker between the two along a clip — and made the picture depend on update=, since an artist kept across frames froze the first frame's answer while a redrawn one re-asked it.

Either scan measures frames as they will be drawn, reprojected into the display CRS, so the animation lands on the same scale as the equivalent still. On a globe that means the scale spans what the globe shows: an extreme value on the hidden hemisphere does not set the top of it.

Only what changes is redrawn (ST-9). The first frame draws the whole scene; every frame after it gives the artist that frame drew the new frame's values (AxesImage.set_data / QuadMesh.set_array) and touches nothing else, so the ocean disc, the coastlines, the projection frame, the colorbar and the view survive instead of being thrown away and rebuilt per frame. That is a strategy, not a different picture: the frames are pixel-identical to the cleared-and-redrawn ones, which tests/static/test_animate_in_place.py compares buffer by buffer. update= chooses the path, and a kind or an option that cannot be updated this way (a contour set, a composite, a per-frame scheme=) is named rather than animated wrongly. A frame the display CRS cannot show hides the artist for that frame, so an off-limb frame still draws nothing.

Parameters:

Name Type Description Default
stack Any

An ordered collection of pyramids Dataset frames (e.g. a list, or a DatasetCollection datacube) — one raster per animation frame.

required
kind str

The method used to draw each frame — a scalar field ("imshow" / "contourf" / "contour" / "pcolormesh" / "block") or a true/false-colour composite ("rgb_composite" / "hsv_composite", which take bands=(r, g, b) through **kwargs to pick their channels).

'imshow'
fps float

Frames per second (sets the inter-frame interval). Defaults to :data:DEFAULT_FPS, the one rate every animation entry point — here, :meth:rotate, and the other backends — starts from.

DEFAULT_FPS
titles Sequence[str] | None

Optional per-frame captions; must match the stack length when given. They are drawn on the axes and left out of the figure's description, so a heading :meth:~digitalearth.static.core.scene.Scene.set_title recorded survives in the record — but it is painted over on the axes by every frame, which is a disagreement between the drawn and the described title and is said once, at WARNING, when both are asked for (round 2, L11).

None
ocean bool

When True, fill the ocean disc behind each frame (globe maps only).

False
coastlines bool

When True, overlay coastlines each frame (best-effort; ignored if unreachable).

False
colorbar bool

When True, add one static colorbar (drawn once, not per frame) using the shared colour scale. Not available on a composite kind — an RGB image has no scalar mappable.

False
cbar_label str | None

Optional label for the colorbar.

None
update str

How the frames after the first are drawn — one of :attr:FrameUpdate.MODES. "auto" (default) updates the artist the first frame drew when the kind and the options allow it and clears the axes when they do not, logging which — including mid-clip, at WARNING, for a stack whose later frame is drawn on another grid. "in_place" insists, and refuses the call rather than falling back: naming :attr:FrameUpdate.blocker for what the kind and the options settle, and — read off the stack once, before the first frame — naming the frame and the two grids for a stack that would leave the fast path mid-clip, or the first frame the display CRS cannot show. "redraw" always clears, which is what every animation did before ST-9, and is refused for nothing.

'auto'
blit bool

When True, build the animation with matplotlib's blitting, which repaints only the artist each frame returns. It requires the in-place path and is refused without it, and it is refused alongside titles (see the note below). It is also refused for a stack that would leave that path mid-clip — one whose frames are not all drawn on a single grid, or whose first frame the display CRS cannot show, either of which clears the axes and rebuilds every layer from there on. That is read off the stack once, before the first frame, so the refusal reaches the caller rather than the playback. It changes playback only: saving a clip draws every frame in full whatever this says.

False
**kwargs Any

Forwarded to the kind method. A scalar field takes band, cmap, vmin, vmax and the rest of its styling — the shared colour scale is measured from that same band (1 by default); a composite takes bands, mask_nodata and limits. vmin/vmax are accepted on a composite because they reach the glyph like any other kwarg, but an RGB image has no colour scale for them to move — use limits.

{}

Returns:

Name Type Description
A FuncAnimation

class:matplotlib.animation.FuncAnimation over len(stack) frames (also kept on

FuncAnimation

self._animation so it is not garbage-collected before you save/display it).

Raises:

Type Description
ValueError

if kind is not a known renderer, update is not one of :attr:FrameUpdate.MODES, stack is empty, titles is given with a mismatched length, colorbar=True is combined with a composite kind, a composite's bands does not hold exactly three indices (measured: rgb_composite() needs exactly three bands, got 2: (1, 2)), a band that is read is not a whole number of 1 or more, or blit=True / update="in_place" is asked for where the frames cannot update one artist — including, for either of those two, a stack whose frames are not all drawn on one grid or whose first frame the display CRS cannot show.

Note

blit=True repaints only what the frame function returns, which is the data artist and nothing else. A per-frame title is therefore refused: matplotlib blits the axes bounding box and the title is drawn above it, so it would hold the first frame's text. A colorbar is fine — an animation's colorbar is static by construction, drawn once on its own axes.

Examples:

  • Animate a two-frame scalar stack; the animation is lazy, so no frame is drawn yet:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalearth.static import Map
    >>> geo = GeoReference(geo=(-180.0, 3.0, 0.0, 90.0, 0.0, -3.0), epsg=4326)
    >>> stack = [Dataset.from_array(arr=np.full((60, 120), value, "float32"), geo_ref=geo)
    ...          for value in (1.0, 2.0)]
    >>> m = Map(crs=4326)
    >>> anim = m.animate(stack, fps=2)
    >>> len(list(anim.new_frame_seq()))
    2
    >>> m.close()
    
  • A true-colour stack animates as a composite, on one stretch frozen over the whole stack:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalearth.static import Map
    >>> geo = GeoReference(geo=(-180.0, 3.0, 0.0, 90.0, 0.0, -3.0), epsg=4326)
    >>> stack = [Dataset.from_array(arr=np.stack([np.full((60, 120), value, "float32")] * 3),
    ...                             geo_ref=geo) for value in (1.0, 2.0)]
    >>> m = Map(crs=4326)
    >>> anim = m.animate(stack, kind="rgb_composite", fps=2)
    >>> len(list(anim.new_frame_seq()))
    2
    >>> m.close()
    
  • A composite has no scalar mappable, so asking for a colorbar is refused rather than answered with a meaningless bar:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalearth.static import Map
    >>> geo = GeoReference(geo=(-180.0, 3.0, 0.0, 90.0, 0.0, -3.0), epsg=4326)
    >>> stack = [Dataset.from_array(arr=np.stack([np.full((60, 120), 1.0, "float32")] * 3),
    ...                             geo_ref=geo)]
    >>> refused = Map(crs=4326)
    >>> refused.animate(stack, kind="rgb_composite", colorbar=True)  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: colorbar=True is not supported for a 'rgb_composite' animation: ...
    >>> refused.close()
    
  • A field animation can be blitted, because its frames update one image:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalearth.static import Map
    >>> geo = GeoReference(geo=(-180.0, 3.0, 0.0, 90.0, 0.0, -3.0), epsg=4326)
    >>> fields = [Dataset.from_array(arr=np.full((60, 120), v, "float32"), geo_ref=geo)
    ...           for v in (1.0, 2.0)]
    >>> scene = Map(crs=4326)
    >>> len(list(scene.animate(fields, fps=2, blit=True).new_frame_seq()))
    2
    >>> scene.close()
    
  • A contour animation cuts its lines from each frame, so blitting it is refused by name:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalearth.static import Map
    >>> geo = GeoReference(geo=(-180.0, 3.0, 0.0, 90.0, 0.0, -3.0), epsg=4326)
    >>> stack = [Dataset.from_array(arr=np.full((60, 120), v, "float32"), geo_ref=geo)
    ...          for v in (1.0, 2.0)]
    >>> refused = Map(crs=4326)
    >>> refused.animate(stack, kind="contourf", blit=True)  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: blit=True needs frames that update one artist in place, ...
    >>> refused.close()
    
See Also

rotate: Spin one field on an orthographic globe instead of stepping through a stack. save_animation: Write the returned animation to an mp4/GIF.

Source code in src/digitalearth/static/builders/animation.py
def animate(
    self,
    stack: Any,
    *,
    kind: str = "imshow",
    fps: float = DEFAULT_FPS,
    titles: Sequence[str] | None = None,
    ocean: bool = False,
    coastlines: bool = False,
    colorbar: bool = False,
    cbar_label: str | None = None,
    update: str = "auto",
    blit: bool = False,
    **kwargs: Any,
) -> FuncAnimation:
    """Animate a stack of rasters over this map, returning a matplotlib :class:`FuncAnimation`.

    Each frame reprojects ``stack[i]`` to the display CRS (pyramids), renders it with the ``kind`` method
    (cleopatra), optionally draws the ocean disc / coastlines, and — on a globe — applies the projection
    frame, so every frame gets the boundary, graticule, and limb-clipping for free. The returned
    animation is lazy: call ``anim.save("out.gif", writer=PillowWriter(fps=...))`` or display it.

    All frames share **one colour treatment**, so nothing flickers between them. A scalar field takes
    ``vmin``/``vmax`` from ``kwargs`` if given, else measured once over the stack. A composite
    (``"rgb_composite"`` / ``"hsv_composite"``) instead takes one per-channel contrast stretch, frozen
    once over the stack — without which every frame would re-derive its own 2-98 percentile and the
    clip would pump. Pass your own ``limits=[(lo, hi), ...]`` to override that scan.

    A stated ``center=`` belongs to that one treatment too. The diverging ramp it asks for is resolved
    **once, over the shared scale**, rather than by each frame against its own values: a stack that
    straddles the centre diverges for the whole clip, and one that does not keeps the sequential ramp
    and says so once. Deciding it per frame made the ramp flicker between the two along a clip — and
    made the picture depend on ``update=``, since an artist kept across frames froze the first frame's
    answer while a redrawn one re-asked it.

    Either scan measures frames **as they will be drawn**, reprojected into the display CRS, so the
    animation lands on the same scale as the equivalent still. On a globe that means the scale spans
    what the globe shows: an extreme value on the hidden hemisphere does not set the top of it.

    **Only what changes is redrawn (ST-9).** The first frame draws the whole scene; every frame after it
    gives the artist that frame drew the new frame's values (``AxesImage.set_data`` /
    ``QuadMesh.set_array``) and touches nothing else, so the ocean disc, the coastlines, the projection
    frame, the colorbar and the view survive instead of being thrown away and rebuilt per frame. That is
    a strategy, not a different picture: the frames are pixel-identical to the cleared-and-redrawn ones,
    which ``tests/static/test_animate_in_place.py`` compares buffer by buffer. ``update=`` chooses the
    path, and a ``kind`` or an option that cannot be updated this way (a contour set, a composite, a
    per-frame ``scheme=``) is named rather than animated wrongly. A frame the display CRS cannot show
    hides the artist for that frame, so an off-limb frame still draws nothing.

    Args:
        stack: An ordered collection of pyramids ``Dataset`` frames (e.g. a list, or a
            ``DatasetCollection`` datacube) — one raster per animation frame.
        kind: The method used to draw each frame — a scalar field (``"imshow"`` / ``"contourf"`` /
            ``"contour"`` / ``"pcolormesh"`` / ``"block"``) or a true/false-colour composite
            (``"rgb_composite"`` / ``"hsv_composite"``, which take ``bands=(r, g, b)`` through
            ``**kwargs`` to pick their channels).
        fps: Frames per second (sets the inter-frame interval). Defaults to :data:`DEFAULT_FPS`, the one
            rate every animation entry point — here, :meth:`rotate`, and the other backends — starts from.
        titles: Optional per-frame captions; must match the stack length when given. They are drawn
            on the axes and left out of the figure's description, so a heading
            :meth:`~digitalearth.static.core.scene.Scene.set_title` recorded survives in the record — but
            it is **painted over** on the axes by every frame, which is a disagreement between the
            drawn and the described title and is said once, at ``WARNING``, when both are asked for
            (round 2, L11).
        ocean: When True, fill the ocean disc behind each frame (globe maps only).
        coastlines: When True, overlay coastlines each frame (best-effort; ignored if unreachable).
        colorbar: When True, add one static colorbar (drawn once, not per frame) using the shared
            colour scale. Not available on a composite ``kind`` — an RGB image has no scalar mappable.
        cbar_label: Optional label for the colorbar.
        update: How the frames after the first are drawn — one of :attr:`FrameUpdate.MODES`. ``"auto"``
            (default) updates the artist the first frame drew when the ``kind`` and the options allow
            it and clears the axes when they do not, logging which — including mid-clip, at
            ``WARNING``, for a stack whose later frame is drawn on another grid. ``"in_place"``
            insists, and refuses the call rather than falling back: naming
            :attr:`FrameUpdate.blocker` for what the ``kind`` and the options settle, and — read off
            the stack once, before the first frame — naming the frame and the two grids for a stack
            that would leave the fast path mid-clip, or the first frame the display CRS cannot show.
            ``"redraw"`` always clears, which is what every animation did before ST-9, and is refused
            for nothing.
        blit: When True, build the animation with matplotlib's blitting, which repaints only the artist
            each frame returns. It requires the in-place path and is refused without it, and it is
            refused alongside ``titles`` (see the note below). It is also refused for a **stack** that
            would leave that path mid-clip — one whose frames are not all drawn on a single grid, or
            whose first frame the display CRS cannot show, either of which clears the axes and rebuilds
            every layer from there on. That is read off the stack once, before the first frame, so the
            refusal reaches the caller rather than the playback. It changes **playback only**: saving a
            clip draws every frame in full whatever this says.
        **kwargs: Forwarded to the ``kind`` method. A scalar field takes ``band``, ``cmap``, ``vmin``,
            ``vmax`` and the rest of its styling — the shared colour scale is measured from that same
            ``band`` (1 by default); a composite takes ``bands``, ``mask_nodata`` and ``limits``.
            ``vmin``/``vmax`` are accepted on a composite because they reach the glyph like any other
            kwarg, but an RGB image has no colour scale for them to move — use ``limits``.

    Returns:
        A :class:`matplotlib.animation.FuncAnimation` over ``len(stack)`` frames (also kept on
        ``self._animation`` so it is not garbage-collected before you save/display it).

    Raises:
        ValueError: if `kind` is not a known renderer, `update` is not one of
            :attr:`FrameUpdate.MODES`, `stack` is empty, `titles` is given with a mismatched length,
            `colorbar=True` is combined with a composite `kind`, a composite's `bands` does not hold
            exactly three indices (measured: `rgb_composite() needs exactly three bands, got 2:
            (1, 2)`), a band that is read is not a whole number of 1 or more, or `blit=True` /
            `update="in_place"` is asked for where the frames cannot update one artist — including,
            for **either** of those two, a stack whose frames are not all drawn on one grid or whose
            first frame the display CRS cannot show.

    Note:
        ``blit=True`` repaints only what the frame function returns, which is the data artist and
        nothing else. A per-frame **title** is therefore refused: matplotlib blits the axes bounding box
        and the title is drawn above it, so it would hold the first frame's text. A colorbar is fine —
        an animation's colorbar is static by construction, drawn once on its own axes.

    Examples:
        - Animate a two-frame scalar stack; the animation is lazy, so no frame is drawn yet:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalearth.static import Map
            >>> geo = GeoReference(geo=(-180.0, 3.0, 0.0, 90.0, 0.0, -3.0), epsg=4326)
            >>> stack = [Dataset.from_array(arr=np.full((60, 120), value, "float32"), geo_ref=geo)
            ...          for value in (1.0, 2.0)]
            >>> m = Map(crs=4326)
            >>> anim = m.animate(stack, fps=2)
            >>> len(list(anim.new_frame_seq()))
            2
            >>> m.close()

            ```
        - A true-colour stack animates as a composite, on one stretch frozen over the whole stack:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalearth.static import Map
            >>> geo = GeoReference(geo=(-180.0, 3.0, 0.0, 90.0, 0.0, -3.0), epsg=4326)
            >>> stack = [Dataset.from_array(arr=np.stack([np.full((60, 120), value, "float32")] * 3),
            ...                             geo_ref=geo) for value in (1.0, 2.0)]
            >>> m = Map(crs=4326)
            >>> anim = m.animate(stack, kind="rgb_composite", fps=2)
            >>> len(list(anim.new_frame_seq()))
            2
            >>> m.close()

            ```
        - A composite has no scalar mappable, so asking for a colorbar is refused rather than
            answered with a meaningless bar:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalearth.static import Map
            >>> geo = GeoReference(geo=(-180.0, 3.0, 0.0, 90.0, 0.0, -3.0), epsg=4326)
            >>> stack = [Dataset.from_array(arr=np.stack([np.full((60, 120), 1.0, "float32")] * 3),
            ...                             geo_ref=geo)]
            >>> refused = Map(crs=4326)
            >>> refused.animate(stack, kind="rgb_composite", colorbar=True)  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: colorbar=True is not supported for a 'rgb_composite' animation: ...
            >>> refused.close()

            ```
        - A field animation can be blitted, because its frames update one image:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalearth.static import Map
            >>> geo = GeoReference(geo=(-180.0, 3.0, 0.0, 90.0, 0.0, -3.0), epsg=4326)
            >>> fields = [Dataset.from_array(arr=np.full((60, 120), v, "float32"), geo_ref=geo)
            ...           for v in (1.0, 2.0)]
            >>> scene = Map(crs=4326)
            >>> len(list(scene.animate(fields, fps=2, blit=True).new_frame_seq()))
            2
            >>> scene.close()

            ```
        - A contour animation cuts its lines from each frame, so blitting it is refused by name:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalearth.static import Map
            >>> geo = GeoReference(geo=(-180.0, 3.0, 0.0, 90.0, 0.0, -3.0), epsg=4326)
            >>> stack = [Dataset.from_array(arr=np.full((60, 120), v, "float32"), geo_ref=geo)
            ...          for v in (1.0, 2.0)]
            >>> refused = Map(crs=4326)
            >>> refused.animate(stack, kind="contourf", blit=True)  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: blit=True needs frames that update one artist in place, ...
            >>> refused.close()

            ```

    See Also:
        rotate: Spin one field on an orthographic globe instead of stepping through a stack.
        save_animation: Write the returned animation to an mp4/GIF.
    """
    if kind not in _ANIMATION_KINDS:
        raise ValueError(
            f"unknown animation kind {kind!r}; choose one of {_ANIMATION_KINDS}"
        )
    frames = _as_frames(
        stack
    )  # a DatasetCollection iterates to arrays, not Datasets
    if not frames:
        raise ValueError("animate got an empty stack (nothing to animate)")
    if titles is not None and len(titles) != len(frames):
        raise ValueError(
            f"titles length ({len(titles)}) must match the stack length ({len(frames)})"
        )
    if titles is not None and self.title is not None:
        # Said here rather than where the caption is painted on, so one clip says it once however
        # many frames it runs for, and both `update=` paths say it alike.
        logger.warning(
            "animate: titles= captions each frame on the axes, which paints over the heading "
            "set_title() recorded (%r). The figure's description keeps that heading, so the drawn "
            "and the described title will disagree for the whole clip — drop one of the two",
            self.title,
        )
    updates = FrameUpdate(
        self, frames, kwargs, kind=kind, mode=update, titles=titles
    ).settle(blit=blit)
    self._prime_animation(
        frames, kwargs, kind=kind, colorbar=colorbar, cbar_label=cbar_label
    )

    def draw_one(i: int) -> Any:
        title = titles[i] if titles is not None else None
        return self._draw_animation_frame(
            frames[i], kind, kwargs, ocean=ocean, coastlines=coastlines, title=title
        )

    return self._animate_frames(
        draw_one, len(frames), fps, blit=blit, updates=updates
    )

save(path, **kwargs) #

Apply the projection frame (for a globe map) then save the figure.

Parameters:

Name Type Description Default
path Union[str, PathLike[str]]

Destination file path; the extension picks the format matplotlib writes.

required
**kwargs Any

Forwarded to :meth:~digitalearth.static.core.scene.Scene.save / Figure.savefig.

{}

Returns:

Type Description
Path

The path that was written, as a :class:pathlib.Path.

Source code in src/digitalearth/static/builders/projection.py
def save(self, path: Union[str, "os.PathLike[str]"], **kwargs: Any) -> Path:
    """Apply the projection frame (for a globe map) then save the figure.

    Args:
        path: Destination file path; the extension picks the format matplotlib writes.
        **kwargs: Forwarded to :meth:`~digitalearth.static.core.scene.Scene.save` / ``Figure.savefig``.

    Returns:
        The path that was written, as a :class:`pathlib.Path`.
    """
    self._apply_frame()
    return super().save(path, **kwargs)

show() #

Apply the projection frame (for a globe map) then show the figure.

Source code in src/digitalearth/static/builders/projection.py
def show(self) -> None:
    """Apply the projection frame (for a globe map) then show the figure."""
    self._apply_frame()
    super().show()

close() #

Close the figure and let go of the in-memory data this scene registered.

Two things are released, because a scene holds two kinds of memory. The figure is matplotlib's, and a long run of scenes that never closes one keeps every axes alive. The object table is this package's: it is process-global and holds strong references, so a session that builds maps keeps every dataset they drew until something says otherwise. This is the caller saying so, and it is what with calls on the way out.

Closing twice is harmless, and a scene that drew nothing has nothing to forget.

An object: source in a :attr:figure_spec captured from this scene cannot be opened afterwards — which is what "closed" means for a figure whose data lived only in this process. Save the data and reference it by path to keep such a figure readable.

The figure is closed only when this scene created it. A figure the scene made itself (a bare Map()/Scene(), and so every :meth:from_figure round trip) is closed here; a figure handed in through ax=/fig= is spared, because it belongs to whoever laid it out. This is

371, resolved: a borrowed figure is spared (R2-L12), which brings this into line with#

:meth:~digitalearth.static.globe.textured_globe.TexturedGlobe.close, always gated the same way. The object table and the pick handler are released on every close regardless — see below.

.. warning:: When the scene owns the figure, this closes the entire self.fig. The panels returned by :func:~digitalearth.static.panels.figure.grid share one figure none of them owns (each is built with ax=/fig=), so closing a single panel no longer closes its siblings — and an :meth:~digitalearth.static.builders.inset.InsetMixin.inset locator, drawn on the host's own figure, likewise spares the host when closed. Close the scene that made the figure (or call :meth:save and close it yourself) to take the whole figure down. The pick handler this scene connected comes off on close whether the figure is owned or borrowed, so a closed borrowed-axes scene stops answering clicks even though its figure lives on.

Examples:

  • A scene that drew nothing closes quietly:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth.static import Scene
    >>> Scene().close()
    
See Also

exit: calls this on the way out of a with block.

Source code in src/digitalearth/static/core/scene.py
def close(self) -> None:
    """Close the figure and let go of the in-memory data this scene registered.

    Two things are released, because a scene holds two kinds of memory. The **figure** is matplotlib's,
    and a long run of scenes that never closes one keeps every axes alive. The **object table** is this
    package's: it is process-global and holds strong references, so a session that builds maps keeps
    every dataset they drew until something says otherwise. This is the caller saying so, and it is what
    ``with`` calls on the way out.

    Closing twice is harmless, and a scene that drew nothing has nothing to forget.

    An ``object:`` source in a :attr:`figure_spec` captured from this scene cannot be opened afterwards
    — which is what "closed" means for a figure whose data lived only in this process. Save the data and
    reference it by path to keep such a figure readable.

    **The figure is closed only when this scene created it.** A figure the scene **made** itself (a
    bare ``Map()``/``Scene()``, and so every :meth:`from_figure` round trip) is closed here; a figure
    handed in through ``ax=``/``fig=`` is **spared**, because it belongs to whoever laid it out. This is
    #371, resolved: a borrowed figure is spared (R2-L12), which brings this into line with
    :meth:`~digitalearth.static.globe.textured_globe.TexturedGlobe.close`, always gated the same way. The
    object table and the pick handler are released on **every** close regardless — see below.

    .. warning::
        When the scene owns the figure, this closes the **entire** ``self.fig``. The panels returned by
        :func:`~digitalearth.static.panels.figure.grid` share **one** figure none of them owns (each is built
        with ``ax=``/``fig=``), so closing a single panel no longer closes its siblings — and an
        :meth:`~digitalearth.static.builders.inset.InsetMixin.inset` locator, drawn on the host's own
        figure, likewise spares the host when closed. Close the scene that **made** the figure (or call
        :meth:`save` and close it yourself) to take the whole figure down. The pick handler this scene
        connected comes off on close whether the figure is owned or borrowed, so a closed borrowed-axes
        scene stops answering clicks even though its figure lives on.

    Examples:
        - A scene that drew nothing closes quietly:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth.static import Scene
            >>> Scene().close()

            ```

    See Also:
        __exit__: calls this on the way out of a ``with`` block.
    """
    forget_namespace(self._objects_ns)
    self._layer_keys = {}
    self._layer_opts = {}
    self._held_objects = {}
    # A closed figure has no pointer over it, so its click handler goes with it: the canvas outlives
    # `plt.close` as a Python object, and a handler left connected would go on answering for a scene
    # whose data has just been let go (see `on_pick`). This runs on **every** close, owned or borrowed:
    # a borrowed-axes scene still connected its own handler, and that is the scene's to take back.
    self._disconnect_picks()
    self._pick_handlers = []
    # Close the figure only when this scene created it (`_owns_fig`, set in `__init__`). A figure handed
    # in through `ax=`/`fig=` — and so every `grid` panel and every `inset` locator — belongs to whoever
    # laid it out; closing it here tore down the caller's whole figure, which was the #371 footgun. This
    # matches `TexturedGlobe.close`, which has always gated on `_owns_fig`.
    if self._owns_fig:
        plt.close(self.fig)