Skip to content

3-D scenes (PyVista)#

Scene3D is the 3-D tier's host: one PyVista plotter and the layers drawn into it. It answers to the same method names as the 2-D tiers wherever it can draw the same thing, and adds what only a 3-D scene has — relief, volumes and isosurfaces, extruded polygons, a globe, and a camera that can orbit.

from digitalearth.three_d import Scene3D

with Scene3D(off_screen=True) as scene:
    scene.terrain(dem, z_exaggeration=3.0)
    scene.colorbar()
    scene.screenshot("relief.png")

The tier needs the 3d extra (pip install digitalearth[3d]). On a Linux machine with no display, see Headless 3-D rendering before the first render.

Where the methods come from#

Scene3D composes a base with one mixin per capability, mirroring how the static Map is built, and every method below is listed on Scene3D itself whichever class defines it:

Capability Methods Defined on
Relief terrain TerrainMixin
Points point_cloud PointCloudMixin
3-D fields volume, isosurface VolumeMixin
Vectors and extrusions vectors, extruded_polygons VectorMixin
Data on a sphere globe GlobeMixin
Decoration set_title, text, axes, orientation_axes DecorationMixin
Colour keys colorbar, legend GuideMixin
Camera motion orbit, record, jupyter AnimationMixin
Layers, view and output everything else Scene3DBase

The plotter is built on first use#

Creating a scene does not open a render window or import PyVista; the plotter is built the first time something is drawn or the plotter property is read. A scene can therefore be described — its layers listed, its figure_spec taken — without a renderer, and Scene3D.from_figure draws a figure described elsewhere.

digitalearth.three_d.scene3d.Scene3D #

Bases: TerrainMixin, PointCloudMixin, FlatMixin, MeshMixin, VolumeMixin, VectorMixin, GlobeMixin, DecorationMixin, GuideMixin, InteractionMixin, ServeMixin, AnimationMixin, PhotorealMixin, Scene3DBase

A single-:class:pyvista.Plotter 3-D scene with geospatial plot verbs.

Inherits the plotter/layer/render lifecycle from :class:~digitalearth.three_d.core.base.Scene3DBase and the plot methods from the capability mixins (:meth:terrain, :meth:point_cloud, :meth:volume, :meth:isosurface, :meth:vectors, :meth:extruded_polygons, :meth:globe, :meth:set_title, :meth:text, :meth:axes, :meth:orientation_axes, :meth:colorbar, :meth:legend, :meth:orbit, :meth:record). See those classes for the full surface.

Examples:

  • Create a headless scene, render a DEM as 3-D relief, screenshot it:
    >>> import numpy as np
    >>> from digitalearth.three_d import Scene3D
    >>> from digitalearth.base.sources import get_source
    >>> dem = np.add.outer(np.linspace(0, 1, 8), np.linspace(0, 1, 8))
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.terrain(get_source(dem), z_exaggeration=3.0)
    >>> img = scene.screenshot()
    >>> img.shape[-1], bool(img.any())
    (3, True)
    >>> scene.close()
    
Source code in src/digitalearth/three_d/scene3d.py
class Scene3D(
    TerrainMixin,
    PointCloudMixin,
    FlatMixin,
    MeshMixin,
    VolumeMixin,
    VectorMixin,
    GlobeMixin,
    DecorationMixin,
    GuideMixin,
    InteractionMixin,
    ServeMixin,
    AnimationMixin,
    PhotorealMixin,
    Scene3DBase,
):
    """A single-:class:`pyvista.Plotter` 3-D scene with geospatial plot verbs.

    Inherits the plotter/layer/render lifecycle from :class:`~digitalearth.three_d.core.base.Scene3DBase` and the
    plot methods from the capability mixins (:meth:`terrain`, :meth:`point_cloud`, :meth:`volume`,
    :meth:`isosurface`, :meth:`vectors`, :meth:`extruded_polygons`, :meth:`globe`, :meth:`set_title`,
    :meth:`text`, :meth:`axes`, :meth:`orientation_axes`, :meth:`colorbar`, :meth:`legend`, :meth:`orbit`,
    :meth:`record`). See those classes for the full surface.

    Examples:
        - Create a headless scene, render a DEM as 3-D relief, screenshot it:
            ```python
            >>> import numpy as np
            >>> from digitalearth.three_d import Scene3D
            >>> from digitalearth.base.sources import get_source
            >>> dem = np.add.outer(np.linspace(0, 1, 8), np.linspace(0, 1, 8))
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.terrain(get_source(dem), z_exaggeration=3.0)
            >>> img = scene.screenshot()
            >>> img.shape[-1], bool(img.any())
            (3, True)
            >>> scene.close()

            ```
    """

layer_ids property #

The ids of the scene's layers, in draw order.

Returns:

Type Description
list[str]

The ids, bottom first. A builder that was given name= used it; the others were numbered by kind.

Examples:

  • Two layers, each addressable by the name the scene gave it:
    >>> import numpy as np
    >>> from digitalearth.base.sources import get_source
    >>> from digitalearth.three_d import Scene3D
    >>> scene = Scene3D(off_screen=True)
    >>> dem = get_source(np.add.outer(np.arange(4.0), np.arange(5.0)))
    >>> _ = scene.terrain(dem)
    >>> _ = scene.point_cloud(np.array([[0.0, 0.0, 9.0]]), name="peak")
    >>> scene.layer_ids
    ['terrain-1', 'peak']
    >>> scene.close()
    

layers property #

The drawn (mesh, actor) pairs, in draw order — the view this tier has always exposed.

Returns:

Type Description
list[tuple[Any, Any]]

One pair per layer that was actually drawn, ordered as :attr:layer_ids is. A described layer that

list[tuple[Any, Any]]

was skipped (an empty raster, a missing custom object) has no pair.

Note

This is a compatibility view of what the renderer holds, not the scene's state: the scene is described by :attr:figure_spec, and layers are addressed by id through :attr:layer_ids, :meth:mesh_of, :meth:actor_of, :meth:remove_layer and :meth:set_visible. It is kept because it is what record's callback and a good deal of user code reach for.

figure_spec property #

What the scene draws, as data: its layers, their sources, and the camera it is seen from.

Returns:

Name Type Description
A FigureSpec

class:~digitalearth.base.spec.FigureSpec with one panel, "scene", whose view is the scene's

current FigureSpec

attr:camera and whose layers are the ids in draw order. Every builder writes into it, so

FigureSpec

it is the scene's description rather than a report about it: written with to_dict(), read back

FigureSpec

with from_dict() and drawn again with :meth:from_figure, it renders the same picture.

FigureSpec

A scene built from data already in memory can be handed straight to :meth:from_figure, but not

written FigureSpec

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

FigureSpec

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

Examples:

  • A built scene describes itself, and the description names what was drawn:
    >>> import numpy as np
    >>> from digitalearth.base.sources import get_source
    >>> from digitalearth.three_d import Scene3D
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.terrain(get_source(np.add.outer(np.arange(4.0), np.arange(5.0))))
    >>> layer = scene.figure_spec.layers.get("terrain-1")
    >>> layer.kind, layer.symbology.props["scalars"]
    ('terrain', 'elevation')
    >>> scene.close()
    

held_objects property #

The engine objects a caller handed to :meth:add_mesh/:meth:add_volume, keyed by layer id.

Returns:

Type Description
dict[str, Any]

The table the renderer looks a custom:pyvista layer up in. A figure describes such a layer but

dict[str, Any]

never carries the object (:mod:digitalearth.base.custom), so this is where it lives.

camera property writable #

Where the scene is looked at from, as a :class:~digitalearth.base.spec.Camera.

Reading it once the scene has rendered gives the live view — pan, zoom and orbit included — so a camera found interactively can be written down, stored with to_dict() and set again later. Before the plotter exists it is the camera that was set, or the scene's default isometric view.

Returns:

Type Description
Camera

The camera, carrying the scene's vertical exaggeration and display CRS.

Examples:

  • A camera set on a scene is the camera it reports:
    >>> from digitalearth.base.spec import Camera
    >>> from digitalearth.three_d import Scene3D
    >>> scene = Scene3D(off_screen=True)
    >>> scene.camera = Camera.look_at((0.0, 0.0, 0.0), azimuth=225.0, elevation=30.0, distance=10.0)
    >>> [round(value, 3) for value in scene.camera.position]
    [-6.124, -6.124, 5.0]
    >>> scene.close()
    

vertical_exaggeration property writable #

The vertical (z) scale the whole scene is rendered at (1.0 = true scale).

Exaggeration is a property of the view, never of the geometry. PyVista applies it as a renderer transform (:meth:pyvista.Plotter.set_scale), which scales every actor — including ones added after it is set — so one scene has exactly one exaggeration, the value can be read back, and changing it costs a camera reset rather than a mesh rebuild. :meth:digitalearth.three_d.Scene3D.terrain's z_exaggeration argument sets this.

Returns:

Name Type Description
float float

the current z scale.

Examples:

  • A fresh scene renders at true scale; the value set reads straight back:
    >>> from digitalearth.three_d.core.base import Scene3DBase
    >>> scene = Scene3DBase(off_screen=True)
    >>> scene.vertical_exaggeration
    1.0
    >>> scene.vertical_exaggeration = 4.0
    >>> scene.vertical_exaggeration
    4.0
    >>> scene.close()
    
  • It is the view that stretches, not the mesh — and a layer added afterwards is stretched too:
    >>> import pyvista as pv
    >>> from digitalearth.three_d.core.base import Scene3DBase
    >>> scene = Scene3DBase(off_screen=True)
    >>> scene.vertical_exaggeration = 4.0
    >>> sphere = pv.Sphere()
    >>> actor = scene.add_mesh(sphere)
    >>> round(sphere.bounds[5] - sphere.bounds[4], 3)
    1.0
    >>> round(actor.scale[2], 3)
    4.0
    >>> scene.close()
    

plotter property writable #

The PyVista plotter the scene draws on, built the first time it is asked for.

Building a scene opens no render window: describing layers needs none, and a scene that is only described never pays for one. The settings given to the constructor are applied when the plotter is built, with :func:house_theme when no theme was given.

Returns:

Type Description
Plotter

The scene's pyvista.Plotter.

Examples:

  • The plotter carries the size the scene was built with:
    >>> from digitalearth.three_d.core.base import Scene3DBase
    >>> scene = Scene3DBase(off_screen=True, window_size=(320, 240))
    >>> list(scene.plotter.window_size)
    [320, 240]
    >>> scene.close()
    
  • Asking twice returns the same plotter:
    >>> from digitalearth.three_d.core.base import Scene3DBase
    >>> scene = Scene3DBase(off_screen=True)
    >>> scene.plotter is scene.plotter
    True
    >>> scene.close()
    

renderer property #

The renderer that draws this scene's figure, and holds what it drew.

Returns:

Name Type Description
The Renderer3D

class:~digitalearth.three_d.render.renderer.Renderer3D. Its drawn mapping is how a layer id

Renderer3D

reaches the mesh and actor behind it.

terrain(data, *, name=None, band=DEFAULT_BAND, z_exaggeration=None, cmap=None, scalars=ELEVATION, texture=None, big_data_threshold=None, **kwargs) #

Render a raster/DEM as a 3-D relief surface and register it as a layer.

The raster is read through pyramids (via :func:~digitalearth.base.sources.get_source — numpy + coords + CRS, no xarray), turned into a StructuredGrid, and added to the plotter. Colour by elevation (default) or pass scalars=None to colour by something else / a uniform colour.

The raster is placed in the scene's display CRS: it sets that CRS when the scene has none, and is reprojected through pyramids when it is in another.

The surface spans the cell centres, not the cell edges. One height is set per node, at the middle of each cell, which is what a surface through sampled elevations means — so the mesh is half a cell narrower than the raster's own extent on each side. The 2-D tiers draw the cells themselves and cover that extent (#301); whether a draped surface should too is decided with draping (#202).

Metre elevations over a geographic scene are converted to degrees by the scene's CRS, not the raster's.

Vertical exaggeration is a property of the scene, not of this layer. z_exaggeration sets :attr:~digitalearth.three_d.core.base.Scene3DBase.vertical_exaggeration, a PyVista view scale that applies to every actor — so two terrains in one scene cannot disagree about it, the value can be read back off the scene, and changing it needs no mesh rebuild. Leaving it None keeps whatever the scene is already set to (1.0, true scale, on a fresh scene). The exaggeration property of the web tier's MapLibre terrain behaves the same way.

Parameters:

Name Type Description Default
data Any

A pyramids Dataset (or anything :func:get_source accepts), or an already-built :class:~digitalearth.base.sources.Source, holding the elevation raster.

required
band int

1-based band index to read.

DEFAULT_BAND
z_exaggeration float | None

Vertical exaggeration to render the scene at (1.0 = true scale; >1 accentuates relief). None leaves the scene's current exaggeration untouched.

None
cmap str | None

Matplotlib/colorcet colormap name for the elevation surface. None (the default) resolves it from the variable through :func:~digitalearth.base.autostyle.auto_style — the same lookup the static, interactive and web tiers use, so a DEM/field is drawn in the same colours on all four — falling back to "terrain" only when the lookup yields nothing.

None
scalars str | None

Scalar array to colour by (default the elevation); None for a flat colour. Ignored when texture is given — a draped image colours the surface instead of a scalar ramp.

ELEVATION
texture Any

Imagery to drape over the relief (#202) — a path to an image file, a numpy (H, W, 3|4) RGB(A) array, or a band-first (3|4, H, W) array as a pyramids RGB raster's values. The image is mapped orthographically from the surface's own x/y extent (planar draping); None (the default) colours by scalars as before. When given, no colour key is published, since the surface is coloured by the image rather than by a field.

None
big_data_threshold int | None

Cells above which the surface is simplified with decimate_pro before it is drawn (#207). None (the default) uses the scene's :attr:~digitalearth.three_d.core.base.Scene3DBase.big_data_threshold; a DEM at or under the budget is drawn exactly as it was built. Measured: a 708x708 DEM is drawn whole, a 709x709 one is reduced, and a 1000x1000 one goes from a 39.0 MB export_html page to a 12.3 MB one — see :mod:digitalearth.three_d.builders.bigdata for the table the budget comes from.

None
**kwargs Any

Forwarded to :meth:pyvista.Plotter.add_mesh (opacity, show_edges, pbr …).

{}

Returns:

Type Description
Any

The registered :class:pyvista.Actor for the terrain surface, or None when the raster held

Any

no elevation to build a surface from (see strict on

Any

class:~digitalearth.three_d.core.base.Scene3DBase).

Raises:

Type Description
OffLimbError

only when the scene was built with strict=True and the raster is empty or entirely nodata; by default that layer is skipped with a warning instead, so one blank tile does not cost a composed scene its other layers.

ValueError

if data is a Source in a CRS other than the scene's — extracted coordinates cannot be reprojected; or if big_data_threshold is negative or not a whole number of cells.

Examples:

  • A ramped DEM renders as a non-flat, correctly-oriented surface, and the exaggeration asked for is readable back off the scene:
    >>> import numpy as np, pyvista as pv
    >>> from digitalearth.three_d import Scene3D
    >>> from digitalearth.base.sources import get_source
    >>> dem = np.add.outer(np.linspace(0, 1, 8), np.linspace(0, 1, 8))
    >>> scene = Scene3D(off_screen=True)
    >>> actor = scene.terrain(get_source(dem), z_exaggeration=3.0)
    >>> len(scene.layers)
    1
    >>> scene.vertical_exaggeration
    3.0
    >>> scene.close()
    
  • An all-nodata tile is skipped with a warning rather than rendered as a flat blank sheet; under strict=True it raises instead:
    >>> import numpy as np
    >>> from digitalearth.three_d import Scene3D
    >>> from digitalearth.base.crs import OffLimbError
    >>> from digitalearth.base.sources import get_source
    >>> blank = get_source(np.full((4, 4), np.nan))
    >>> scene = Scene3D(off_screen=True)
    >>> scene.terrain(blank) is None, len(scene.layers)
    (True, 0)
    >>> scene.close()
    >>> strict = Scene3D(off_screen=True, strict=True)
    >>> try:
    ...     strict.terrain(blank)
    ... except OffLimbError as error:
    ...     print(error)
    ... finally:
    ...     strict.close()
    terrain: the raster holds no finite elevation
    
Source code in src/digitalearth/three_d/builders/terrain.py
def terrain(
    self,
    data: Any,
    *,
    name: Any = None,
    band: int = DEFAULT_BAND,
    z_exaggeration: float | None = None,
    cmap: str | None = None,
    scalars: str | None = ELEVATION,
    texture: Any = None,
    big_data_threshold: int | None = None,
    **kwargs: Any,
) -> Any:
    """Render a raster/DEM as a 3-D relief surface and register it as a layer.

    The raster is read through pyramids (via :func:`~digitalearth.base.sources.get_source` — numpy + coords +
    CRS, no xarray), turned into a ``StructuredGrid``, and added to the plotter. Colour by elevation
    (default) or pass ``scalars=None`` to colour by something else / a uniform colour.

    The raster is placed in the scene's display CRS: it sets that CRS when the scene has none, and is
    reprojected through pyramids when it is in another.

    **The surface spans the cell centres, not the cell edges.** One height is set per node, at the middle
    of each cell, which is what a surface through sampled elevations means — so the mesh is half a cell
    narrower than the raster's own extent on each side. The 2-D tiers draw the cells themselves and cover
    that extent (#301); whether a draped surface should too is decided with draping (#202).

    Metre elevations over a geographic scene are converted to degrees by the scene's CRS, not the
    raster's.

    **Vertical exaggeration is a property of the scene, not of this layer.** ``z_exaggeration`` sets
    :attr:`~digitalearth.three_d.core.base.Scene3DBase.vertical_exaggeration`, a PyVista view scale that applies
    to every actor — so two terrains in one scene cannot disagree about it, the value can be read back off
    the scene, and changing it needs no mesh rebuild. Leaving it ``None`` keeps whatever the scene is
    already set to (``1.0``, true scale, on a fresh scene). The ``exaggeration`` property of the web tier's
    MapLibre terrain behaves the same way.

    Args:
        data: A pyramids ``Dataset`` (or anything :func:`get_source` accepts), or an already-built
            :class:`~digitalearth.base.sources.Source`, holding the elevation raster.
        band: 1-based band index to read.
        z_exaggeration: Vertical exaggeration to render the **scene** at (``1.0`` = true scale; ``>1``
            accentuates relief). ``None`` leaves the scene's current exaggeration untouched.
        cmap: Matplotlib/colorcet colormap name for the elevation surface. ``None`` (the default) resolves
            it from the variable through :func:`~digitalearth.base.autostyle.auto_style` — the same lookup
            the static, interactive and web tiers use, so a DEM/field is drawn in the same colours on all
            four — falling back to ``"terrain"`` only when the lookup yields nothing.
        scalars: Scalar array to colour by (default the elevation); ``None`` for a flat colour. Ignored
            when ``texture`` is given — a draped image colours the surface instead of a scalar ramp.
        texture: Imagery to drape over the relief (#202) — a path to an image file, a numpy
            ``(H, W, 3|4)`` RGB(A) array, or a band-first ``(3|4, H, W)`` array as a pyramids RGB raster's
            ``values``. The image is mapped orthographically from the surface's own x/y extent (planar
            draping); ``None`` (the default) colours by ``scalars`` as before. When given, no colour key
            is published, since the surface is coloured by the image rather than by a field.
        big_data_threshold: Cells above which the surface is simplified with ``decimate_pro`` before it is
            drawn (#207). ``None`` (the default) uses the scene's
            :attr:`~digitalearth.three_d.core.base.Scene3DBase.big_data_threshold`; a DEM at or under the budget
            is drawn exactly as it was built. Measured: a 708x708 DEM is drawn whole, a 709x709 one is
            reduced, and a 1000x1000 one goes from a 39.0 MB ``export_html`` page to a 12.3 MB one — see
            :mod:`digitalearth.three_d.builders.bigdata` for the table the budget comes from.
        **kwargs: Forwarded to :meth:`pyvista.Plotter.add_mesh` (``opacity``, ``show_edges``, ``pbr`` …).

    Returns:
        The registered :class:`pyvista.Actor` for the terrain surface, or ``None`` when the raster held
        no elevation to build a surface from (see ``strict`` on
        :class:`~digitalearth.three_d.core.base.Scene3DBase`).

    Raises:
        OffLimbError: only when the scene was built with ``strict=True`` and the raster is empty or
            entirely nodata; by default that layer is skipped with a warning instead, so one blank tile
            does not cost a composed scene its other layers.
        ValueError: if `data` is a `Source` in a CRS other than the scene's — extracted coordinates cannot be
            reprojected; or if ``big_data_threshold`` is negative or not a whole number of cells.

    Examples:
        - A ramped DEM renders as a non-flat, correctly-oriented surface, and the exaggeration asked for is
          readable back off the scene:
            ```python
            >>> import numpy as np, pyvista as pv
            >>> from digitalearth.three_d import Scene3D
            >>> from digitalearth.base.sources import get_source
            >>> dem = np.add.outer(np.linspace(0, 1, 8), np.linspace(0, 1, 8))
            >>> scene = Scene3D(off_screen=True)
            >>> actor = scene.terrain(get_source(dem), z_exaggeration=3.0)
            >>> len(scene.layers)
            1
            >>> scene.vertical_exaggeration
            3.0
            >>> scene.close()

            ```
        - An all-nodata tile is skipped with a warning rather than rendered as a flat blank sheet; under
          ``strict=True`` it raises instead:
            ```python
            >>> import numpy as np
            >>> from digitalearth.three_d import Scene3D
            >>> from digitalearth.base.crs import OffLimbError
            >>> from digitalearth.base.sources import get_source
            >>> blank = get_source(np.full((4, 4), np.nan))
            >>> scene = Scene3D(off_screen=True)
            >>> scene.terrain(blank) is None, len(scene.layers)
            (True, 0)
            >>> scene.close()
            >>> strict = Scene3D(off_screen=True, strict=True)
            >>> try:
            ...     strict.terrain(blank)
            ... except OffLimbError as error:
            ...     print(error)
            ... finally:
            ...     strict.close()
            terrain: the raster holds no finite elevation

            ```
    """
    if z_exaggeration is not None:
        self.vertical_exaggeration = z_exaggeration
    return self._add_described_layer(
        kind="terrain",
        data=data,
        name=name,
        selection=Selection(band=(band,)),
        # The array the surface's colour comes from, so a key over this layer explains that array and is
        # titled after it (order 24). No scale: VTK holds the mapping from the array's own range through
        # its lookup table, which is what `scale=None` means. A draped image is not a field, so a textured
        # terrain publishes no colour encoding — a key over it would label nothing.
        encodings=None if texture is not None else _color_encoding(scalars, kwargs),
        cmap=cmap,
        scalars=scalars,
        texture=texture,
        big_data_threshold=self._resolve_big_data_threshold(
            big_data_threshold, caller="Scene3D.terrain()"
        ),
        **kwargs,
    )

point_cloud(data, *, name=None, values=None, value_column=None, size=5.0, scheme=None, k=5, render_points_as_spheres=True, eye_dome_lighting=True, cmap='viridis', big_data_threshold=None, **kwargs) #

Render a point cloud (LiDAR / observations / raster cells) and register it as a layer.

A GeoDataFrame is placed in the scene's display CRS — setting it when the scene has none, reprojected through pyramids when it is in another. A numpy point table declares no CRS and is placed as given.

Parameters:

Name Type Description Default
data Any

A numpy (N, 3)/(N, 2) point table (e.g. Dataset.to_xyz() or LiDAR xyz), a GeoDataFrame of Point geometries (e.g. Dataset.to_geodataframe(geometry="point")), or a path to a LAS/LAZ file (str/Path), read through the optional pointclouds dependency: coordinates come back scaled (its LAS scale/offset applied) and the file's CRS sets or reprojects the scene exactly as a GeoDataFrame's does.

required
values ndarray | None

Explicit per-point scalar array to colour by (overrides value_column).

None
value_column str | None

Column name to colour by when data is a GeoDataFrame; for a LAS/LAZ path, a per-point field — one of classification, intensity, return_number (or x/y/ z). None for no colour.

None
size float

Marker size in pixels (default 5.0). Named size on every tier, so one number means one visual marker size whichever backend drew it.

5.0
scheme Any | None

How the colour values are classified, when the cloud is coloured at all. None (the default) is a continuous ramp over the raw values; "categorical" gives every distinct value its own colour; any other cleopatra.styling.styles.classify scheme name ("quantiles", "equal_interval", "fisher_jenks", …) colours k graduated classes. The classes are computed exactly as the 2-D tiers compute them.

None
k int

Number of classes for a graduated scheme; ignored otherwise.

5
render_points_as_spheres bool

Draw points as shaded spheres (cleaner than flat dots).

True
eye_dome_lighting bool

Enable depth-cueing eye-dome lighting (recommended for dense clouds).

True
cmap str

Colormap used when the cloud is coloured by a scalar.

'viridis'
big_data_threshold int | None

Points above which the cloud is subsampled (an even stride over the points) before it is drawn (#207). None (the default) uses the scene's :attr:~digitalearth.three_d.core.base.Scene3DBase.big_data_threshold; a cloud at or under the budget keeps every point. The subsample is deterministic, so the render repeats, and the colour scalar is carried through.

None
**kwargs Any

Forwarded to :meth:pyvista.Plotter.add_points. A coloured cloud derives scalars, clim and n_colors, so pinning one of those beside values=/value_column= is a TypeError naming the keyword. nan_color is honoured instead of refused: the colour missing data is drawn in is a choice the colouring only fills a default for.

{}

Returns:

Type Description
Any

The registered :class:pyvista.Actor for the point cloud, or None when the cloud held no

Any

points (see strict on :class:~digitalearth.three_d.core.base.Scene3DBase).

Raises:

Type Description
ValueError

if values does not have one entry per point, if scheme cannot classify the values, or if data declares a CRS other than the scene's and cannot be reprojected (a PointArrays). Also — only when the scene was built with strict=True — :class:~digitalearth.base.crs.OffLimbError for an empty cloud, which is otherwise skipped with a warning.

Examples:

  • Render a coloured LiDAR-style xyz table:
    >>> import numpy as np
    >>> from digitalearth.three_d import Scene3D
    >>> pts = np.column_stack([np.arange(50.0), np.arange(50.0), np.linspace(0, 9, 50)])
    >>> scene = Scene3D(off_screen=True)
    >>> actor = scene.point_cloud(pts, values=pts[:, 2])
    >>> len(scene.layers)
    1
    >>> scene.close()
    
  • A 2-D table is lifted to z=0 and rendered uncoloured:
    >>> import numpy as np
    >>> from digitalearth.three_d import Scene3D
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.point_cloud(np.random.default_rng(0).random((30, 2)))
    >>> scene.layers[0][0].n_points
    30
    >>> scene.close()
    
  • Classify the colours into quantile classes instead of a continuous ramp:
    >>> import numpy as np
    >>> from digitalearth.three_d import Scene3D
    >>> pts = np.column_stack([np.arange(20.0), np.arange(20.0), np.zeros(20)])
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.point_cloud(pts, values=pts[:, 0], scheme="quantiles", k=4)
    >>> sorted(set(int(v) for v in scene.layers[0][0]["scalar"]))
    [0, 1, 2, 3]
    >>> scene.close()
    
  • Read a LAS/LAZ survey from disk and colour it by ASPRS classification (needs the 3d extra):
    >>> from digitalearth.three_d import Scene3D  # doctest: +SKIP
    >>> scene = Scene3D(off_screen=True)  # doctest: +SKIP
    >>> _ = scene.point_cloud(  # doctest: +SKIP
    ...     "survey.laz", value_column="classification", scheme="categorical"
    ... )
    >>> scene.display_crs  # adopted from the file's header  # doctest: +SKIP
    28992
    >>> scene.close()  # doctest: +SKIP
    
Source code in src/digitalearth/three_d/builders/point_cloud.py
def point_cloud(
    self,
    data: Any,
    *,
    name: Any = None,
    values: np.ndarray | None = None,
    value_column: str | None = None,
    size: float = 5.0,
    scheme: Any | None = None,
    k: int = 5,
    render_points_as_spheres: bool = True,
    eye_dome_lighting: bool = True,
    cmap: str = "viridis",
    big_data_threshold: int | None = None,
    **kwargs: Any,
) -> Any:
    """Render a point cloud (LiDAR / observations / raster cells) and register it as a layer.

    A GeoDataFrame is placed in the scene's display CRS — setting it when the scene has none, reprojected
    through pyramids when it is in another. A numpy point table declares no CRS and is placed as given.

    Args:
        data: A numpy ``(N, 3)``/``(N, 2)`` point table (e.g. ``Dataset.to_xyz()`` or LiDAR xyz), a
            GeoDataFrame of ``Point`` geometries (e.g. ``Dataset.to_geodataframe(geometry="point")``), or a
            path to a **LAS/LAZ file** (``str``/``Path``), read through the optional ``pointclouds``
            dependency: coordinates come back scaled (its LAS scale/offset applied) and the file's CRS sets
            or reprojects the scene exactly as a GeoDataFrame's does.
        values: Explicit per-point scalar array to colour by (overrides ``value_column``).
        value_column: Column name to colour by when ``data`` is a GeoDataFrame; for a LAS/LAZ path, a
            per-point field — one of ``classification``, ``intensity``, ``return_number`` (or ``x``/``y``/
            ``z``). ``None`` for no colour.
        size: Marker size in pixels (default ``5.0``). Named ``size`` on every tier, so one number means
            one visual marker size whichever backend drew it.
        scheme: How the colour values are classified, when the cloud is coloured at all. ``None`` (the
            default) is a continuous ramp over the raw values; ``"categorical"`` gives every distinct
            value its own colour; any other ``cleopatra.styling.styles.classify`` scheme name
            (``"quantiles"``, ``"equal_interval"``, ``"fisher_jenks"``, …) colours ``k`` graduated
            classes. The classes are computed exactly as the 2-D tiers compute them.
        k: Number of classes for a graduated ``scheme``; ignored otherwise.
        render_points_as_spheres: Draw points as shaded spheres (cleaner than flat dots).
        eye_dome_lighting: Enable depth-cueing eye-dome lighting (recommended for dense clouds).
        cmap: Colormap used when the cloud is coloured by a scalar.
        big_data_threshold: Points above which the cloud is subsampled (an even stride over the points)
            before it is drawn (#207). ``None`` (the default) uses the scene's
            :attr:`~digitalearth.three_d.core.base.Scene3DBase.big_data_threshold`; a cloud at or under the
            budget keeps every point. The subsample is deterministic, so the render repeats, and the
            colour scalar is carried through.
        **kwargs: Forwarded to :meth:`pyvista.Plotter.add_points`. A coloured cloud derives ``scalars``,
            ``clim`` and ``n_colors``, so pinning one of those beside ``values=``/``value_column=`` is a
            ``TypeError`` naming the keyword. ``nan_color`` is honoured instead of refused: the colour
            missing data is drawn in is a choice the colouring only fills a default for.

    Returns:
        The registered :class:`pyvista.Actor` for the point cloud, or ``None`` when the cloud held no
        points (see ``strict`` on :class:`~digitalearth.three_d.core.base.Scene3DBase`).

    Raises:
        ValueError: if ``values`` does not have one entry per point, if ``scheme`` cannot classify
            the values, or if `data` declares a CRS other than the scene's and cannot be reprojected (a
            `PointArrays`). Also — only when the scene was built with ``strict=True`` —
            :class:`~digitalearth.base.crs.OffLimbError` for an empty cloud, which is otherwise skipped
            with a warning.

    Examples:
        - Render a coloured LiDAR-style xyz table:
            ```python
            >>> import numpy as np
            >>> from digitalearth.three_d import Scene3D
            >>> pts = np.column_stack([np.arange(50.0), np.arange(50.0), np.linspace(0, 9, 50)])
            >>> scene = Scene3D(off_screen=True)
            >>> actor = scene.point_cloud(pts, values=pts[:, 2])
            >>> len(scene.layers)
            1
            >>> scene.close()

            ```
        - A 2-D table is lifted to z=0 and rendered uncoloured:
            ```python
            >>> import numpy as np
            >>> from digitalearth.three_d import Scene3D
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.point_cloud(np.random.default_rng(0).random((30, 2)))
            >>> scene.layers[0][0].n_points
            30
            >>> scene.close()

            ```
        - Classify the colours into quantile classes instead of a continuous ramp:
            ```python
            >>> import numpy as np
            >>> from digitalearth.three_d import Scene3D
            >>> pts = np.column_stack([np.arange(20.0), np.arange(20.0), np.zeros(20)])
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.point_cloud(pts, values=pts[:, 0], scheme="quantiles", k=4)
            >>> sorted(set(int(v) for v in scene.layers[0][0]["scalar"]))
            [0, 1, 2, 3]
            >>> scene.close()

            ```
        - Read a LAS/LAZ survey from disk and colour it by ASPRS classification (needs the `3d` extra):
            ```python
            >>> from digitalearth.three_d import Scene3D  # doctest: +SKIP
            >>> scene = Scene3D(off_screen=True)  # doctest: +SKIP
            >>> _ = scene.point_cloud(  # doctest: +SKIP
            ...     "survey.laz", value_column="classification", scheme="categorical"
            ... )
            >>> scene.display_crs  # adopted from the file's header  # doctest: +SKIP
            28992
            >>> scene.close()  # doctest: +SKIP

            ```
    """
    if isinstance(data, (str, Path)):
        # A LAS/LAZ path is decoded by pointclouds into CRS-carrying coordinates plus the chosen field.
        # The field becomes an explicit `values` array (so the drawer never re-reads the file), while
        # `value_column` is kept only to title the colour key after the field.
        if values is not None:
            # An explicit values= array colours the cloud and overrides any file field, so drop
            # value_column — otherwise the colour key is titled after a field that was never read (L3).
            value_column = None
        data, las_values = _read_las_path(data, value_column)
        if values is None:
            values = las_values
            # Title the key by the field's canonical lower-case name, matching the field actually read,
            # since the lookup itself is case-insensitive (N2).
            if value_column is not None:
                value_column = value_column.lower()
    return self._add_described_layer(
        kind="point_cloud",
        data=data,
        name=name,
        encodings=_color_encoding(data, values, value_column, scheme, k, cmap),
        values=values,
        value_column=value_column,
        size=size,
        scheme=scheme,
        k=k,
        render_points_as_spheres=render_points_as_spheres,
        eye_dome_lighting=eye_dome_lighting,
        cmap=cmap,
        big_data_threshold=self._resolve_big_data_threshold(
            big_data_threshold, caller="Scene3D.point_cloud()"
        ),
        **kwargs,
    )

volume(data, *, name=None, cmap='viridis', opacity='sigmoid', blending='composite', clim=None, shade=False, origin=None, spacing=None, big_data_threshold=None, **kwargs) #

Ray-cast a 3-D scalar field as a volume and register it as a layer.

Parameters:

Name Type Description Default
data Any

A 3-D numpy cube, or a pyramids DatasetCollection whose .values is a 3-D stack.

required
cmap str

Colormap for the field.

'viridis'
opacity Any

Opacity transfer function — a named ramp ("sigmoid", "linear", "geom" …), a scalar, or an array. Controls how much of the field is see-through. A ray-cast volume with the wrong ramp shows a fog bank or nothing, so this is the control that most decides whether the render reads at all.

'sigmoid'
blending str

How samples along each ray are combined — one of :data:VOLUME_BLENDING: "composite" (front-to-back alpha, the default), "maximum"/"minimum" (intensity projection), "average" or "additive".

'composite'
clim tuple[float, float] | None

Fixed (low, high) colour range for the field. None lets the lookup table span the data's own range; pinning it is what keeps the colours steady across the frames of an :meth:~digitalearth.three_d.temporal.animation.AnimationMixin.record so a time stack does not flicker.

None
shade bool

Whether the volume is lit (gradient shading). Off by default — shading a smooth field can read as noise — but on it gives solid-looking structure a surface-like relief.

False
origin tuple[float, float, float] | None

World (x, y, z) of the cube's lower-left-bottom corner (#198). None derives it from the data's pyramids geotransform when it has one, else places the cube at the world origin — so a volume given a georeferenced cube shares a scene with a terrain in the same CRS instead of sitting at (0, 0, 0).

None
spacing tuple[float, float, float] | None

World cell size (dx, dy, dz). None derives the horizontal size from the data's geotransform when it has one (the vertical stays one unit per level), else unit spacing.

None
big_data_threshold int | None

Voxels above which the cube is resampled to fewer per axis before it is ray-cast (#207). None (the default) uses the scene's :attr:~digitalearth.three_d.core.base.Scene3DBase.big_data_threshold; a cube at or under the budget is drawn at full resolution. Resampling is output-driven, so it costs the same fraction of a second whatever it is given — see :mod:digitalearth.three_d.builders.bigdata.

None
**kwargs Any

Forwarded to :meth:pyvista.Plotter.add_volume.

{}

Returns:

Type Description
Any

The registered volume actor.

Raises:

Type Description
ValueError

if blending is not one of :data:VOLUME_BLENDING, or if big_data_threshold is negative or not a whole number of cells.

Examples:

  • Volume-render a synthetic 3-D Gaussian blob:
    >>> import numpy as np
    >>> from digitalearth.three_d import Scene3D
    >>> ax = np.linspace(-2, 2, 12)
    >>> xx, yy, zz = np.meshgrid(ax, ax, ax, indexing="ij")
    >>> cube = np.exp(-(xx**2 + yy**2 + zz**2))
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.volume(cube, blending="maximum", clim=(0.0, 1.0))
    >>> len(scene.layers)
    1
    >>> scene.close()
    
Source code in src/digitalearth/three_d/builders/volume.py
def volume(
    self,
    data: Any,
    *,
    name: Any = None,
    cmap: str = "viridis",
    opacity: Any = "sigmoid",
    blending: str = "composite",
    clim: tuple[float, float] | None = None,
    shade: bool = False,
    origin: tuple[float, float, float] | None = None,
    spacing: tuple[float, float, float] | None = None,
    big_data_threshold: int | None = None,
    **kwargs: Any,
) -> Any:
    """Ray-cast a 3-D scalar field as a volume and register it as a layer.

    Args:
        data: A 3-D numpy cube, or a pyramids ``DatasetCollection`` whose ``.values`` is a 3-D stack.
        cmap: Colormap for the field.
        opacity: Opacity transfer function — a named ramp (``"sigmoid"``, ``"linear"``, ``"geom"`` …), a
            scalar, or an array. Controls how much of the field is see-through. A ray-cast volume with the
            wrong ramp shows a fog bank or nothing, so this is the control that most decides whether the
            render reads at all.
        blending: How samples along each ray are combined — one of :data:`VOLUME_BLENDING`:
            ``"composite"`` (front-to-back alpha, the default), ``"maximum"``/``"minimum"`` (intensity
            projection), ``"average"`` or ``"additive"``.
        clim: Fixed ``(low, high)`` colour range for the field. ``None`` lets the lookup table span the
            data's own range; pinning it is what keeps the colours steady across the frames of an
            :meth:`~digitalearth.three_d.temporal.animation.AnimationMixin.record` so a time stack does not flicker.
        shade: Whether the volume is lit (gradient shading). Off by default — shading a smooth field can
            read as noise — but on it gives solid-looking structure a surface-like relief.
        origin: World ``(x, y, z)`` of the cube's lower-left-bottom corner (#198). ``None`` derives it
            from the data's pyramids ``geotransform`` when it has one, else places the cube at the world
            origin — so a volume given a georeferenced cube shares a scene with a terrain in the same CRS
            instead of sitting at ``(0, 0, 0)``.
        spacing: World cell size ``(dx, dy, dz)``. ``None`` derives the horizontal size from the data's
            ``geotransform`` when it has one (the vertical stays one unit per level), else unit spacing.
        big_data_threshold: Voxels above which the cube is resampled to fewer per axis before it is
            ray-cast (#207). ``None`` (the default) uses the scene's
            :attr:`~digitalearth.three_d.core.base.Scene3DBase.big_data_threshold`; a cube at or under the budget
            is drawn at full resolution. Resampling is output-driven, so it costs the same fraction of a
            second whatever it is given — see :mod:`digitalearth.three_d.builders.bigdata`.
        **kwargs: Forwarded to :meth:`pyvista.Plotter.add_volume`.

    Returns:
        The registered volume actor.

    Raises:
        ValueError: if ``blending`` is not one of :data:`VOLUME_BLENDING`, or if ``big_data_threshold``
            is negative or not a whole number of cells.

    Examples:
        - Volume-render a synthetic 3-D Gaussian blob:
            ```python
            >>> import numpy as np
            >>> from digitalearth.three_d import Scene3D
            >>> ax = np.linspace(-2, 2, 12)
            >>> xx, yy, zz = np.meshgrid(ax, ax, ax, indexing="ij")
            >>> cube = np.exp(-(xx**2 + yy**2 + zz**2))
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.volume(cube, blending="maximum", clim=(0.0, 1.0))
            >>> len(scene.layers)
            1
            >>> scene.close()

            ```
    """
    if blending not in VOLUME_BLENDING:
        raise ValueError(
            f"volume() got blending={blending!r}; choose one of {sorted(VOLUME_BLENDING)}"
        )
    return self._add_described_layer(
        kind="volume",
        data=data,
        name=name,
        # The cube's colour is driven by the array :data:`FIELD` the grid carries it under, so a key
        # over this layer explains that field and is titled after it (order 24). No scale: VTK maps
        # the array's own range through its lookup table, which is what `scale=None` means.
        encodings={"color": Encoding.by_field("color", FIELD)},
        cmap=cmap,
        opacity=opacity,
        blending=blending,
        clim=clim,
        shade=shade,
        origin=origin,
        spacing=spacing,
        big_data_threshold=self._resolve_big_data_threshold(
            big_data_threshold, caller="Scene3D.volume()"
        ),
        **kwargs,
    )

isosurface(data, *, name=None, isosurfaces=None, cmap='viridis', origin=None, spacing=None, big_data_threshold=None, **kwargs) #

Extract and render isosurfaces (shells of constant value) from a 3-D field as a layer.

Parameters:

Name Type Description Default
data Any

A 3-D numpy cube, or a pyramids DatasetCollection whose .values is a 3-D stack.

required
isosurfaces Sequence[float] | None

Iso-values to extract; None lets PyVista pick 10 levels across the data range.

None
cmap str

Colormap for the extracted surfaces.

'viridis'
origin tuple[float, float, float] | None

World (x, y, z) of the cube's lower-left-bottom corner (#198); None derives it from the data's pyramids geotransform when it has one, else the world origin.

None
spacing tuple[float, float, float] | None

World cell size (dx, dy, dz); None derives the horizontal size from the data's geotransform when it has one, else unit spacing.

None
big_data_threshold int | None

Cells above which the extracted shells are simplified with decimate_pro before they are drawn (#207). None (the default) uses the scene's :attr:~digitalearth.three_d.core.base.Scene3DBase.big_data_threshold. The budget applies to the shells, which is what reaches the plotter; the contour is still extracted from the full cube, so this bounds what is carried rather than what the extraction costs.

None
**kwargs Any

Forwarded to :meth:pyvista.Plotter.add_mesh.

{}

Returns:

Type Description
Any

The registered :class:pyvista.Actor for the isosurface mesh.

Raises:

Type Description
ValueError

if big_data_threshold is negative or not a whole number of cells.

Examples:

  • Two iso-shells of a Gaussian blob:
    >>> import numpy as np
    >>> from digitalearth.three_d import Scene3D
    >>> ax = np.linspace(-2, 2, 16)
    >>> xx, yy, zz = np.meshgrid(ax, ax, ax, indexing="ij")
    >>> cube = np.exp(-(xx**2 + yy**2 + zz**2))
    >>> scene = Scene3D(off_screen=True)
    >>> actor = scene.isosurface(cube, isosurfaces=[0.3, 0.6])
    >>> scene.layers[0][0].n_points > 0
    True
    >>> scene.close()
    
Source code in src/digitalearth/three_d/builders/volume.py
def isosurface(
    self,
    data: Any,
    *,
    name: Any = None,
    isosurfaces: Sequence[float] | None = None,
    cmap: str = "viridis",
    origin: tuple[float, float, float] | None = None,
    spacing: tuple[float, float, float] | None = None,
    big_data_threshold: int | None = None,
    **kwargs: Any,
) -> Any:
    """Extract and render isosurfaces (shells of constant value) from a 3-D field as a layer.

    Args:
        data: A 3-D numpy cube, or a pyramids ``DatasetCollection`` whose ``.values`` is a 3-D stack.
        isosurfaces: Iso-values to extract; ``None`` lets PyVista pick 10 levels across the data range.
        cmap: Colormap for the extracted surfaces.
        origin: World ``(x, y, z)`` of the cube's lower-left-bottom corner (#198); ``None`` derives it
            from the data's pyramids ``geotransform`` when it has one, else the world origin.
        spacing: World cell size ``(dx, dy, dz)``; ``None`` derives the horizontal size from the data's
            ``geotransform`` when it has one, else unit spacing.
        big_data_threshold: Cells above which the extracted shells are simplified with ``decimate_pro``
            before they are drawn (#207). ``None`` (the default) uses the scene's
            :attr:`~digitalearth.three_d.core.base.Scene3DBase.big_data_threshold`. The budget applies to the
            **shells**, which is what reaches the plotter; the contour is still extracted from the full
            cube, so this bounds what is carried rather than what the extraction costs.
        **kwargs: Forwarded to :meth:`pyvista.Plotter.add_mesh`.

    Returns:
        The registered :class:`pyvista.Actor` for the isosurface mesh.

    Raises:
        ValueError: if ``big_data_threshold`` is negative or not a whole number of cells.

    Examples:
        - Two iso-shells of a Gaussian blob:
            ```python
            >>> import numpy as np
            >>> from digitalearth.three_d import Scene3D
            >>> ax = np.linspace(-2, 2, 16)
            >>> xx, yy, zz = np.meshgrid(ax, ax, ax, indexing="ij")
            >>> cube = np.exp(-(xx**2 + yy**2 + zz**2))
            >>> scene = Scene3D(off_screen=True)
            >>> actor = scene.isosurface(cube, isosurfaces=[0.3, 0.6])
            >>> scene.layers[0][0].n_points > 0
            True
            >>> scene.close()

            ```
    """
    return self._add_described_layer(
        kind="isosurface",
        data=data,
        name=name,
        # The cube's colour is driven by the array :data:`FIELD` the grid carries it under, so a key
        # over this layer explains that field and is titled after it (order 24). No scale: VTK maps
        # the array's own range through its lookup table, which is what `scale=None` means.
        encodings={"color": Encoding.by_field("color", FIELD)},
        isosurfaces=isosurfaces,
        cmap=cmap,
        origin=origin,
        spacing=spacing,
        big_data_threshold=self._resolve_big_data_threshold(
            big_data_threshold, caller="Scene3D.isosurface()"
        ),
        **kwargs,
    )

vectors(points, vectors, *, name=None, factor=1.0, cmap='viridis', **kwargs) #

Render a 3-D vector field as arrow glyphs (oriented + scaled by magnitude) and register it.

Parameters:

Name Type Description Default
points ndarray

(N, 3) glyph anchor positions.

required
vectors ndarray

(N, 3) (u, v, w) vectors at each point.

required
factor float

Overall arrow length scale.

1.0
cmap str

Colormap applied to the arrow magnitudes.

'viridis'
**kwargs Any

Forwarded to :meth:pyvista.Plotter.add_mesh.

{}

Returns:

Type Description
Any

The registered :class:pyvista.Actor for the glyph mesh, or None when there were no points

Any

to place a glyph at (see strict on :class:~digitalearth.three_d.core.base.Scene3DBase).

Raises:

Type Description
ValueError

if points and vectors do not have the same shape. Also — only when the scene was built with strict=True — :class:~digitalearth.base.crs.OffLimbError for an empty field, which is otherwise skipped with a warning.

Examples:

  • A uniform eastward field renders as same-length arrows coloured by magnitude:
    >>> import numpy as np
    >>> from digitalearth.three_d import Scene3D
    >>> ax = np.linspace(0, 1, 6)
    >>> xx, yy = np.meshgrid(ax, ax)
    >>> pts = np.column_stack([xx.ravel(), yy.ravel(), np.zeros(xx.size)])
    >>> vec = np.column_stack([np.ones(pts.shape[0]), np.zeros(pts.shape[0]), np.zeros(pts.shape[0])])
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.vectors(pts, vec, factor=0.1)
    >>> len(scene.layers)
    1
    >>> scene.close()
    
Source code in src/digitalearth/three_d/builders/vector.py
def vectors(
    self,
    points: np.ndarray,
    vectors: np.ndarray,
    *,
    name: Any = None,
    factor: float = 1.0,
    cmap: str = "viridis",
    **kwargs: Any,
) -> Any:
    """Render a 3-D vector field as arrow glyphs (oriented + scaled by magnitude) and register it.

    Args:
        points: ``(N, 3)`` glyph anchor positions.
        vectors: ``(N, 3)`` ``(u, v, w)`` vectors at each point.
        factor: Overall arrow length scale.
        cmap: Colormap applied to the arrow magnitudes.
        **kwargs: Forwarded to :meth:`pyvista.Plotter.add_mesh`.

    Returns:
        The registered :class:`pyvista.Actor` for the glyph mesh, or ``None`` when there were no points
        to place a glyph at (see ``strict`` on :class:`~digitalearth.three_d.core.base.Scene3DBase`).

    Raises:
        ValueError: if ``points`` and ``vectors`` do not have the same shape. Also — only when the scene
            was built with ``strict=True`` — :class:`~digitalearth.base.crs.OffLimbError` for an empty
            field, which is otherwise skipped with a warning.

    Examples:
        - A uniform eastward field renders as same-length arrows coloured by magnitude:
            ```python
            >>> import numpy as np
            >>> from digitalearth.three_d import Scene3D
            >>> ax = np.linspace(0, 1, 6)
            >>> xx, yy = np.meshgrid(ax, ax)
            >>> pts = np.column_stack([xx.ravel(), yy.ravel(), np.zeros(xx.size)])
            >>> vec = np.column_stack([np.ones(pts.shape[0]), np.zeros(pts.shape[0]), np.zeros(pts.shape[0])])
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.vectors(pts, vec, factor=0.1)
            >>> len(scene.layers)
            1
            >>> scene.close()

            ```
    """
    return self._add_described_layer(
        kind="vectors",
        data=points,
        name=name,
        vectors=vectors,
        factor=factor,
        cmap=cmap,
        **kwargs,
    )

extruded_polygons(gdf, *, name=None, height=1.0, column=None, scheme=None, k=5, cmap='viridis', **kwargs) #

Extrude polygon footprints into 3-D prisms and register them as a single layer.

The footprints are placed in the scene's display CRS — setting it when the scene has none, reprojected through pyramids when they are in another.

Parameters:

Name Type Description Default
gdf Any

A GeoDataFrame of Polygon/MultiPolygon geometries (e.g. a pyramids FeatureCollection / to_geodataframe(geometry="polygon")); coordinates are read by duck-typing (no geopandas/shapely import).

required
height float | str

Uniform extrusion height (float), or the name of a column (str) to read a per-feature height from. Every height must be finite: a NaN one builds a prism whose coordinates are all NaN, which draws nothing while still counting as cells on the actor, so it is refused by row rather than rendered as an invisible building.

1.0
column str | None

Optional attribute column to colour the prisms by; None for a flat colour.

None
scheme Any | None

How column is classified. None (the default) is a continuous ramp over the raw values; "categorical" gives every distinct value its own colour; any other cleopatra.styling.styles.classify scheme name ("quantiles", "equal_interval", "fisher_jenks", …) colours k graduated classes — computed exactly as the 2-D tiers compute them, so one scheme/k pair means one set of classes on every tier.

None
k int

Number of classes for a graduated scheme; ignored otherwise.

5
cmap str

Colormap used when colouring by column.

'viridis'
**kwargs Any

Forwarded to :meth:pyvista.Plotter.add_mesh. A classified layer derives clim and n_colors from the classes it cut, so passing one of those and a scheme is a TypeError naming the keyword rather than a "multiple values" error out of Python's call machinery. nan_color is the exception and is honoured: the colour missing data is drawn in is a choice the classifier only fills a default for, so a caller's own wins, as cmap does.

{}

Returns:

Type Description
Any

The registered :class:pyvista.Actor for the merged prism mesh, or None when there was

Any

nothing to extrude (see strict on :class:~digitalearth.three_d.core.base.Scene3DBase).

Raises:

Type Description
ValueError

if scheme cannot classify column, or if an extrusion height is not finite. Also — only when the scene was built with strict=True — :class:~digitalearth.base.crs.OffLimbError when no polygon rings were found, which is otherwise skipped with a warning.

TypeError

if scheme is combined with a colour keyword the scheme itself sets (clim / n_colors / nan_color).

Examples:

  • Extrude two squares to different heights and colour by an attribute (needs geopandas at the call site — only ever as the type pyramids hands back):
    >>> import geopandas as gpd
    >>> from shapely.geometry import Polygon
    >>> from digitalearth.three_d import Scene3D
    >>> gdf = gpd.GeoDataFrame(
    ...     {"pop": [10.0, 20.0]},
    ...     geometry=[Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]),
    ...               Polygon([(2, 0), (3, 0), (3, 1), (2, 1)])],
    ... )
    >>> scene = Scene3D(off_screen=True)
    >>> actor = scene.extruded_polygons(gdf, height="pop", column="pop")
    >>> scene.layers[0][0].n_cells > 0
    True
    >>> scene.close()
    
  • Nothing to extrude is a skipped layer with a warning, not a dead scene — unless the scene was built strict=True:
    >>> import geopandas as gpd
    >>> from digitalearth.three_d import Scene3D
    >>> from digitalearth.base.crs import OffLimbError
    >>> empty = gpd.GeoDataFrame({"pop": []}, geometry=[])
    >>> scene = Scene3D(off_screen=True)
    >>> scene.extruded_polygons(empty) is None, len(scene.layers)
    (True, 0)
    >>> scene.close()
    >>> strict = Scene3D(off_screen=True, strict=True)
    >>> try:
    ...     strict.extruded_polygons(empty)
    ... except OffLimbError as error:
    ...     print(error)
    ... finally:
    ...     strict.close()
    extruded_polygons: no polygon geometries to extrude
    
Source code in src/digitalearth/three_d/builders/vector.py
def extruded_polygons(
    self,
    gdf: Any,
    *,
    name: Any = None,
    height: float | str = 1.0,
    column: str | None = None,
    scheme: Any | None = None,
    k: int = 5,
    cmap: str = "viridis",
    **kwargs: Any,
) -> Any:
    """Extrude polygon footprints into 3-D prisms and register them as a single layer.

    The footprints are placed in the scene's display CRS — setting it when the scene has none, reprojected
    through pyramids when they are in another.

    Args:
        gdf: A GeoDataFrame of ``Polygon``/``MultiPolygon`` geometries (e.g. a pyramids
            ``FeatureCollection`` / ``to_geodataframe(geometry="polygon")``); coordinates are read by
            duck-typing (no geopandas/shapely import).
        height: Uniform extrusion height (``float``), or the name of a column (``str``) to read a
            per-feature height from. Every height must be finite: a ``NaN`` one builds a prism whose
            coordinates are all ``NaN``, which draws nothing while still counting as cells on the
            actor, so it is refused by row rather than rendered as an invisible building.
        column: Optional attribute column to colour the prisms by; ``None`` for a flat colour.
        scheme: How ``column`` is classified. ``None`` (the default) is a continuous ramp over the raw
            values; ``"categorical"`` gives every distinct value its own colour; any other
            ``cleopatra.styling.styles.classify`` scheme name (``"quantiles"``, ``"equal_interval"``,
            ``"fisher_jenks"``, …) colours ``k`` graduated classes — computed exactly as the 2-D tiers
            compute them, so one ``scheme``/``k`` pair means one set of classes on every tier.
        k: Number of classes for a graduated ``scheme``; ignored otherwise.
        cmap: Colormap used when colouring by ``column``.
        **kwargs: Forwarded to :meth:`pyvista.Plotter.add_mesh`. A classified layer derives ``clim`` and
            ``n_colors`` from the classes it cut, so passing one of those *and* a ``scheme`` is a
            ``TypeError`` naming the keyword rather than a "multiple values" error out of Python's call
            machinery. ``nan_color`` is the exception and is honoured: the colour missing data is drawn in
            is a choice the classifier only fills a default for, so a caller's own wins, as ``cmap`` does.

    Returns:
        The registered :class:`pyvista.Actor` for the merged prism mesh, or ``None`` when there was
        nothing to extrude (see ``strict`` on :class:`~digitalearth.three_d.core.base.Scene3DBase`).

    Raises:
        ValueError: if ``scheme`` cannot classify ``column``, or if an extrusion height is not finite.
            Also — only when the scene was built with ``strict=True`` —
            :class:`~digitalearth.base.crs.OffLimbError` when no polygon rings were found, which is
            otherwise skipped with a warning.
        TypeError: if ``scheme`` is combined with a colour keyword the scheme itself sets
            (``clim`` / ``n_colors`` / ``nan_color``).

    Examples:
        - Extrude two squares to different heights and colour by an attribute (needs geopandas at the
          call site — only ever as the type pyramids hands back):
            ```python
            >>> import geopandas as gpd
            >>> from shapely.geometry import Polygon
            >>> from digitalearth.three_d import Scene3D
            >>> gdf = gpd.GeoDataFrame(
            ...     {"pop": [10.0, 20.0]},
            ...     geometry=[Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]),
            ...               Polygon([(2, 0), (3, 0), (3, 1), (2, 1)])],
            ... )
            >>> scene = Scene3D(off_screen=True)
            >>> actor = scene.extruded_polygons(gdf, height="pop", column="pop")
            >>> scene.layers[0][0].n_cells > 0
            True
            >>> scene.close()

            ```
        - Nothing to extrude is a skipped layer with a warning, not a dead scene — unless the scene was
          built ``strict=True``:
            ```python
            >>> import geopandas as gpd
            >>> from digitalearth.three_d import Scene3D
            >>> from digitalearth.base.crs import OffLimbError
            >>> empty = gpd.GeoDataFrame({"pop": []}, geometry=[])
            >>> scene = Scene3D(off_screen=True)
            >>> scene.extruded_polygons(empty) is None, len(scene.layers)
            (True, 0)
            >>> scene.close()
            >>> strict = Scene3D(off_screen=True, strict=True)
            >>> try:
            ...     strict.extruded_polygons(empty)
            ... except OffLimbError as error:
            ...     print(error)
            ... finally:
            ...     strict.close()
            extruded_polygons: no polygon geometries to extrude

            ```
    """
    return self._add_described_layer(
        kind="extrusion",
        data=gdf,
        name=name,
        # The prisms' colour comes from `column`, so a key over this layer explains that column and is
        # titled after it (order 24). No column is a flat fill, which publishes nothing: there is nothing
        # for a key to label. The scale carries the classes the drawer cuts, from the same classifier, so
        # a legend derived from it cannot disagree with the fill.
        encodings=_color_encoding(gdf, column, scheme, k, cmap),
        height=height,
        column=column,
        scheme=scheme,
        k=k,
        cmap=cmap,
        **kwargs,
    )

globe(data, *, name=None, band=DEFAULT_BAND, cmap=None, coastlines=True, coastline_resolution='110m', coastline_color='black', **kwargs) #

Drape a global field onto a 3-D sphere and register it as a layer.

Projected input is reprojected, not refused: a pyramids Dataset in any CRS is warped to EPSG:4326 through pyramids (Dataset.to_crs) on the way in, exactly as the static, interactive and web tiers do. Only input that cannot be reprojected — a bare :class:~digitalearth.base.sources.Source or raw array carrying a projected CRS or none at all — is rejected, with an error naming what is wrong.

A globe draws in EPSG:4326, and declares that as the scene's display CRS when the scene has none.

The sphere spans the cell centres, not the cell edges, as terrain does: geovista places one vertex per lon/lat pair, so a global field is drawn half a cell inside its own extent at each pole and meridian (#301).

Parameters:

Name Type Description Default
data Any

A pyramids Dataset (or anything :func:~digitalearth.base.sources.get_source accepts), or an already-built :class:~digitalearth.base.sources.Source whose x/y are longitude/latitude and whose z is the field to drape.

required
band int

1-based band index to read.

DEFAULT_BAND
cmap str | None

Colormap for the draped field. None (the default) resolves it from the variable through :func:~digitalearth.base.autostyle.auto_style — the same lookup the other three tiers use, so a field is drawn in the same colours whichever tier renders it.

None
coastlines bool

Overlay Natural-Earth coastlines on the globe.

True
coastline_resolution str

Coastline detail ("110m", "50m", "10m").

'110m'
coastline_color str

Colour of the coastline lines.

'black'
**kwargs Any

Forwarded to :meth:pyvista.Plotter.add_mesh for the field sphere.

{}

Returns:

Type Description
Any

The registered :class:pyvista.Actor for the field sphere.

Raises:

Type Description
ImportError

if the optional geovista dependency is not installed.

ValueError

if data cannot be reprojected and is not geographic — a Source in a projected CRS, or one with no CRS whose coordinates are not lon/lat — or if the scene is already drawn in a CRS other than EPSG:4326.

Examples:

  • Drape a cosine-of-latitude field on a globe with coastlines (needs the 3d extra / geovista):
    >>> import numpy as np
    >>> from digitalearth.three_d import Scene3D
    >>> from digitalearth.base.sources import get_source
    >>> lon = np.linspace(-180, 180, 37)
    >>> lat = np.linspace(-90, 90, 19)
    >>> field = np.add.outer(np.cos(np.deg2rad(lat)), np.zeros(len(lon)))
    >>> scene = Scene3D(off_screen=True)
    >>> actor = scene.globe(get_source(field, x=lon, y=lat), coastlines=False)
    >>> len(scene.layers)
    1
    >>> scene.close()
    
Source code in src/digitalearth/three_d/builders/globe.py
def globe(
    self,
    data: Any,
    *,
    name: Any = None,
    band: int = DEFAULT_BAND,
    cmap: str | None = None,
    coastlines: bool = True,
    coastline_resolution: str = "110m",
    coastline_color: str = "black",
    **kwargs: Any,
) -> Any:
    """Drape a global field onto a 3-D sphere and register it as a layer.

    Projected input is **reprojected, not refused**: a pyramids ``Dataset`` in any CRS is warped to
    EPSG:4326 through pyramids (``Dataset.to_crs``) on the way in, exactly as the static, interactive and
    web tiers do. Only input that cannot be reprojected — a bare
    :class:`~digitalearth.base.sources.Source` or raw array carrying a projected CRS or none at all — is
    rejected, with an error naming what is wrong.

    A globe draws in EPSG:4326, and declares that as the scene's display CRS when the scene has none.

    **The sphere spans the cell centres, not the cell edges**, as `terrain` does: geovista places one
    vertex per lon/lat pair, so a global field is drawn half a cell inside its own extent at each pole and
    meridian (#301).

    Args:
        data: A pyramids ``Dataset`` (or anything :func:`~digitalearth.base.sources.get_source` accepts), or an
            already-built :class:`~digitalearth.base.sources.Source` whose x/y are longitude/latitude and whose
            z is the field to drape.
        band: 1-based band index to read.
        cmap: Colormap for the draped field. ``None`` (the default) resolves it from the variable through
            :func:`~digitalearth.base.autostyle.auto_style` — the same lookup the other three tiers use, so
            a field is drawn in the same colours whichever tier renders it.
        coastlines: Overlay Natural-Earth coastlines on the globe.
        coastline_resolution: Coastline detail (``"110m"``, ``"50m"``, ``"10m"``).
        coastline_color: Colour of the coastline lines.
        **kwargs: Forwarded to :meth:`pyvista.Plotter.add_mesh` for the field sphere.

    Returns:
        The registered :class:`pyvista.Actor` for the field sphere.

    Raises:
        ImportError: if the optional ``geovista`` dependency is not installed.
        ValueError: if ``data`` cannot be reprojected and is not geographic — a ``Source`` in a projected
            CRS, or one with no CRS whose coordinates are not lon/lat — or if the scene is already drawn in
            a CRS other than EPSG:4326.

    Examples:
        - Drape a cosine-of-latitude field on a globe with coastlines (needs the ``3d`` extra / geovista):
            ```python
            >>> import numpy as np
            >>> from digitalearth.three_d import Scene3D
            >>> from digitalearth.base.sources import get_source
            >>> lon = np.linspace(-180, 180, 37)
            >>> lat = np.linspace(-90, 90, 19)
            >>> field = np.add.outer(np.cos(np.deg2rad(lat)), np.zeros(len(lon)))
            >>> scene = Scene3D(off_screen=True)
            >>> actor = scene.globe(get_source(field, x=lon, y=lat), coastlines=False)
            >>> len(scene.layers)
            1
            >>> scene.close()

            ```
    """
    actor = self._add_described_layer(
        kind="raster",
        data=data,
        name=name,
        selection=Selection(band=(band,)),
        cmap=cmap,
        **kwargs,
    )
    if coastlines:
        self._add_described_layer(
            kind="coastlines",
            resolution=coastline_resolution,
            color=coastline_color,
        )
    return actor

set_title(heading, *, subtitle=None, font_size=18, color=None) #

Give the scene a heading, and record it on the figure.

The Core contract's Tier-2 set_title, with the subtitle it declares: the same name, the same chainable return and the same meaning as on the other three tiers. A rendered scene travels alone — a screenshot, an exported page — so whatever context the notebook around it had is gone, and the heading has to be part of the picture.

The title is figure furniture, and described: it is the panel's own title, which PanelSpec already carries, so it survives figure_spec.to_dict() and is drawn again by :meth:~digitalearth.three_d.core.base.Scene3DBase.from_figure. It is not a layer — it has no place on the ground, it is not in the layer tree, and removing a layer never takes it with it.

Parameters:

Name Type Description Default
heading str

The title text, drawn centred along the top of the render window.

required
subtitle str | None

A smaller second line — a date, a source, a unit. Drawn in the upper-left corner rather than under the heading: a render window has one centred title band and the two lines in it cannot be sized apart. Recorded as drawing state rather than on the figure, exactly as the web tier records its own subtitle.

None
font_size int

Size of the heading in points; the subtitle is drawn at 60% of it.

18
color Any

Colour of both lines. None leaves PyVista's theme colour.

None

Returns:

Type Description
Self

This scene, so decoration chains.

Raises:

Type Description
TypeError

when heading is not a string. A title is the one piece of a figure a reader is certain to read, and None drawn as "None" is worse than no title.

Examples:

  • A heading is drawn and is part of what the scene describes:
    >>> from digitalearth.three_d import Scene3D
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.set_title("Elevation (m)", subtitle="SRTM, 2024")
    >>> scene.figure_spec.panels[0].title
    'Elevation (m)'
    >>> scene.close()
    
  • The heading survives the round trip the seam exists for:
    >>> from digitalearth.base.spec import FigureSpec
    >>> from digitalearth.three_d import Scene3D
    >>> first = Scene3D(off_screen=True)
    >>> stored = first.set_title("Elevation (m)").figure_spec.to_dict()
    >>> first.close()
    >>> second = Scene3D.from_figure(FigureSpec.from_dict(stored), off_screen=True)
    >>> second.figure_spec.panels[0].title
    'Elevation (m)'
    >>> second.close()
    
See Also

digitalearth.web.decoration.decoration.DecorationMixin.set_title: the same name on the web tier.

Source code in src/digitalearth/three_d/decoration/decoration.py
def set_title(
    self,
    heading: str,
    *,
    subtitle: str | None = None,
    font_size: int = 18,
    color: Any = None,
) -> Self:
    """Give the scene a heading, and record it on the figure.

    The Core contract's Tier-2 `set_title`, with the `subtitle` it declares: the same name, the same
    chainable return and the same meaning as on the other three tiers. A rendered scene travels alone —
    a screenshot, an exported page — so whatever context the notebook around it had is gone, and the
    heading has to be part of the picture.

    The title is **figure furniture, and described**: it is the panel's own `title`, which `PanelSpec`
    already carries, so it survives `figure_spec.to_dict()` and is drawn again by
    :meth:`~digitalearth.three_d.core.base.Scene3DBase.from_figure`. It is not a layer — it has no place on the
    ground, it is not in the layer tree, and removing a layer never takes it with it.

    Args:
        heading: The title text, drawn centred along the top of the render window.
        subtitle: A smaller second line — a date, a source, a unit. Drawn in the **upper-left corner**
            rather than under the heading: a render window has one centred title band and the two lines in
            it cannot be sized apart. Recorded as drawing state rather than on the figure, exactly as the
            web tier records its own subtitle.
        font_size: Size of the heading in points; the subtitle is drawn at 60% of it.
        color: Colour of both lines. `None` leaves PyVista's theme colour.

    Returns:
        This scene, so decoration chains.

    Raises:
        TypeError: when `heading` is not a string. A title is the one piece of a figure a reader is
            certain to read, and `None` drawn as `"None"` is worse than no title.

    Examples:
        - A heading is drawn and is part of what the scene describes:
            ```python
            >>> from digitalearth.three_d import Scene3D
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.set_title("Elevation (m)", subtitle="SRTM, 2024")
            >>> scene.figure_spec.panels[0].title
            'Elevation (m)'
            >>> scene.close()

            ```
        - The heading survives the round trip the seam exists for:
            ```python
            >>> from digitalearth.base.spec import FigureSpec
            >>> from digitalearth.three_d import Scene3D
            >>> first = Scene3D(off_screen=True)
            >>> stored = first.set_title("Elevation (m)").figure_spec.to_dict()
            >>> first.close()
            >>> second = Scene3D.from_figure(FigureSpec.from_dict(stored), off_screen=True)
            >>> second.figure_spec.panels[0].title
            'Elevation (m)'
            >>> second.close()

            ```

    See Also:
        digitalearth.web.decoration.decoration.DecorationMixin.set_title: the same name on the web tier.
    """
    if not isinstance(heading, str):
        raise TypeError(
            f"set_title() needs the heading as a string; got {type(heading).__name__}"
        )
    panel = with_fields(self._figure.panels[0], title=heading)
    self._figure = with_fields(self._figure, panels=(panel,))
    self._decoration["title"] = {
        "font_size": int(font_size),
        "color": color,
        "subtitle": subtitle,
    }
    redraw_decoration(self)
    return self

text(lon, lat, s=None, *, z=0.0, crs=4326, text_size=14.0, color=None, name=None, **kwargs) #

Place a single string at a coordinate, as a layer of its own.

The "label this spot" case, and the tier's answer to the Core contract's Tier-2 text: the same name, the same s/crs/name arguments and the same meaning as on the static, interactive and web tiers, plus the z a scene drawn in three dimensions needs.

The label is a layer, not furniture: it has an id, set_visible hides it, remove_layer takes it off, and it is drawn again from figure_spec.to_dict(). It does not set the scene's display CRS — an annotation is decoration, and decoration must not decide what coordinates the scene is drawn in — so a label given in another CRS is reprojected into the display CRS the data established. Add it after the layer that sets that CRS, or give the scene crs=, or there is nothing yet to reproject into.

Parameters:

Name Type Description Default
lon Any

X of the anchor, in crs — a longitude by default.

required
lat Any

Y of the anchor, in crs — a latitude by default.

required
s str | None

The string to draw. Named s as it is on the other three tiers, which follow matplotlib's own spelling.

None
z Any

Height of the anchor, in the scene's vertical units. 0.0 puts the label on the ground plane.

0.0
crs Any

What lon/lat are measured in. EPSG:4326 by default; a point in another CRS is reprojected into the scene's display CRS through pyramids, exactly as a layer's data is.

4326
text_size float

Text size in points. Named for the text rather than size, which is the visual size of a marker and nothing else (contract C3).

14.0
color Any

Text colour. None leaves PyVista's theme colour, so a label matches the scene it is drawn on.

None
name Any

The caller's name for the layer, used as its id; None numbers it by kind (text-1), and a name already on the scene is suffixed.

None
**kwargs Any

Forwarded to :meth:pyvista.Plotter.add_point_labels — bold, italic, shape, shape_color, always_visible, ….

{}

Returns:

Type Description
Self

This scene, so decoration chains.

Raises:

Type Description
TypeError

when the string to draw is not given.

ValueError

when lon, lat, z or text_size is not a finite number — a figure holding NaN or infinity could not be written down.

Examples:

  • Label a peak, and the label is a layer with an id like any other:
    >>> from digitalearth.three_d import Scene3D
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.text(0.0, 0.0, "origin", z=1.0, name="mark")
    >>> scene.layer_ids
    ['mark']
    >>> scene.get_layer("mark").kind
    'text'
    >>> scene.close()
    
  • A label is hidden and taken off by id, as a data layer is:
    >>> from digitalearth.three_d import Scene3D
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.text(0.0, 0.0, "origin").set_visible("text-1", False)
    >>> scene.renderer.is_visible("text-1")
    False
    >>> _ = scene.remove_layer("text-1")
    >>> scene.layer_ids
    []
    >>> scene.close()
    
See Also

digitalearth.static.builders.decoration.DecorationMixin.text: the same name on the static tier.

Source code in src/digitalearth/three_d/decoration/decoration.py
def text(
    self,
    lon: Any,
    lat: Any,
    s: str | None = None,
    *,
    z: Any = 0.0,
    crs: Any = 4326,
    text_size: float = 14.0,
    color: Any = None,
    name: Any = None,
    **kwargs: Any,
) -> Self:
    """Place a single string at a coordinate, as a layer of its own.

    The "label this spot" case, and the tier's answer to the Core contract's Tier-2 `text`: the same name,
    the same `s`/`crs`/`name` arguments and the same meaning as on the static, interactive and web tiers,
    plus the `z` a scene drawn in three dimensions needs.

    The label is a **layer**, not furniture: it has an id, `set_visible` hides it, `remove_layer` takes it
    off, and it is drawn again from `figure_spec.to_dict()`. It does **not** set the scene's display CRS —
    an annotation is decoration, and decoration must not decide what coordinates the scene is drawn in — so
    a label given in another CRS is reprojected into the display CRS the data established. Add it after the
    layer that sets that CRS, or give the scene `crs=`, or there is nothing yet to reproject into.

    Args:
        lon: X of the anchor, in `crs` — a longitude by default.
        lat: Y of the anchor, in `crs` — a latitude by default.
        s: The string to draw. Named `s` as it is on the other three tiers, which follow matplotlib's own
            spelling.
        z: Height of the anchor, in the scene's vertical units. `0.0` puts the label on the ground plane.
        crs: What `lon`/`lat` are measured in. EPSG:4326 by default; a point in another CRS is reprojected
            into the scene's display CRS through pyramids, exactly as a layer's data is.
        text_size: Text size in points. Named for the text rather than `size`, which is the visual size of
            a marker and nothing else (contract C3).
        color: Text colour. `None` leaves PyVista's theme colour, so a label matches the scene it is drawn
            on.
        name: The caller's name for the layer, used as its id; `None` numbers it by kind (`text-1`), and a
            name already on the scene is suffixed.
        **kwargs: Forwarded to :meth:`pyvista.Plotter.add_point_labels` — `bold`, `italic`, `shape`,
            `shape_color`, `always_visible`, ….

    Returns:
        This scene, so decoration chains.

    Raises:
        TypeError: when the string to draw is not given.
        ValueError: when `lon`, `lat`, `z` or `text_size` is not a finite number — a figure holding `NaN`
            or infinity could not be written down.

    Examples:
        - Label a peak, and the label is a layer with an id like any other:
            ```python
            >>> from digitalearth.three_d import Scene3D
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.text(0.0, 0.0, "origin", z=1.0, name="mark")
            >>> scene.layer_ids
            ['mark']
            >>> scene.get_layer("mark").kind
            'text'
            >>> scene.close()

            ```
        - A label is hidden and taken off by id, as a data layer is:
            ```python
            >>> from digitalearth.three_d import Scene3D
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.text(0.0, 0.0, "origin").set_visible("text-1", False)
            >>> scene.renderer.is_visible("text-1")
            False
            >>> _ = scene.remove_layer("text-1")
            >>> scene.layer_ids
            []
            >>> scene.close()

            ```

    See Also:
        digitalearth.static.builders.decoration.DecorationMixin.text: the same name on the static tier.
    """
    call = "Scene3D.text()"
    if s is None:
        raise TypeError(
            "text() needs the string to draw; pass it as the third argument"
        )
    self._add_described_layer(
        kind="text",
        name=name,
        s=s,
        x=_finite(lon, "lon", call),
        y=_finite(lat, "lat", call),
        z=_finite(z, "z", call),
        # In the shared CRS spelling: a caller may hand in a CRS object, which a figure written to JSON
        # has no form for, and this is how every other spec field holds one.
        crs=crs_to_json(crs, f"{call} crs="),
        text_size=_finite(text_size, "text_size", call),
        color=color,
        **kwargs,
    )
    return self

axes(show=True, *, xtitle=None, ytitle=None, ztitle=None, **kwargs) #

Draw a labelled box round the data, so the scene says what its coordinates are.

A 3-D render is otherwise an object floating in space: nothing on the window says how wide the ground is or how high the relief goes. This is PyVista's show_bounds — the box with ticks and axis titles — reached in the tier's own vocabulary, and titled from the scene's display CRS rather than from PyVista's X/Y/Z (see :func:axis_titles). The box's extent follows the renderer, so calling this before the data is added is fine: the box grows with what is drawn.

It is figure furniture, not a layer: it frames the data rather than being data, so it is not in the layer tree and removing a layer never takes it with it. It is not written into the figure either — see the module docstring for the two base/ registrations that would let it be.

Parameters:

Name Type Description Default
show bool

Whether the box is drawn. False takes it off, and keeps it off the next window the scene is given.

True
xtitle str | None

What to call the x axis. None names it from the display CRS.

None
ytitle str | None

What to call the y axis. None names it from the display CRS.

None
ztitle str | None

What to call the z axis. None names it from the display CRS.

None
**kwargs Any

Forwarded to :meth:pyvista.Plotter.show_bounds — grid, location, ticks, n_xlabels, font_size, all_edges, ….

{}

Returns:

Type Description
Self

This scene, so decoration chains.

Examples:

  • A projected scene names its own axes rather than showing letters:
    >>> from digitalearth.three_d import Scene3D
    >>> scene = Scene3D(off_screen=True, crs=32618)
    >>> _ = scene.axes()
    >>> box = scene.plotter.renderer.cube_axes_actor
    >>> box.GetXTitle(), box.GetYTitle(), box.GetZTitle()
    ('Easting', 'Northing', 'Elevation')
    >>> scene.close()
    
  • Off again, in one keyword rather than a second method:
    >>> from digitalearth.three_d import Scene3D
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.axes().axes(False)
    >>> scene.plotter.renderer.cube_axes_actor is None
    True
    >>> scene.close()
    
See Also

orientation_axes: the corner triad, which says which way the axes point.

Source code in src/digitalearth/three_d/decoration/decoration.py
def axes(
    self,
    show: bool = True,
    *,
    xtitle: str | None = None,
    ytitle: str | None = None,
    ztitle: str | None = None,
    **kwargs: Any,
) -> Self:
    """Draw a labelled box round the data, so the scene says what its coordinates are.

    A 3-D render is otherwise an object floating in space: nothing on the window says how wide the ground
    is or how high the relief goes. This is PyVista's `show_bounds` — the box with ticks and axis titles —
    reached in the tier's own vocabulary, and **titled from the scene's display CRS** rather than from
    PyVista's `X`/`Y`/`Z` (see :func:`axis_titles`). The box's extent follows the renderer, so calling this
    before the data is added is fine: the box grows with what is drawn.

    It is figure furniture, not a layer: it frames the data rather than being data, so it is not in the
    layer tree and removing a layer never takes it with it. It is **not** written into the figure either —
    see the module docstring for the two `base/` registrations that would let it be.

    Args:
        show: Whether the box is drawn. `False` takes it off, and keeps it off the next window the scene
            is given.
        xtitle: What to call the x axis. `None` names it from the display CRS.
        ytitle: What to call the y axis. `None` names it from the display CRS.
        ztitle: What to call the z axis. `None` names it from the display CRS.
        **kwargs: Forwarded to :meth:`pyvista.Plotter.show_bounds` — `grid`, `location`, `ticks`,
            `n_xlabels`, `font_size`, `all_edges`, ….

    Returns:
        This scene, so decoration chains.

    Examples:
        - A projected scene names its own axes rather than showing letters:
            ```python
            >>> from digitalearth.three_d import Scene3D
            >>> scene = Scene3D(off_screen=True, crs=32618)
            >>> _ = scene.axes()
            >>> box = scene.plotter.renderer.cube_axes_actor
            >>> box.GetXTitle(), box.GetYTitle(), box.GetZTitle()
            ('Easting', 'Northing', 'Elevation')
            >>> scene.close()

            ```
        - Off again, in one keyword rather than a second method:
            ```python
            >>> from digitalearth.three_d import Scene3D
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.axes().axes(False)
            >>> scene.plotter.renderer.cube_axes_actor is None
            True
            >>> scene.close()

            ```

    See Also:
        orientation_axes: the corner triad, which says which way the axes point.
    """
    if not show:
        self._decoration.pop("axes", None)
        if self._plotter is not None:
            self._plotter.remove_bounds_axes()
        return self
    self._decoration["axes"] = {
        "xtitle": xtitle,
        "ytitle": ytitle,
        "ztitle": ztitle,
        **kwargs,
    }
    redraw_decoration(self)
    return self

orientation_axes(show=True, *, xlabel=None, ylabel=None, zlabel=None, **kwargs) #

Show the corner triad, so a reader can tell which way the scene is being looked at from.

A 3-D scene has no fixed orientation — the camera decides — so the triad shows all three axes at once: three arrows in the corner of the window, turning with the camera, labelled for the CRS the scene draws in rather than X/Y/Z (see :func:axis_labels). For the one direction a map most wants named on its own, :meth:north_arrow draws a camera-aware single arrow instead.

Figure furniture, like :meth:axes: it sits in a corner of the window rather than in the scene's coordinates, so it is not a layer.

Parameters:

Name Type Description Default
show bool

Whether the triad is drawn. False hides it, and keeps it hidden on the next window.

True
xlabel str | None

What to label the x arrow. None labels it from the display CRS.

None
ylabel str | None

What to label the y arrow. None labels it from the display CRS.

None
zlabel str | None

What to label the z arrow. None labels it from the display CRS.

None
**kwargs Any

Forwarded to :meth:pyvista.Plotter.add_axes — line_width, x_color, viewport, labels_off, ….

{}

Returns:

Type Description
Self

This scene, so decoration chains.

Examples:

  • A lon/lat scene's triad is labelled in its own terms:
    >>> from digitalearth.three_d import Scene3D
    >>> scene = Scene3D(off_screen=True, crs=4326)
    >>> _ = scene.orientation_axes()
    >>> triad = scene.plotter.renderer.axes_actor
    >>> triad.GetXAxisLabelText(), triad.GetZAxisLabelText()
    ('Lon', 'Up')
    >>> scene.close()
    
See Also

axes: the labelled box, which says how far the coordinates reach.

Source code in src/digitalearth/three_d/decoration/decoration.py
def orientation_axes(
    self,
    show: bool = True,
    *,
    xlabel: str | None = None,
    ylabel: str | None = None,
    zlabel: str | None = None,
    **kwargs: Any,
) -> Self:
    """Show the corner triad, so a reader can tell which way the scene is being looked at from.

    A 3-D scene has no fixed orientation — the camera decides — so the triad shows all three axes at once:
    three arrows in the corner of the window, turning with the camera, labelled for the CRS the scene
    draws in rather than `X`/`Y`/`Z` (see :func:`axis_labels`). For the one direction a map most wants
    named on its own, :meth:`north_arrow` draws a camera-aware single arrow instead.

    Figure furniture, like :meth:`axes`: it sits in a corner of the window rather than in the scene's
    coordinates, so it is not a layer.

    Args:
        show: Whether the triad is drawn. `False` hides it, and keeps it hidden on the next window.
        xlabel: What to label the x arrow. `None` labels it from the display CRS.
        ylabel: What to label the y arrow. `None` labels it from the display CRS.
        zlabel: What to label the z arrow. `None` labels it from the display CRS.
        **kwargs: Forwarded to :meth:`pyvista.Plotter.add_axes` — `line_width`, `x_color`, `viewport`,
            `labels_off`, ….

    Returns:
        This scene, so decoration chains.

    Examples:
        - A lon/lat scene's triad is labelled in its own terms:
            ```python
            >>> from digitalearth.three_d import Scene3D
            >>> scene = Scene3D(off_screen=True, crs=4326)
            >>> _ = scene.orientation_axes()
            >>> triad = scene.plotter.renderer.axes_actor
            >>> triad.GetXAxisLabelText(), triad.GetZAxisLabelText()
            ('Lon', 'Up')
            >>> scene.close()

            ```

    See Also:
        axes: the labelled box, which says how far the coordinates reach.
    """
    if not show:
        self._decoration.pop("orientation_axes", None)
        if self._plotter is not None:
            self._plotter.hide_axes()
        return self
    self._decoration["orientation_axes"] = {
        "xlabel": xlabel,
        "ylabel": ylabel,
        "zlabel": zlabel,
        **kwargs,
    }
    redraw_decoration(self)
    return self

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

Show the continuous colour key of a layer — PyVista's scalar bar, as a guide on its encoding.

The Core contract's colorbar, in the shape the web tier already answers to (#299, #261): the same name, the same three keywords and the same meaning. What order 24 changes is where the key lives. It is recorded on the layer's colour :class:~digitalearth.base.spec.encoding.Encoding and then drawn from that record, so it moves with the layer, hides with it, goes away with it, and comes back when the layer's description is drawn again.

Parameters:

Name Type Description Default
layer_id str | None

Which layer's key to show. None takes the most recent layer that is coloured by data — not simply the last layer added, since a label or a flat-coloured mesh drawn after a terrain has nothing to key.

None
label str | None

What to call the bar — the variable and its units, usually. None leaves it titled after the array the colour is driven by, which is the title PyVista's own bar already carries.

None
visible bool

False draws no bar, so a caller passing a flag through does not have to branch. The layer is still resolved and checked first, so one spelling is not valid only half the time.

True

Returns:

Type Description
Self

This scene, so the call chains.

Raises:

Type Description
KeyError

when layer_id names no layer on this scene.

ValueError

when the named layer is not coloured by data; when none is and none was named; when the layer is coloured by classes, whose key is :meth:legend (a scalar bar over class indices reads 0, 1, 2 …); or when label is a title another layer's bar already holds.

Examples:

  • A terrain's bar, titled, and recorded on the layer that carries it:
    >>> import numpy as np
    >>> from digitalearth.base.sources import get_source
    >>> from digitalearth.three_d import Scene3D
    >>> dem = get_source(np.add.outer(np.arange(8.0), np.arange(8.0)))
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.terrain(dem)
    >>> _ = scene.colorbar(label="Elevation (m)")
    >>> scene.get_layer("terrain-1").symbology.guide().title
    'Elevation (m)'
    >>> "Elevation (m)" in scene.plotter.scalar_bars
    True
    >>> scene.close()
    
  • The key goes away with its layer:
    >>> import numpy as np
    >>> from digitalearth.base.sources import get_source
    >>> from digitalearth.three_d import Scene3D
    >>> dem = get_source(np.add.outer(np.arange(8.0), np.arange(8.0)))
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.terrain(dem)
    >>> _ = scene.colorbar(label="Elevation (m)")
    >>> _ = scene.remove_layer("terrain-1")
    >>> list(scene.plotter.scalar_bars.keys())
    []
    >>> scene.close()
    
See Also

legend: the keyed list, for a layer coloured by classes. digitalearth.web.core.base.WebMapBase.colorbar: the same name on the web tier.

Source code in src/digitalearth/three_d/legends/legend.py
def colorbar(
    self,
    layer_id: str | None = None,
    *,
    label: str | None = None,
    visible: bool = True,
) -> Self:
    """Show the continuous colour key of a layer — PyVista's scalar bar, as a guide on its encoding.

    The Core contract's `colorbar`, in the shape the web tier already answers to (#299, #261): the same
    name, the same three keywords and the same meaning. What order 24 changes is where the key lives. It
    is recorded on the layer's colour :class:`~digitalearth.base.spec.encoding.Encoding` and **then**
    drawn from that record, so it moves with the layer, hides with it, goes away with it, and comes back
    when the layer's description is drawn again.

    Args:
        layer_id: Which layer's key to show. `None` takes the most recent layer that is **coloured by
            data** — not simply the last layer added, since a label or a flat-coloured mesh drawn after a
            terrain has nothing to key.
        label: What to call the bar — the variable and its units, usually. `None` leaves it titled after
            the array the colour is driven by, which is the title PyVista's own bar already carries.
        visible: `False` draws no bar, so a caller passing a flag through does not have to branch. The
            layer is still resolved and checked first, so one spelling is not valid only half the time.

    Returns:
        This scene, so the call chains.

    Raises:
        KeyError: when `layer_id` names no layer on this scene.
        ValueError: when the named layer is not coloured by data; when none is and none was named; when
            the layer is coloured by **classes**, whose key is :meth:`legend` (a scalar bar over class
            indices reads `0, 1, 2 …`); or when `label` is a title another layer's bar already holds.

    Examples:
        - A terrain's bar, titled, and recorded on the layer that carries it:
            ```python
            >>> import numpy as np
            >>> from digitalearth.base.sources import get_source
            >>> from digitalearth.three_d import Scene3D
            >>> dem = get_source(np.add.outer(np.arange(8.0), np.arange(8.0)))
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.terrain(dem)
            >>> _ = scene.colorbar(label="Elevation (m)")
            >>> scene.get_layer("terrain-1").symbology.guide().title
            'Elevation (m)'
            >>> "Elevation (m)" in scene.plotter.scalar_bars
            True
            >>> scene.close()

            ```
        - The key goes away with its layer:
            ```python
            >>> import numpy as np
            >>> from digitalearth.base.sources import get_source
            >>> from digitalearth.three_d import Scene3D
            >>> dem = get_source(np.add.outer(np.arange(8.0), np.arange(8.0)))
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.terrain(dem)
            >>> _ = scene.colorbar(label="Elevation (m)")
            >>> _ = scene.remove_layer("terrain-1")
            >>> list(scene.plotter.scalar_bars.keys())
            []
            >>> scene.close()

            ```

    See Also:
        legend: the keyed list, for a layer coloured by classes.
        digitalearth.web.core.base.WebMapBase.colorbar: the same name on the web tier.
    """
    self._record_guide(
        layer_id,
        title=label,
        visible=visible,
        caller="colorbar()",
        keyed=False,
    )
    return self

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

Show the keyed colour list of a layer — PyVista's legend box, as a guide on its encoding.

The Core contract's legend, and PENDING's "a keyed list beside a scene". The rows are derived from the layer's own :class:~digitalearth.base.spec.scale.Scale through :meth:~digitalearth.base.spec.legend.LegendSpec.from_scale, and their colours are read back off the lookup table the layer is being drawn through — so a swatch cannot disagree with the picture, which is the whole reason that type exists.

A render window holds one legend box, so the box is built from every layer that asks for one, in draw order, rather than the last caller replacing the previous one. Where more than one layer contributes, each row is prefixed with that layer's title, since an unprefixed box says nothing about which layer a swatch belongs to.

Parameters:

Name Type Description Default
layer_id str | None

Which layer's classes to list. None takes the most recent layer coloured by data.

None
title str | None

Heading for this layer's rows. None uses the column or array the colour is driven by.

None
labels Sequence[str] | None

The caller's own row labels, replacing the derived ones — for units, or for renaming categories. One per row: a list that does not number the classes this layer contributes is refused, as it is on the other three tiers, because a short one leaves swatches unlabelled and a long one labels swatches that are not drawn. Recorded as drawn state on the scene rather than in the figure, exactly as :meth:~digitalearth.three_d.decoration.decoration.DecorationMixin.set_title's font size and subtitle are: the guide is what travels, and the labels are how this tier draws it. None clears labels an earlier call recorded, bringing the derived ranges or categories back, so one call's override does not outlive it.

None
visible bool

False draws none of this layer's rows. The layer is resolved and checked first.

True

Returns:

Type Description
Self

This scene, so the call chains.

Raises:

Type Description
KeyError

when layer_id names no layer on this scene.

ValueError

when the named layer is not coloured by data; when none is and none was named; when the layer is coloured by a continuous ramp, which has no classes to list — its key is :meth:colorbar; or when labels does not number the rows the layer contributes.

Examples:

  • A classified point cloud's classes, listed with the colours they were drawn in:
    >>> import numpy as np
    >>> from digitalearth.three_d import Scene3D
    >>> points = np.column_stack([np.arange(20.0), np.arange(20.0), np.zeros(20)])
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.point_cloud(points, values=points[:, 0], scheme="quantiles", k=4)
    >>> _ = scene.legend(title="Distance")
    >>> scene.plotter.legend.GetNumberOfEntries()
    4
    >>> scene.close()
    
  • The caller's own labels replace the derived ranges:
    >>> import numpy as np
    >>> from digitalearth.three_d import Scene3D
    >>> points = np.column_stack([np.arange(20.0), np.arange(20.0), np.zeros(20)])
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.point_cloud(points, values=points[:, 0], scheme="quantiles", k=2)
    >>> _ = scene.legend(labels=["low", "high"])
    >>> scene.plotter.legend.GetEntryString(0)
    'low'
    >>> scene.close()
    
See Also

colorbar: the scalar bar, for a layer coloured by a continuous ramp. digitalearth.web.legends.legend.LegendMixin.legend: the same name on the web tier.

Source code in src/digitalearth/three_d/legends/legend.py
def legend(
    self,
    layer_id: str | None = None,
    *,
    title: str | None = None,
    labels: Sequence[str] | None = None,
    visible: bool = True,
) -> Self:
    """Show the keyed colour list of a layer — PyVista's legend box, as a guide on its encoding.

    The Core contract's `legend`, and `PENDING`'s *"a keyed list beside a scene"*. The rows are derived
    from the layer's own :class:`~digitalearth.base.spec.scale.Scale` through
    :meth:`~digitalearth.base.spec.legend.LegendSpec.from_scale`, and their colours are read back off the
    lookup table the layer is being **drawn** through — so a swatch cannot disagree with the picture,
    which is the whole reason that type exists.

    A render window holds one legend box, so the box is built from **every** layer that asks for one, in
    draw order, rather than the last caller replacing the previous one. Where more than one layer
    contributes, each row is prefixed with that layer's title, since an unprefixed box says nothing about
    which layer a swatch belongs to.

    Args:
        layer_id: Which layer's classes to list. `None` takes the most recent layer coloured by data.
        title: Heading for this layer's rows. `None` uses the column or array the colour is driven by.
        labels: The caller's own row labels, replacing the derived ones — for units, or for renaming
            categories. One per row: a list that does not number the classes this layer contributes is
            refused, as it is on the other three tiers, because a short one leaves swatches unlabelled
            and a long one labels swatches that are not drawn. Recorded as **drawn state** on the scene
            rather than in the figure, exactly as
            :meth:`~digitalearth.three_d.decoration.decoration.DecorationMixin.set_title`'s font size and subtitle
            are: the guide is what travels, and the labels are how this tier draws it. `None` clears
            labels an earlier call recorded, bringing the derived ranges or categories back, so one
            call's override does not outlive it.
        visible: `False` draws none of this layer's rows. The layer is resolved and checked first.

    Returns:
        This scene, so the call chains.

    Raises:
        KeyError: when `layer_id` names no layer on this scene.
        ValueError: when the named layer is not coloured by data; when none is and none was named; when
            the layer is coloured by a **continuous ramp**, which has no classes to list — its key is
            :meth:`colorbar`; or when `labels` does not number the rows the layer contributes.

    Examples:
        - A classified point cloud's classes, listed with the colours they were drawn in:
            ```python
            >>> import numpy as np
            >>> from digitalearth.three_d import Scene3D
            >>> points = np.column_stack([np.arange(20.0), np.arange(20.0), np.zeros(20)])
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.point_cloud(points, values=points[:, 0], scheme="quantiles", k=4)
            >>> _ = scene.legend(title="Distance")
            >>> scene.plotter.legend.GetNumberOfEntries()
            4
            >>> scene.close()

            ```
        - The caller's own labels replace the derived ranges:
            ```python
            >>> import numpy as np
            >>> from digitalearth.three_d import Scene3D
            >>> points = np.column_stack([np.arange(20.0), np.arange(20.0), np.zeros(20)])
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.point_cloud(points, values=points[:, 0], scheme="quantiles", k=2)
            >>> _ = scene.legend(labels=["low", "high"])
            >>> scene.plotter.legend.GetEntryString(0)
            'low'
            >>> scene.close()

            ```

    See Also:
        colorbar: the scalar bar, for a layer coloured by a continuous ramp.
        digitalearth.web.legends.legend.LegendMixin.legend: the same name on the web tier.
    """
    self._record_guide(
        layer_id,
        title=title,
        visible=visible,
        caller="legend()",
        keyed=True,
        labels=labels,
    )
    return self

orbit(path, *, n_frames=36, fps=DEFAULT_FPS, factor=3.0, shift=0.0, viewup=None, **orbit_kwargs) #

Sweep the camera around the scene and write the fly-through to a GIF/MP4.

factor, shift and viewup shape the path the camera travels; the rest of orbit_kwargs tunes how it is flown along that path. They belong to two different pyvista calls, which is why they are separate arguments rather than one pass-through bag.

viewup shapes both — the circle the camera flies and the camera's own up vector. Before these arguments existed it reached only the camera, so a caller who passed it got a path built around the theme's up vector and a camera holding a different one, which rolls the horizon through the turn. That is now a behaviour change for such a caller, and a deliberate one: the two cannot sensibly disagree.

Parameters:

Name Type Description Default
path str

Output file. A video suffix (.mp4/.mov/.avi/.m4v) writes a movie; anything else a GIF.

required
n_frames int

Number of frames (camera positions) along the orbit. A whole number, at least 3. pyvista silently clamps a smaller value to 3, so fewer used to "work" and produce a three-frame clip; this rejects it instead, which is a narrowing of what the argument accepted before.

36
fps float

Frames per second of the output. Defaults to :data:DEFAULT_FPS (3.0) — the one speed shared with every other tier's animation entry point, declared once in :mod:digitalearth.base.animation; this method used to default to 12.

DEFAULT_FPS
factor float

Orbit radius as a multiple of the scene's bounding size. Smaller closes in on the data. Must be positive and finite. Anything float() accepts is taken, so "0.9" works as well as 0.9.

3.0
shift float

How far to lift the orbit off the data's mid-plane, as an absolute offset along viewup (so along z while viewup is z-aligned, which is the default). It is in scene units, not a fraction, so the useful value depends on the data's own extent along that vector and on any z_exaggeration applied to it — it has to be picked per scene. The default 0.0 circles level with the middle of the data, which for near-flat terrain is an edge-on view of a sheet.

0.0
viewup UpVector | None

Up vector for the path and the camera alike, as three floats. None leaves pyvista's default.

None
**orbit_kwargs Any

Forwarded to :meth:pyvista.Plotter.orbit_on_path, whose signature names what it accepts — step and focus are the useful ones here. It takes no **kwargs, so a keyword it does not name raises :class:TypeError; factor and shift are not among them, which is why they are named arguments above. progress_bar=True additionally needs tqdm, which the 3d extra does not install.

{}

Returns:

Type Description
str

The path written.

Raises:

Type Description
ValueError

If factor is not a positive finite number, shift is not a finite number, n_frames is not a whole number of at least 3, or viewup is not three finite numbers with a direction (a zero vector gives none). Non-numeric values are rejected here too, by name — numpy's own message for them names neither the argument nor this method. Also if threaded=True is passed: :meth:pyvista.Plotter.orbit_on_path returns before its render thread has written a frame, so the writer here would already be closed and no file would be produced — drive that method yourself for a background render.

TypeError

If orbit_kwargs carries a keyword orbit_on_path does not name; it takes no **kwargs of its own. The frame writer is still closed when that happens.

Examples:

  • Orbit a terrain scene to a GIF (needs the 3d extra for imageio):
    >>> import numpy as np, os, tempfile
    >>> from digitalearth.three_d import Scene3D
    >>> from digitalearth.base.sources import get_source
    >>> dem = np.add.outer(np.linspace(0, 1, 8), np.linspace(0, 1, 8))
    >>> with tempfile.TemporaryDirectory() as folder, Scene3D(off_screen=True) as scene:
    ...     _ = scene.terrain(get_source(dem), z_exaggeration=3.0)
    ...     out = scene.orbit(os.path.join(folder, "spin.gif"), n_frames=6)
    ...     size = os.path.getsize(out)
    >>> size > 0
    True
    
  • Close the orbit in and lift it clear of the terrain, so a near-flat sheet is looked down on rather than seen edge-on. The orbit sits at the middle of the data, so a shift greater than half the vertical extent lifts the camera above it — 3.0 for this scene, whose z runs 0..6. Pick it from your own data's extent, not from this example:
    >>> import numpy as np, os, tempfile
    >>> from digitalearth.three_d import Scene3D
    >>> from digitalearth.base.sources import get_source
    >>> dem = np.add.outer(np.linspace(0, 1, 8), np.linspace(0, 1, 8))
    >>> with tempfile.TemporaryDirectory() as folder, Scene3D(off_screen=True) as scene:
    ...     _ = scene.terrain(get_source(dem), z_exaggeration=3.0)
    ...     out = scene.orbit(
    ...         os.path.join(folder, "spin.gif"), n_frames=4, factor=0.9, shift=8.0
    ...     )
    ...     size = os.path.getsize(out)
    >>> size > 0
    True
    
Source code in src/digitalearth/three_d/temporal/animation.py
def orbit(
    self,
    path: str,
    *,
    n_frames: int = 36,
    fps: float = DEFAULT_FPS,
    factor: float = 3.0,
    shift: float = 0.0,
    viewup: UpVector | None = None,
    **orbit_kwargs: Any,
) -> str:
    """Sweep the camera around the scene and write the fly-through to a GIF/MP4.

    ``factor``, ``shift`` and ``viewup`` shape the path the camera travels; the rest of ``orbit_kwargs``
    tunes how it is flown along that path. They belong to two different pyvista calls, which is why they
    are separate arguments rather than one pass-through bag.

    ``viewup`` shapes **both** — the circle the camera flies and the camera's own up vector. Before these
    arguments existed it reached only the camera, so a caller who passed it got a path built around the
    theme's up vector and a camera holding a different one, which rolls the horizon through the turn. That
    is now a behaviour change for such a caller, and a deliberate one: the two cannot sensibly disagree.

    Args:
        path: Output file. A video suffix (``.mp4``/``.mov``/``.avi``/``.m4v``) writes a movie;
            anything else a GIF.
        n_frames: Number of frames (camera positions) along the orbit. A whole number, at least 3.
            pyvista silently
            clamps a smaller value to 3, so fewer used to "work" and produce a three-frame clip; this
            rejects it instead, which is a narrowing of what the argument accepted before.
        fps: Frames per second of the output. Defaults to :data:`DEFAULT_FPS` (``3.0``) — the one
            speed shared with every other tier's animation entry point, declared once in
            :mod:`digitalearth.base.animation`; this method used to default to ``12``.
        factor: Orbit radius as a multiple of the scene's bounding size. Smaller closes in on the data.
            Must be positive and finite. Anything ``float()`` accepts is taken, so ``"0.9"`` works as
            well as ``0.9``.
        shift: How far to lift the orbit off the data's mid-plane, as an absolute offset **along**
            ``viewup`` (so along z while ``viewup`` is z-aligned, which is the default). It is in scene
            units, not a fraction, so the useful value depends on the data's own extent along that vector
            and on any ``z_exaggeration`` applied to it — it has to be picked per scene. The default
            ``0.0`` circles level with the middle of the data, which for near-flat terrain is an edge-on
            view of a sheet.
        viewup: Up vector for the path and the camera alike, as three floats. ``None`` leaves pyvista's
            default.
        **orbit_kwargs: Forwarded to :meth:`pyvista.Plotter.orbit_on_path`, whose signature names what it
            accepts — ``step`` and ``focus`` are the useful ones here. It takes no ``**kwargs``, so a
            keyword it does not name raises :class:`TypeError`; ``factor`` and ``shift`` are not among
            them, which is why they are named arguments above. ``progress_bar=True`` additionally needs
            ``tqdm``, which the ``3d`` extra does not install.

    Returns:
        The ``path`` written.

    Raises:
        ValueError: If ``factor`` is not a positive finite number, ``shift`` is not a finite number,
            ``n_frames`` is not a whole number of at least 3, or ``viewup`` is not three finite numbers
            with a direction (a zero vector gives none). Non-numeric values are rejected here too, by
            name — numpy's own message for them names neither the argument nor this method. Also if
            ``threaded=True`` is passed: :meth:`pyvista.Plotter.orbit_on_path` returns
            before its render thread has written a frame, so the writer here would already be closed and
            no file would be produced — drive that method yourself for a background render.
        TypeError: If ``orbit_kwargs`` carries a keyword ``orbit_on_path`` does not name; it takes no
            ``**kwargs`` of its own. The frame writer is still closed when that happens.

    Examples:
        - Orbit a terrain scene to a GIF (needs the ``3d`` extra for imageio):
            ```python
            >>> import numpy as np, os, tempfile
            >>> from digitalearth.three_d import Scene3D
            >>> from digitalearth.base.sources import get_source
            >>> dem = np.add.outer(np.linspace(0, 1, 8), np.linspace(0, 1, 8))
            >>> with tempfile.TemporaryDirectory() as folder, Scene3D(off_screen=True) as scene:
            ...     _ = scene.terrain(get_source(dem), z_exaggeration=3.0)
            ...     out = scene.orbit(os.path.join(folder, "spin.gif"), n_frames=6)
            ...     size = os.path.getsize(out)
            >>> size > 0
            True

            ```
        - Close the orbit in and lift it clear of the terrain, so a near-flat sheet is looked down on
          rather than seen edge-on. The orbit sits at the middle of the data, so a shift greater than half
          the vertical extent lifts the camera above it — 3.0 for this scene, whose z runs 0..6. Pick it
          from your own data's extent, not from this example:
            ```python
            >>> import numpy as np, os, tempfile
            >>> from digitalearth.three_d import Scene3D
            >>> from digitalearth.base.sources import get_source
            >>> dem = np.add.outer(np.linspace(0, 1, 8), np.linspace(0, 1, 8))
            >>> with tempfile.TemporaryDirectory() as folder, Scene3D(off_screen=True) as scene:
            ...     _ = scene.terrain(get_source(dem), z_exaggeration=3.0)
            ...     out = scene.orbit(
            ...         os.path.join(folder, "spin.gif"), n_frames=4, factor=0.9, shift=8.0
            ...     )
            ...     size = os.path.getsize(out)
            >>> size > 0
            True

            ```
    """
    factor = _finite_number(factor, "factor (orbit radius)")
    if factor <= 0:
        raise ValueError(
            f"orbit() needs a positive, finite factor (orbit radius), got {factor!r}"
        )
    shift = _finite_number(shift, "shift")
    if not isinstance(n_frames, (int, np.integer)) or n_frames < 3:
        raise ValueError(
            f"orbit() needs a whole number of frames, at least 3, got {n_frames!r}"
        )
    viewup = _up_vector(viewup)
    if orbit_kwargs.get("threaded"):
        # orbit_on_path(threaded=True) returns before the render thread has written a frame, so the
        # finally below closes the writer first and the file is never created — silently, with a path
        # returned as if it had been. Refuse rather than hand back a filename for nothing.
        raise ValueError(
            "orbit() writes frames synchronously and closes the writer as it returns, so threaded=True "
            "would finish after the file was closed and produce nothing. Drive plotter.orbit_on_path "
            "directly if you need a background render."
        )
    _open_writer(self.plotter, path, fps)
    try:
        orbital_path = self.plotter.generate_orbital_path(
            factor=factor, n_points=n_frames, viewup=viewup, shift=shift
        )
        # The path and the camera take the same up vector: generating the path around one while the camera
        # holds another rolls the horizon through the turn.
        self.plotter.orbit_on_path(
            orbital_path, write_frames=True, viewup=viewup, **orbit_kwargs
        )
    finally:
        _finalize_frames(
            self.plotter
        )  # always flush/close the writer, even if rendering raised
    return path

record(frames, path, update, *, fps=DEFAULT_FPS, clim=None) #

Render a frame-by-frame animation driven by update and write it to a GIF/MP4.

For each item in frames, update(self, frame) mutates the scene (e.g. swaps the active scalars or re-adds a layer), then one frame is written. Typical frames is a DatasetCollection time stack.

Freeze the colour scale with clim so a time stack does not flicker (#210). When update re-draws a layer each frame, each builder derives its own colour range from that frame's data, so the range moves frame to frame and the clip flickers. Passing clim=(low, high) pins the colour range on every drawn colour-mapped layer (the scalar bar follows its mapper) after each update, so one scale spans the whole animation — compute it once over the full stack (e.g. (stack.values.min(), stack.values.max())) and hand it in. None (the default) keeps the per-frame behaviour. A ray-cast volume's range is :meth:~digitalearth.three_d.builders.volume.VolumeMixin.volume's own clim= instead.

Scope: clim pins every colour-mapped layer in the scene, not only the one update animates. That is what the time-stack use case wants (there is one data layer), but in a scene that holds a second colour-mapped layer on a different scale, that layer is clamped to clim too for the recording. To hold one layer while others keep their own range, build them in separate scenes.

Parameters:

Name Type Description Default
frames Iterable[Any]

Iterable of per-frame states passed one at a time to update.

required
path str

Output file. A video suffix writes a movie; anything else a GIF.

required
update Callable[[AnimationMixin, Any], None]

Callback (scene, frame) -> None that updates the scene before each frame is captured.

required
fps float

Frames per second of the output. Defaults to :data:DEFAULT_FPS (3.0) — the one speed shared with every other tier's animation entry point, declared once in :mod:digitalearth.base.animation; this method used to default to 8.

DEFAULT_FPS
clim tuple[float, float] | None

(low, high) colour range held fixed across every frame, applied to every colour-mapped layer in the scene (a ray-cast volume is excepted — its range stays volume(clim=)'s). None lets each frame keep the range its own data drives (the pre-#210 behaviour).

None

Returns:

Type Description
str

The path written.

Raises:

Type Description
ValueError

if clim is given but is not two finite numbers with low < high.

Examples:

  • Animate a growing terrain over three frames:
    >>> import numpy as np, os, tempfile
    >>> from digitalearth.three_d import Scene3D
    >>> from digitalearth.base.sources import get_source
    >>> dem = np.add.outer(np.linspace(0, 1, 8), np.linspace(0, 1, 8))
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.terrain(get_source(dem))
    >>> def grow(s, factor):
    ...     s.layers[0][0].points[:, 2] *= factor
    >>> with tempfile.TemporaryDirectory() as folder:
    ...     out = scene.record([1.1, 1.1, 1.1], os.path.join(folder, "grow.gif"), grow)
    ...     size = os.path.getsize(out)
    >>> scene.close()
    >>> size > 0
    True
    
  • Freeze the colour scale across frames whose data ranges differ, so a time stack does not flicker: two frames (elevation ~0..2, then ~0..50) re-draw the layer, but clim=(0, 50) keeps the drawn range fixed rather than letting it follow the last frame:
    >>> import numpy as np, os, tempfile
    >>> from digitalearth.three_d import Scene3D
    >>> from digitalearth.base.sources import get_source
    >>> def swap(s, array):
    ...     s.remove_layer("dem")
    ...     s.terrain(get_source(array), name="dem")
    >>> low = np.add.outer(np.linspace(0, 1, 8), np.linspace(0, 1, 8))
    >>> high = low * 50.0
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.terrain(get_source(low), name="dem")
    >>> with tempfile.TemporaryDirectory() as folder:
    ...     _ = scene.record(
    ...         [low, high], os.path.join(folder, "stack.gif"), swap, clim=(0.0, 50.0)
    ...     )
    >>> tuple(scene.actor_of("dem").mapper.scalar_range)
    (0.0, 50.0)
    >>> scene.close()
    
Source code in src/digitalearth/three_d/temporal/animation.py
def record(
    self,
    frames: Iterable[Any],
    path: str,
    update: Callable[["AnimationMixin", Any], None],
    *,
    fps: float = DEFAULT_FPS,
    clim: tuple[float, float] | None = None,
) -> str:
    """Render a frame-by-frame animation driven by ``update`` and write it to a GIF/MP4.

    For each item in ``frames``, ``update(self, frame)`` mutates the scene (e.g. swaps the active scalars or
    re-adds a layer), then one frame is written. Typical ``frames`` is a ``DatasetCollection`` time stack.

    **Freeze the colour scale with ``clim`` so a time stack does not flicker (#210).** When ``update``
    re-draws a layer each frame, each builder derives its own colour range from that frame's data, so the
    range moves frame to frame and the clip flickers. Passing ``clim=(low, high)`` pins the colour range on
    every drawn colour-mapped layer (the scalar bar follows its mapper) after each ``update``, so one scale
    spans the whole animation — compute it once over the full stack (e.g.
    ``(stack.values.min(), stack.values.max())``) and hand it in. ``None`` (the default) keeps the per-frame
    behaviour. A ray-cast volume's range is :meth:`~digitalearth.three_d.builders.volume.VolumeMixin.volume`'s own
    ``clim=`` instead.

    Scope: ``clim`` pins **every** colour-mapped layer in the scene, not only the one ``update`` animates.
    That is what the time-stack use case wants (there is one data layer), but in a scene that holds a second
    colour-mapped layer on a different scale, that layer is clamped to ``clim`` too for the recording. To hold
    one layer while others keep their own range, build them in separate scenes.

    Args:
        frames: Iterable of per-frame states passed one at a time to ``update``.
        path: Output file. A video suffix writes a movie; anything else a GIF.
        update: Callback ``(scene, frame) -> None`` that updates the scene before each frame is captured.
        fps: Frames per second of the output. Defaults to :data:`DEFAULT_FPS` (``3.0``) — the one
            speed shared with every other tier's animation entry point, declared once in
            :mod:`digitalearth.base.animation`; this method used to default to ``8``.
        clim: ``(low, high)`` colour range held fixed across every frame, applied to **every** colour-mapped
            layer in the scene (a ray-cast volume is excepted — its range stays ``volume(clim=)``'s).
            ``None`` lets each frame keep the range its own data drives (the pre-#210 behaviour).

    Returns:
        The ``path`` written.

    Raises:
        ValueError: if ``clim`` is given but is not two finite numbers with ``low < high``.

    Examples:
        - Animate a growing terrain over three frames:
            ```python
            >>> import numpy as np, os, tempfile
            >>> from digitalearth.three_d import Scene3D
            >>> from digitalearth.base.sources import get_source
            >>> dem = np.add.outer(np.linspace(0, 1, 8), np.linspace(0, 1, 8))
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.terrain(get_source(dem))
            >>> def grow(s, factor):
            ...     s.layers[0][0].points[:, 2] *= factor
            >>> with tempfile.TemporaryDirectory() as folder:
            ...     out = scene.record([1.1, 1.1, 1.1], os.path.join(folder, "grow.gif"), grow)
            ...     size = os.path.getsize(out)
            >>> scene.close()
            >>> size > 0
            True

            ```
        - Freeze the colour scale across frames whose data ranges differ, so a time stack does not
          flicker: two frames (elevation ~0..2, then ~0..50) re-draw the layer, but ``clim=(0, 50)``
          keeps the drawn range fixed rather than letting it follow the last frame:
            ```python
            >>> import numpy as np, os, tempfile
            >>> from digitalearth.three_d import Scene3D
            >>> from digitalearth.base.sources import get_source
            >>> def swap(s, array):
            ...     s.remove_layer("dem")
            ...     s.terrain(get_source(array), name="dem")
            >>> low = np.add.outer(np.linspace(0, 1, 8), np.linspace(0, 1, 8))
            >>> high = low * 50.0
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.terrain(get_source(low), name="dem")
            >>> with tempfile.TemporaryDirectory() as folder:
            ...     _ = scene.record(
            ...         [low, high], os.path.join(folder, "stack.gif"), swap, clim=(0.0, 50.0)
            ...     )
            >>> tuple(scene.actor_of("dem").mapper.scalar_range)
            (0.0, 50.0)
            >>> scene.close()

            ```
    """
    frozen = _checked_clim(clim)
    _open_writer(self.plotter, path, fps)
    try:
        for frame in frames:
            update(self, frame)
            if frozen is not None:
                # After `update` (which may have re-drawn the layer), before the frame is captured, so the
                # colour scale is the same every frame rather than whatever this frame's data derived.
                _freeze_colour_range(self, frozen)
            self.plotter.write_frame()
    finally:
        _finalize_frames(
            self.plotter
        )  # always flush/close the writer, even if a frame raised
    return path

jupyter(backend='trame') #

Switch PyVista's rendering backend so the scene displays interactively in a notebook.

The backend is PyVista's, set process-wide rather than per scene, so it stays in force for every plotter until something changes it back.

Parameters:

Name Type Description Default
backend str

A PyVista Jupyter backend — "trame" (default, server/remote), "client" (vtk.js), "static" (screenshot), or "html".

'trame'

Examples:

  • Switch to the static (screenshot) backend and read the change back. The restore is in a finally because the backend is process-wide: doctests share one interpreter, and a failure between the switch and the restore would leave every later one on a renderer nobody chose:
    >>> import pyvista as pv
    >>> from digitalearth.three_d import Scene3D
    >>> scene = Scene3D(off_screen=True)
    >>> previous = pv.global_theme.jupyter_backend
    >>> try:
    ...     scene.jupyter("static")
    ...     pv.global_theme.jupyter_backend
    ... finally:
    ...     scene.close()
    ...     pv.set_jupyter_backend(previous)
    'static'
    
See Also

orbit: writes a fly-through to a file instead, for when a notebook is not the destination.

Source code in src/digitalearth/three_d/temporal/animation.py
def jupyter(self, backend: str = "trame") -> None:
    """Switch PyVista's rendering backend so the scene displays interactively in a notebook.

    The backend is PyVista's, set process-wide rather than per scene, so it stays in force for every
    plotter until something changes it back.

    Args:
        backend: A PyVista Jupyter backend — ``"trame"`` (default, server/remote), ``"client"`` (vtk.js),
            ``"static"`` (screenshot), or ``"html"``.

    Examples:
        - Switch to the static (screenshot) backend and read the change back. The restore is in a
          ``finally`` because the backend is process-wide: doctests share one interpreter, and a failure
          between the switch and the restore would leave every later one on a renderer nobody chose:
            ```python
            >>> import pyvista as pv
            >>> from digitalearth.three_d import Scene3D
            >>> scene = Scene3D(off_screen=True)
            >>> previous = pv.global_theme.jupyter_backend
            >>> try:
            ...     scene.jupyter("static")
            ...     pv.global_theme.jupyter_backend
            ... finally:
            ...     scene.close()
            ...     pv.set_jupyter_backend(previous)
            'static'

            ```

    See Also:
        orbit: writes a fly-through to a file instead, for when a notebook is not the destination.
    """
    import pyvista as pv

    pv.set_jupyter_backend(backend)

get_layer(layer_id) #

Return the description of one layer, by id.

Parameters:

Name Type Description Default
layer_id str

The layer to look up.

required

Returns:

Name Type Description
Its LayerSpec

class:~digitalearth.base.spec.LayerSpec — kind, source, symbology, band and visibility.

Raises:

Type Description
KeyError

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

Examples:

  • What a builder recorded, read back by id:
    >>> import numpy as np
    >>> from digitalearth.base.sources import get_source
    >>> from digitalearth.three_d import Scene3D
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.terrain(get_source(np.add.outer(np.arange(4.0), np.arange(5.0))))
    >>> scene.get_layer("terrain-1").kind
    'terrain'
    >>> scene.close()
    
Source code in src/digitalearth/three_d/core/base.py
def get_layer(self, layer_id: str) -> LayerSpec:
    """Return the description of one layer, by id.

    Args:
        layer_id: The layer to look up.

    Returns:
        Its :class:`~digitalearth.base.spec.LayerSpec` — kind, source, symbology, band and visibility.

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

    Examples:
        - What a builder recorded, read back by id:
            ```python
            >>> import numpy as np
            >>> from digitalearth.base.sources import get_source
            >>> from digitalearth.three_d import Scene3D
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.terrain(get_source(np.add.outer(np.arange(4.0), np.arange(5.0))))
            >>> scene.get_layer("terrain-1").kind
            'terrain'
            >>> scene.close()

            ```
    """
    self._require_layer(layer_id)
    return self._figure.layers.get(layer_id)

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.

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 scene, or outside the layer's band (#292).

Note

VTK composites its actors by depth, so this changes the description rather than the picture. It is recorded because the figure is drawn by the other tiers too, where order decides what is on top.

Examples:

  • Two layers, reordered by id:
    >>> import numpy as np
    >>> from digitalearth.base.sources import get_source
    >>> from digitalearth.three_d import Scene3D
    >>> scene = Scene3D(off_screen=True)
    >>> dem = get_source(np.add.outer(np.arange(4.0), np.arange(5.0)))
    >>> _ = scene.terrain(dem, name="under")
    >>> _ = scene.terrain(dem, name="over")
    >>> scene.move_layer("over", 0).layer_ids
    ['over', 'under']
    >>> scene.close()
    
Source code in src/digitalearth/three_d/core/base.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.

    Returns:
        This scene (chainable).

    Raises:
        KeyError: if no layer has that id.
        IndexError: if the position is outside the scene, or outside the layer's band (#292).

    Note:
        VTK composites its actors by depth, so this changes the description rather than the picture. It is
        recorded because the figure is drawn by the other tiers too, where order decides what is on top.

    Examples:
        - Two layers, reordered by id:
            ```python
            >>> import numpy as np
            >>> from digitalearth.base.sources import get_source
            >>> from digitalearth.three_d import Scene3D
            >>> scene = Scene3D(off_screen=True)
            >>> dem = get_source(np.add.outer(np.arange(4.0), np.arange(5.0)))
            >>> _ = scene.terrain(dem, name="under")
            >>> _ = scene.terrain(dem, name="over")
            >>> scene.move_layer("over", 0).layer_ids
            ['over', 'under']
            >>> scene.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 scene.
    self._require_layer(layer_id)
    self._change(
        self._figure_with(layers=self._figure.layers.move(layer_id, index))
    )
    return self

remove_layer(layer_id) #

Take a layer off the scene, 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.

Examples:

  • A layer added and then removed leaves nothing behind:
    >>> import numpy as np
    >>> from digitalearth.base.sources import get_source
    >>> from digitalearth.three_d import Scene3D
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.terrain(get_source(np.add.outer(np.arange(4.0), np.arange(5.0))))
    >>> scene.remove_layer("terrain-1").layer_ids
    []
    >>> len(scene.layers)
    0
    >>> scene.close()
    
Source code in src/digitalearth/three_d/core/base.py
def remove_layer(self, layer_id: str) -> Self:
    """Take a layer off the scene, 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.

    Examples:
        - A layer added and then removed leaves nothing behind:
            ```python
            >>> import numpy as np
            >>> from digitalearth.base.sources import get_source
            >>> from digitalearth.three_d import Scene3D
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.terrain(get_source(np.add.outer(np.arange(4.0), np.arange(5.0))))
            >>> scene.remove_layer("terrain-1").layer_ids
            []
            >>> len(scene.layers)
            0
            >>> scene.close()

            ```
    """
    self._require_layer(layer_id)
    dropped = self._figure.layers.get(layer_id).source_id
    sources = {
        key: ref for key, ref in self._figure.sources.items() if key != dropped
    }
    self._change(
        self._figure_with(
            layers=self._figure.layers.remove(layer_id), sources=sources
        )
    )
    self._custom.pop(layer_id, None)
    # The reference goes out of *this* scene's figure and the object stays registered — the policy the
    # other three tiers settled in round 1 and state at their own `remove_layer`: a `FigureSpec` captured
    # before the removal still names the source, so forgetting here made every such figure undrawable
    # (`KeyError: no object is registered as ...`). This tier forgot and cited the web tier for it, which
    # says the opposite in so many words (review R2-M12). The leak that forgetting was added for is
    # answered by :meth:`close`, which calls `forget_namespace` on this scene's own namespace — the caller
    # saying they are finished with every figure it produced.
    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 added: the renderer draws it again from the new description, since VTK bakes a colormap into the mesh it built.

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 declare — a plugin's kind on a machine without the plugin reads as that.

KeyError

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

ValueError

if layer is not a LayerSpec — naming the method and the type it was handed, since the commonest form of this is passing the id where the description belongs — or if it draws from data and names no source_id: the drawers read the source from the figure, and a missing one reached get_source(None) and answered with a TypeError nothing documents.

Examples:

  • A layer redrawn in another colormap keeps its id:
    >>> import numpy as np
    >>> from dataclasses import replace
    >>> from digitalearth.base.spec import Symbology
    >>> from digitalearth.base.sources import get_source
    >>> from digitalearth.three_d import Scene3D
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.terrain(get_source(np.add.outer(np.arange(4.0), np.arange(5.0))))
    >>> held = scene.get_layer("terrain-1")
    >>> _ = scene.replace_layer(replace(held, symbology=Symbology(props={"cmap": "magma"})))
    >>> scene.get_layer("terrain-1").symbology.props["cmap"]
    'magma'
    >>> scene.close()
    
Source code in src/digitalearth/three_d/core/base.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 added: the renderer draws it again
    from the new description, since VTK bakes a colormap into the mesh it built.

    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 declare — a plugin's kind on
            a machine without the plugin reads as that.
        KeyError: if no layer has that id, naming the ids that do.
        ValueError: if `layer` is not a `LayerSpec` — naming the method and the type it was handed, since
            the commonest form of this is passing the id where the description belongs — or if it draws
            from data and names no `source_id`: the drawers read the source from the figure, and a missing
            one reached `get_source(None)` and answered with a `TypeError` nothing documents.

    Examples:
        - A layer redrawn in another colormap keeps its id:
            ```python
            >>> import numpy as np
            >>> from dataclasses import replace
            >>> from digitalearth.base.spec import Symbology
            >>> from digitalearth.base.sources import get_source
            >>> from digitalearth.three_d import Scene3D
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.terrain(get_source(np.add.outer(np.arange(4.0), np.arange(5.0))))
            >>> held = scene.get_layer("terrain-1")
            >>> _ = scene.replace_layer(replace(held, symbology=Symbology(props={"cmap": "magma"})))
            >>> scene.get_layer("terrain-1").symbology.props["cmap"]
            'magma'
            >>> scene.close()

            ```
    """
    # By type before by id: `layer.id` was read straight off the argument, so anything that is not a
    # description died as `AttributeError: 'str' object has no attribute 'id'` — Python's words about this
    # tier's internals, naming neither the method nor what it wanted. `isinstance` rather than a duck-typed
    # `hasattr`, because an object carrying only `.id` and `.kind` got past the id lookup *and* the
    # capability gate and died three checks deep at `layer.source_id`, having already been accepted twice
    # (review R2-M9). The four tiers gave four classes for one bad argument; this is the fourth to settle.
    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 fourth production caller of `Capabilities.require` (D-10), joining the other three tiers. 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 plotter is touched. Without it the refusal came from the drawer
    # table part-way through a reconcile, as a `KeyError` that said nothing about what the tier declares.
    CAPABILITIES.require(layer.kind, caller="Scene3D.replace_layer")
    if layer.source_id is None and kind_info(layer.kind).takes != "none":
        # The drawers hand `_source_object`'s `None` straight to `get_source`, which answers with a
        # `TypeError` nothing documents — and, going through `_change`, used to leave the scene holding
        # a figure it could not draw (review L9). A layer that draws from data says where it is.
        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(layers=self._figure.layers.replace(layer)))
    return self

set_visible(layer_id, visible=True) #

Show or hide a layer, by id.

The layer stays in the scene and in its description — which is what lets a viewer switch it back on, and what tells a saved figure that the layer is there but hidden.

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 numpy as np
    >>> from digitalearth.base.sources import get_source
    >>> from digitalearth.three_d import Scene3D
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.terrain(get_source(np.add.outer(np.arange(4.0), np.arange(5.0))))
    >>> hidden = scene.set_visible("terrain-1", False)
    >>> hidden.figure_spec.layers.is_visible("terrain-1")
    False
    >>> scene.set_visible("terrain-1").figure_spec.layers.is_visible("terrain-1")
    True
    >>> scene.close()
    
Source code in src/digitalearth/three_d/core/base.py
def set_visible(self, layer_id: str, visible: bool = True) -> Self:
    """Show or hide a layer, by id.

    The layer stays in the scene and in its description — which is what lets a viewer switch it back on,
    and what tells a saved figure that the layer is there but hidden.

    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 numpy as np
            >>> from digitalearth.base.sources import get_source
            >>> from digitalearth.three_d import Scene3D
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.terrain(get_source(np.add.outer(np.arange(4.0), np.arange(5.0))))
            >>> hidden = scene.set_visible("terrain-1", False)
            >>> hidden.figure_spec.layers.is_visible("terrain-1")
            False
            >>> scene.set_visible("terrain-1").figure_spec.layers.is_visible("terrain-1")
            True
            >>> scene.close()

            ```
    """
    self._require_layer(layer_id)
    self._change(
        self._figure_with(layers=self._figure.layers.set_visible(layer_id, visible))
    )
    return self

from_figure(figure, **scene_kwargs) classmethod #

Build a scene and draw a figure into it.

This is the round trip the seam exists for: a scene describes itself with :attr:figure_spec, the description survives to_dict()/from_dict(), and this draws it again.

Parameters:

Name Type Description Default
figure FigureSpec

The figure to draw.

required
**scene_kwargs Any

Passed to the constructor — off_screen, window_size, strict, …. The display CRS comes from the figure's camera unless crs= is given here.

{}

Returns:

Type Description
Self

The scene, with every layer drawn.

Examples:

  • A figure written by one scene is drawn by another:
    >>> from digitalearth.base.spec import FigureSpec
    >>> from digitalearth.three_d import Scene3D
    >>> first = Scene3D(off_screen=True)
    >>> _ = first.terrain("examples/data/acc4000.tif")
    >>> stored = first.figure_spec.to_dict()
    >>> first.close()
    >>> second = Scene3D.from_figure(FigureSpec.from_dict(stored), off_screen=True)
    >>> second.layer_ids
    ['terrain-1']
    >>> second.close()
    
Source code in src/digitalearth/three_d/core/base.py
@classmethod
def from_figure(cls, figure: FigureSpec, **scene_kwargs: Any) -> Self:
    """Build a scene and draw a figure into it.

    This is the round trip the seam exists for: a scene describes itself with :attr:`figure_spec`, the
    description survives `to_dict()`/`from_dict()`, and this draws it again.

    Args:
        figure: The figure to draw.
        **scene_kwargs: Passed to the constructor — `off_screen`, `window_size`, `strict`, …. The display
            CRS comes from the figure's camera unless `crs=` is given here.

    Returns:
        The scene, with every layer drawn.

    Examples:
        - A figure written by one scene is drawn by another:
            ```python
            >>> from digitalearth.base.spec import FigureSpec
            >>> from digitalearth.three_d import Scene3D
            >>> first = Scene3D(off_screen=True)
            >>> _ = first.terrain("examples/data/acc4000.tif")
            >>> stored = first.figure_spec.to_dict()
            >>> first.close()
            >>> second = Scene3D.from_figure(FigureSpec.from_dict(stored), off_screen=True)
            >>> second.layer_ids
            ['terrain-1']
            >>> second.close()

            ```
    """
    view = figure.panels[0].view
    crs = getattr(view, "crs", None)
    scene = cls(**{"crs": crs, **scene_kwargs})
    scene.draw_figure(figure)
    return scene

draw_figure(figure) #

Draw a figure into this scene, bringing it from whatever it showed before.

Parameters:

Name Type Description Default
figure FigureSpec

The figure to draw. Its one panel's camera becomes the scene's.

required

Returns:

Type Description
Self

This scene (chainable).

Raises:

Type Description
KeyError

when a layer names a kind this tier does not draw.

OffLimbError

when a layer cannot be drawn and the scene is strict.

Source code in src/digitalearth/three_d/core/base.py
def draw_figure(self, figure: FigureSpec) -> Self:
    """Draw a figure into this scene, bringing it from whatever it showed before.

    Args:
        figure: The figure to draw. Its one panel's camera becomes the scene's.

    Returns:
        This scene (chainable).

    Raises:
        KeyError: when a layer names a kind this tier does not draw.
        OffLimbError: when a layer cannot be drawn and the scene is `strict`.
    """
    view = figure.panels[0].view
    if isinstance(view, Camera):
        self.camera = view
    self._change(figure)
    # The panel's own `title` is part of the figure (#203), and nothing in the layer diff re-reads it, so
    # a heading drawn only at `set_title()` would be lost on exactly the round trip the seam exists for.
    from digitalearth.three_d.decoration.decoration import redraw_decoration

    redraw_decoration(self)
    return self

add_mesh(mesh, *, name=None, band=None, color_field=None, **kwargs) #

Add a PyVista mesh to the scene and register it as a layer.

The low-level entry point the capability mixins build on. kwargs pass straight to :meth:pyvista.Plotter.add_mesh (scalars, cmap, opacity, show_edges, pbr …).

An object you build yourself is a custom layer: what a figure keeps is its description — an id, the kind custom:pyvista, a label, a band and whether it is visible — and never the object, which has no description to write. The object stays with the scene that was handed it, so a figure saved and loaded again names the layer but cannot rebuild it, and another backend cannot draw it at all (:mod:digitalearth.base.custom says which case a reader is in). Name what the object's colour encodes with color_field and the layer carries a colour key, published as Encoding.by_field("color", color_field) the way a builder's is (#349).

Parameters:

Name Type Description Default
mesh Any

Any PyVista dataset (ImageData/StructuredGrid/PolyData/UnstructuredGrid).

required
color_field str | None

The name of the value the mesh's colour encodes. Names it so the custom layer carries a colour key for :meth:colorbar/:meth:legend (#349); None leaves it keyless.

None
**kwargs Any

Forwarded to :meth:pyvista.Plotter.add_mesh.

{}

Returns:

Type Description
Any

The registered :class:pyvista.Actor.

Examples:

  • Add one mesh and find it, paired with its actor, in the layer registry:
    >>> import pyvista as pv
    >>> from digitalearth.three_d.core.base import Scene3DBase
    >>> scene = Scene3DBase(off_screen=True)
    >>> actor = scene.add_mesh(pv.Sphere())
    >>> mesh, registered = scene.layers[0]
    >>> registered is actor
    True
    >>> scene.close()
    
  • Style the mesh through kwargs, then tune the returned actor further:
    >>> import numpy as np, pyvista as pv
    >>> from digitalearth.three_d.core.base import Scene3DBase
    >>> grid = pv.ImageData(dimensions=(8, 8, 1))
    >>> grid.point_data["z"] = np.linspace(0.0, 1.0, 64)
    >>> scene = Scene3DBase(off_screen=True)
    >>> actor = scene.add_mesh(grid, scalars="z", cmap="terrain", show_edges=True)
    >>> actor.prop.opacity = 0.5
    >>> len(scene.layers)
    1
    >>> scene.close()
    
See Also

add_volume: the ray-cast counterpart, for scalar fields rather than surfaces.

Source code in src/digitalearth/three_d/core/base.py
def add_mesh(
    self,
    mesh: Any,
    *,
    name: Any = None,
    band: Any = None,
    color_field: str | None = None,
    **kwargs: Any,
) -> Any:
    """Add a PyVista ``mesh`` to the scene and register it as a layer.

    The low-level entry point the capability mixins build on. ``kwargs`` pass straight to
    :meth:`pyvista.Plotter.add_mesh` (``scalars``, ``cmap``, ``opacity``, ``show_edges``, ``pbr`` …).

    An object you build yourself is a **custom layer**: what a figure keeps is its description — an id, the
    kind `custom:pyvista`, a label, a band and whether it is visible — and never the object, which has no
    description to write. The object stays with the scene that was handed it, so a figure saved and loaded
    again names the layer but cannot rebuild it, and another backend cannot draw it at all
    (:mod:`digitalearth.base.custom` says which case a reader is in). Name what the object's colour
    encodes with ``color_field`` and the layer carries a colour key, published as
    ``Encoding.by_field("color", color_field)`` the way a builder's is (#349).

    Args:
        mesh: Any PyVista dataset (``ImageData``/``StructuredGrid``/``PolyData``/``UnstructuredGrid``).
        color_field: The name of the value the mesh's colour encodes. Names it so the custom layer carries
            a colour key for :meth:`colorbar`/:meth:`legend` (#349); ``None`` leaves it keyless.
        **kwargs: Forwarded to :meth:`pyvista.Plotter.add_mesh`.

    Returns:
        The registered :class:`pyvista.Actor`.

    Examples:
        - Add one mesh and find it, paired with its actor, in the layer registry:
            ```python
            >>> import pyvista as pv
            >>> from digitalearth.three_d.core.base import Scene3DBase
            >>> scene = Scene3DBase(off_screen=True)
            >>> actor = scene.add_mesh(pv.Sphere())
            >>> mesh, registered = scene.layers[0]
            >>> registered is actor
            True
            >>> scene.close()

            ```
        - Style the mesh through ``kwargs``, then tune the returned actor further:
            ```python
            >>> import numpy as np, pyvista as pv
            >>> from digitalearth.three_d.core.base import Scene3DBase
            >>> grid = pv.ImageData(dimensions=(8, 8, 1))
            >>> grid.point_data["z"] = np.linspace(0.0, 1.0, 64)
            >>> scene = Scene3DBase(off_screen=True)
            >>> actor = scene.add_mesh(grid, scalars="z", cmap="terrain", show_edges=True)
            >>> actor.prop.opacity = 0.5
            >>> len(scene.layers)
            1
            >>> scene.close()

            ```

    See Also:
        add_volume: the ray-cast counterpart, for scalar fields rather than surfaces.
    """
    return self._add_custom(
        mesh, name=name, band=band, volume=False, color_field=color_field, **kwargs
    )

add_volume(volume, *, name=None, band=None, color_field=None, **kwargs) #

Add a volumetric volume (ray-cast rendering) and register it as a layer.

An object you build yourself is a custom layer: what a figure keeps is its description — an id, the kind custom:pyvista, a label, a band and whether it is visible — and never the object, which has no description to write. The object stays with the scene that was handed it, so a figure saved and loaded again names the layer but cannot rebuild it, and another backend cannot draw it at all (:mod:digitalearth.base.custom says which case a reader is in). Name what the object's colour encodes with color_field and the layer carries a colour key, published as Encoding.by_field("color", color_field) the way a builder's is (#349).

Parameters:

Name Type Description Default
volume Any

An ImageData/UnstructuredGrid carrying a scalar field to ray-cast.

required
color_field str | None

The name of the value the volume's colour encodes. Names it so the custom layer carries a colour key for :meth:colorbar/:meth:legend (#349); None leaves it keyless.

None
**kwargs Any

Forwarded to :meth:pyvista.Plotter.add_volume.

{}

Returns:

Type Description
Any

The registered volume actor.

Examples:

  • Ray-cast a 3-D scalar field and see it registered as one layer:
    >>> import numpy as np, pyvista as pv
    >>> from digitalearth.three_d.core.base import Scene3DBase
    >>> grid = pv.ImageData(dimensions=(6, 6, 6))
    >>> grid.cell_data["v"] = np.linspace(0.0, 1.0, 125)
    >>> scene = Scene3DBase(off_screen=True)
    >>> _ = scene.add_volume(grid, cmap="viridis")
    >>> len(scene.layers)
    1
    >>> scene.close()
    
  • A volume and a surface share the one plotter, stacking in add order:
    >>> import numpy as np, pyvista as pv
    >>> from digitalearth.three_d.core.base import Scene3DBase
    >>> grid = pv.ImageData(dimensions=(6, 6, 6))
    >>> grid.cell_data["v"] = np.linspace(0.0, 1.0, 125)
    >>> scene = Scene3DBase(off_screen=True)
    >>> _ = scene.add_volume(grid)
    >>> _ = scene.add_mesh(pv.Sphere(radius=1.0, center=(2, 2, 2)))
    >>> len(scene.layers)
    2
    >>> scene.close()
    
See Also

add_mesh: the surface counterpart, and the method the capability mixins call.

Source code in src/digitalearth/three_d/core/base.py
def add_volume(
    self,
    volume: Any,
    *,
    name: Any = None,
    band: Any = None,
    color_field: str | None = None,
    **kwargs: Any,
) -> Any:
    """Add a volumetric ``volume`` (ray-cast rendering) and register it as a layer.

    An object you build yourself is a **custom layer**: what a figure keeps is its description — an id, the
    kind `custom:pyvista`, a label, a band and whether it is visible — and never the object, which has no
    description to write. The object stays with the scene that was handed it, so a figure saved and loaded
    again names the layer but cannot rebuild it, and another backend cannot draw it at all
    (:mod:`digitalearth.base.custom` says which case a reader is in). Name what the object's colour
    encodes with ``color_field`` and the layer carries a colour key, published as
    ``Encoding.by_field("color", color_field)`` the way a builder's is (#349).

    Args:
        volume: An ``ImageData``/``UnstructuredGrid`` carrying a scalar field to ray-cast.
        color_field: The name of the value the volume's colour encodes. Names it so the custom layer
            carries a colour key for :meth:`colorbar`/:meth:`legend` (#349); ``None`` leaves it keyless.
        **kwargs: Forwarded to :meth:`pyvista.Plotter.add_volume`.

    Returns:
        The registered volume actor.

    Examples:
        - Ray-cast a 3-D scalar field and see it registered as one layer:
            ```python
            >>> import numpy as np, pyvista as pv
            >>> from digitalearth.three_d.core.base import Scene3DBase
            >>> grid = pv.ImageData(dimensions=(6, 6, 6))
            >>> grid.cell_data["v"] = np.linspace(0.0, 1.0, 125)
            >>> scene = Scene3DBase(off_screen=True)
            >>> _ = scene.add_volume(grid, cmap="viridis")
            >>> len(scene.layers)
            1
            >>> scene.close()

            ```
        - A volume and a surface share the one plotter, stacking in add order:
            ```python
            >>> import numpy as np, pyvista as pv
            >>> from digitalearth.three_d.core.base import Scene3DBase
            >>> grid = pv.ImageData(dimensions=(6, 6, 6))
            >>> grid.cell_data["v"] = np.linspace(0.0, 1.0, 125)
            >>> scene = Scene3DBase(off_screen=True)
            >>> _ = scene.add_volume(grid)
            >>> _ = scene.add_mesh(pv.Sphere(radius=1.0, center=(2, 2, 2)))
            >>> len(scene.layers)
            2
            >>> scene.close()

            ```

    See Also:
        add_mesh: the surface counterpart, and the method the capability mixins call.
    """
    return self._add_custom(
        volume, name=name, band=band, volume=True, color_field=color_field, **kwargs
    )

actor_of(layer_id) #

Return the actor drawn for a layer.

Parameters:

Name Type Description Default
layer_id str

The layer to look up.

required

Returns:

Type Description
Any

The PyVista actor, or None when the layer was described but not drawn.

Raises:

Type Description
KeyError

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

Source code in src/digitalearth/three_d/core/base.py
def actor_of(self, layer_id: str) -> Any:
    """Return the actor drawn for a layer.

    Args:
        layer_id: The layer to look up.

    Returns:
        The PyVista actor, or `None` when the layer was described but not drawn.

    Raises:
        KeyError: if no layer has that id, naming the ids that do.
    """
    return self._drawn_pair(layer_id, "actor")

mesh_of(layer_id) #

Return the mesh drawn for a layer.

Parameters:

Name Type Description Default
layer_id str

The layer to look up.

required

Returns:

Type Description
Any

The PyVista mesh, or None when the layer was described but not drawn.

Raises:

Type Description
KeyError

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

Examples:

  • The mesh a builder produced, reached by the layer's id rather than by position:
    >>> import numpy as np
    >>> from digitalearth.base.sources import get_source
    >>> from digitalearth.three_d import Scene3D
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.terrain(get_source(np.add.outer(np.arange(4.0), np.arange(5.0))))
    >>> scene.mesh_of("terrain-1").n_points
    20
    >>> scene.close()
    
Source code in src/digitalearth/three_d/core/base.py
def mesh_of(self, layer_id: str) -> Any:
    """Return the mesh drawn for a layer.

    Args:
        layer_id: The layer to look up.

    Returns:
        The PyVista mesh, or `None` when the layer was described but not drawn.

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

    Examples:
        - The mesh a builder produced, reached by the layer's id rather than by position:
            ```python
            >>> import numpy as np
            >>> from digitalearth.base.sources import get_source
            >>> from digitalearth.three_d import Scene3D
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.terrain(get_source(np.add.outer(np.arange(4.0), np.arange(5.0))))
            >>> scene.mesh_of("terrain-1").n_points
            20
            >>> scene.close()

            ```
    """
    return self._drawn_pair(layer_id, "mesh")

view(name) #

Look at the scene from a named view — "top", "front", "isometric", ….

The one-word half of the camera API. :attr:camera says exactly where to stand; this says it the way a figure caption does, over PyVista's own view_* methods, which frame the scene's current bounds from a direction. The names are a table a caller can add to (:func:~digitalearth.three_d.view.views.register_view), not a fixed list of methods.

The view is captured, not only applied: PyVista aims its camera, the scene reads the result back as a Camera and stores it. That is what makes the viewpoint survive the next render — which writes the stored camera onto the plotter — and what puts it on the figure's panel, in to_dict(), and anywhere else the view is read.

Parameters:

Name Type Description Default
name str

The view's name, as :func:~digitalearth.three_d.view.views.view_names lists it.

required

Returns:

Type Description
Self

The scene, so a view chains with the builders.

Raises:

Type Description
KeyError

for a name nothing registered; the message lists the names that do exist.

Examples:

  • Look at a DEM from straight above, and read the viewpoint back:
    >>> import numpy as np
    >>> from digitalearth.base.sources import get_source
    >>> from digitalearth.three_d import Scene3D
    >>> dem = np.add.outer(np.linspace(0, 1, 8), np.linspace(0, 1, 8))
    >>> scene = Scene3D(off_screen=True)
    >>> _ = scene.terrain(get_source(dem))
    >>> camera = scene.view("top").camera
    >>> camera.position[2] > camera.focal_point[2]
    True
    >>> scene.close()
    
  • The presets are absolute viewpoints, not turns, so the last one wins:
    >>> from digitalearth.three_d import Scene3D
    >>> scene = Scene3D(off_screen=True)
    >>> position = scene.view("top").view("front").camera.position
    >>> position[1] < 0.0, round(position[2], 6)
    (True, 0.0)
    >>> scene.close()
    
See Also

digitalearth.three_d.view.views: the table, and how to put a view of your own in it.

Source code in src/digitalearth/three_d/core/base.py
def view(self, name: str) -> Self:
    """Look at the scene from a named view — ``"top"``, ``"front"``, ``"isometric"``, ….

    The one-word half of the camera API. :attr:`camera` says exactly where to stand; this says it the way a
    figure caption does, over PyVista's own ``view_*`` methods, which frame the scene's current bounds from
    a direction. The names are a table a caller can add to
    (:func:`~digitalearth.three_d.view.views.register_view`), not a fixed list of methods.

    The view is **captured**, not only applied: PyVista aims its camera, the scene reads the result back as
    a `Camera` and stores it. That is what makes the viewpoint survive the next render — which writes the
    stored camera onto the plotter — and what puts it on the figure's panel, in `to_dict()`, and anywhere
    else the view is read.

    Args:
        name: The view's name, as :func:`~digitalearth.three_d.view.views.view_names` lists it.

    Returns:
        The scene, so a view chains with the builders.

    Raises:
        KeyError: for a name nothing registered; the message lists the names that do exist.

    Examples:
        - Look at a DEM from straight above, and read the viewpoint back:
            ```python
            >>> import numpy as np
            >>> from digitalearth.base.sources import get_source
            >>> from digitalearth.three_d import Scene3D
            >>> dem = np.add.outer(np.linspace(0, 1, 8), np.linspace(0, 1, 8))
            >>> scene = Scene3D(off_screen=True)
            >>> _ = scene.terrain(get_source(dem))
            >>> camera = scene.view("top").camera
            >>> camera.position[2] > camera.focal_point[2]
            True
            >>> scene.close()

            ```
        - The presets are absolute viewpoints, not turns, so the last one wins:
            ```python
            >>> from digitalearth.three_d import Scene3D
            >>> scene = Scene3D(off_screen=True)
            >>> position = scene.view("top").view("front").camera.position
            >>> position[1] < 0.0, round(position[2], 6)
            (True, 0.0)
            >>> scene.close()

            ```

    See Also:
        digitalearth.three_d.view.views: the table, and how to put a view of your own in it.
    """
    named_view(name).apply(self.plotter)
    self.camera = self._live_camera()
    return self

render() #

Build and return the renderer's own object — this tier's plotter.

Every tier answers to render() with the thing its engine draws on, so a caller who wants to reach past the facade has one name to learn. Here that is the pyvista.Plotter, built on first use (#290).

Returns:

Type Description
Any

The scene's plotter, with every layer drawn on it.

Examples:

  • The plotter is what a 3-D scene renders to:
    >>> from digitalearth.three_d import Scene3D
    >>> scene = Scene3D(off_screen=True)
    >>> scene.render() is scene.plotter
    True
    >>> scene.close()
    
Source code in src/digitalearth/three_d/core/base.py
def render(self) -> Any:
    """Build and return the renderer's own object — this tier's plotter.

    Every tier answers to `render()` with the thing its engine draws on, so a caller who wants to reach
    past the facade has one name to learn. Here that is the `pyvista.Plotter`, built on first use (#290).

    Returns:
        The scene's plotter, with every layer drawn on it.

    Examples:
        - The plotter is what a 3-D scene renders to:
            ```python
            >>> from digitalearth.three_d import Scene3D
            >>> scene = Scene3D(off_screen=True)
            >>> scene.render() is scene.plotter
            True
            >>> scene.close()

            ```
    """
    self._apply_camera()
    return self.plotter

screenshot(path=None, **kwargs) #

Render the scene off-screen and return the RGB image (optionally writing it to path).

Parameters:

Name Type Description Default
path Destination | None

Optional destination for the PNG, as a string or os.PathLike. When None the image is only returned.

None
**kwargs Any

Forwarded to :meth:pyvista.Plotter.screenshot.

{}

Returns:

Type Description
ndarray

numpy.ndarray: the (height, width, 3) RGB frame.

Examples:

  • Render to memory and work with the frame as an array:
    >>> import pyvista as pv
    >>> from digitalearth.three_d.core.base import Scene3DBase
    >>> scene = Scene3DBase(off_screen=True, window_size=(200, 150))
    >>> _ = scene.add_mesh(pv.Sphere())
    >>> frame = scene.screenshot()
    >>> frame.ndim, frame.shape[-1]
    (3, 3)
    >>> bool(frame.any())
    True
    >>> scene.close()
    
  • Write a PNG to disk; the frame is still returned:
    >>> import os, tempfile, pyvista as pv
    >>> from digitalearth.three_d.core.base import Scene3DBase
    >>> with tempfile.TemporaryDirectory() as folder:
    ...     scene = Scene3DBase(off_screen=True)
    ...     _ = scene.add_mesh(pv.Cube())
    ...     out = os.path.join(folder, "frame.png")
    ...     frame = scene.screenshot(path=out)
    ...     scene.close()
    ...     os.path.getsize(out) > 0
    True
    
See Also

save: dispatches here for the raster-frame suffixes (:data:IMAGE_SUFFIXES).

Source code in src/digitalearth/three_d/core/base.py
def screenshot(self, path: Destination | None = None, **kwargs: Any) -> np.ndarray:
    """Render the scene off-screen and return the RGB image (optionally writing it to ``path``).

    Args:
        path: Optional destination for the PNG, as a string or ``os.PathLike``. When ``None`` the
            image is only returned.
        **kwargs: Forwarded to :meth:`pyvista.Plotter.screenshot`.

    Returns:
        numpy.ndarray: the ``(height, width, 3)`` RGB frame.

    Examples:
        - Render to memory and work with the frame as an array:
            ```python
            >>> import pyvista as pv
            >>> from digitalearth.three_d.core.base import Scene3DBase
            >>> scene = Scene3DBase(off_screen=True, window_size=(200, 150))
            >>> _ = scene.add_mesh(pv.Sphere())
            >>> frame = scene.screenshot()
            >>> frame.ndim, frame.shape[-1]
            (3, 3)
            >>> bool(frame.any())
            True
            >>> scene.close()

            ```
        - Write a PNG to disk; the frame is still returned:
            ```python
            >>> import os, tempfile, pyvista as pv
            >>> from digitalearth.three_d.core.base import Scene3DBase
            >>> with tempfile.TemporaryDirectory() as folder:
            ...     scene = Scene3DBase(off_screen=True)
            ...     _ = scene.add_mesh(pv.Cube())
            ...     out = os.path.join(folder, "frame.png")
            ...     frame = scene.screenshot(path=out)
            ...     scene.close()
            ...     os.path.getsize(out) > 0
            True

            ```

    See Also:
        save: dispatches here for the raster-frame suffixes (:data:`IMAGE_SUFFIXES`).
    """
    if not self._effective_off_screen():
        # The scene renders on-screen, but a screenshot never needs a window: take it from a faithful
        # off-screen copy so the static-image path (this, `_repr_png_`, and `save` to a file) works
        # regardless of the resolved live mode or any pyvista global (#573) — that is what makes
        # `ds.plot(var, backend="3d")` embed inline in a notebook whose kernel never set
        # `pyvista.OFF_SCREEN` — without opening or disturbing the scene's live window.
        return self._offscreen_snapshot(path, **kwargs)
    self._apply_camera()
    return self.plotter.screenshot(filename=path, return_img=True, **kwargs)

save(path, **kwargs) #

Save the scene, dispatching on path's suffix — a rendered frame, or a scene export.

Two families share the one entry point, and the suffix decides which:

  • .html → :meth:export_html, a self-contained interactive page (see there for why a heavy scene is better served by :meth:digitalearth.three_d.Scene3D.orbit, and for the suffix normalisation it applies).
  • :data:IMAGE_SUFFIXES (.png .jpg .jpeg .bmp .tif .tiff) → :meth:screenshot, a rendered raster frame in the format the suffix names — .tif writes a TIFF, not a PNG.
  • :data:SCENE_EXPORTERS (.gltf .obj .vrml .wrl .vtksz) → the matching :class:pyvista.Plotter scene exporter, which writes the geometry itself rather than a picture of it.
  • :data:VECTOR_SUFFIXES (.svg .pdf .eps .ps .tex) → :meth:export_vector, a vector graphic of the view (GL2PS), with textured surfaces embedded as raster insets. These take no **kwargs — passing any with a vector suffix is refused rather than dropped.
  • anything else — including a path with no suffix at all — raises. A format is never invented on the caller's behalf, so save("scene") no longer quietly writes scene.png.

The suffix match is case-insensitive throughout (SCENE.HTML exports a page).

It returns the path it wrote, like every other tier's save(), so a caller can chain on the result without rebuilding the filename — and .html returns the normalised name, which is not always the one passed in.

Changed, with no transition: it used to return the RGB frame for a raster suffix, and None for an export — a return type that depended on the suffix, and gave the one branch producing a useful value no counterpart on the others. Ask for the frame by name instead: :meth:screenshot writes the same file and hands back the array, so frame = scene.save(out) becomes frame = scene.screenshot(out) — one call, the same two effects. Unlike the renamed keywords in this batch, which keep their old spelling for a release, a return type has no shim to offer: a value contrived to read as both a Path and an array would be worse than the break, so this one is announced rather than eased.

Parameters:

Name Type Description Default
path Destination

Output file, as a string or os.PathLike. Its suffix selects the branch.

required
**kwargs Any

Forwarded to the branch that runs — :meth:screenshot for a raster frame, the pyvista.Plotter exporter for a scene export (e.g. inline_data=False for .gltf); ignored for HTML.

{}

Returns:

Type Description
Path

pathlib.Path: the file that was written — path itself for every branch but .html, which

Path

returns the suffix-normalised name :meth:export_html actually wrote.

Raises:

Type Description
ValueError

when path has no suffix, or one outside the dispatch table; the message names both families' supported suffixes. Also when the installed pyvista lacks the exporter a supported scene suffix needs.

Examples:

  • A raster suffix screenshots, and hands back the path it wrote — not the frame:
    >>> import os, tempfile, pyvista as pv
    >>> from digitalearth.three_d.core.base import Scene3DBase
    >>> with tempfile.TemporaryDirectory() as folder:
    ...     scene = Scene3DBase(off_screen=True, window_size=(200, 150))
    ...     _ = scene.add_mesh(pv.Sphere())
    ...     out = os.path.join(folder, "scene.png")
    ...     written = scene.save(out)
    ...     scene.close()
    ...     written.name, written.is_file()
    ('scene.png', True)
    
  • A scene-export suffix writes the geometry through PyVista's own exporter, and returns its path the same way:
    >>> import os, tempfile, pyvista as pv
    >>> from digitalearth.three_d.core.base import Scene3DBase
    >>> with tempfile.TemporaryDirectory() as folder:
    ...     scene = Scene3DBase(off_screen=True)
    ...     _ = scene.add_mesh(pv.Sphere())
    ...     written = scene.save(os.path.join(folder, "scene.gltf"))
    ...     scene.close()
    ...     written.suffix, written.stat().st_size > 0
    ('.gltf', True)
    
  • An .html suffix exports an interactive page instead. The match is case-insensitive, and :meth:export_html normalises the suffix it writes — so SCENE.HTML lands as SCENE.html and the returned path is the normalised one, not the name that was passed:
    >>> import os, tempfile, pyvista as pv
    >>> from digitalearth.three_d.core.base import Scene3DBase
    >>> with tempfile.TemporaryDirectory() as folder:
    ...     scene = Scene3DBase(off_screen=True)
    ...     _ = scene.add_mesh(pv.Sphere())
    ...     written = scene.save(os.path.join(folder, "SCENE.HTML"))
    ...     scene.close()
    ...     written.name, sorted(os.listdir(folder))
    ('SCENE.html', ['SCENE.html'])
    
  • A suffix-less destination is an error, not a silent .png:
    >>> from digitalearth.three_d.core.base import Scene3DBase
    >>> scene = Scene3DBase(off_screen=True)
    >>> try:
    ...     scene.save("scene")
    ... except ValueError as error:
    ...     print(str(error).split(";")[0])
    ... finally:
    ...     scene.close()
    save() cannot infer a format from 'scene': it has no suffix
    
See Also

screenshot: the raster-frame branch, where its **kwargs end up, and the only method that returns the rendered array. export_html: the interactive-page branch.

Source code in src/digitalearth/three_d/core/base.py
def save(self, path: Destination, **kwargs: Any) -> Path:
    """Save the scene, dispatching on ``path``'s suffix — a rendered frame, or a scene export.

    Two families share the one entry point, and the suffix decides which:

    - ``.html`` → :meth:`export_html`, a self-contained interactive page (see there for why a heavy scene
      is better served by :meth:`digitalearth.three_d.Scene3D.orbit`, and for the suffix normalisation it
      applies).
    - :data:`IMAGE_SUFFIXES` (``.png`` ``.jpg`` ``.jpeg`` ``.bmp`` ``.tif`` ``.tiff``) →
      :meth:`screenshot`, a rendered raster frame **in the format the suffix names** — ``.tif`` writes a
      TIFF, not a PNG.
    - :data:`SCENE_EXPORTERS` (``.gltf`` ``.obj`` ``.vrml`` ``.wrl`` ``.vtksz``) → the matching
      :class:`pyvista.Plotter` scene exporter, which writes the geometry itself rather than a picture of
      it.
    - :data:`VECTOR_SUFFIXES` (``.svg`` ``.pdf`` ``.eps`` ``.ps`` ``.tex``) → :meth:`export_vector`, a
      vector graphic of the view (GL2PS), with textured surfaces embedded as raster insets. These take
      **no** ``**kwargs`` — passing any with a vector suffix is refused rather than dropped.
    - anything else — **including a path with no suffix at all** — raises. A format is never invented on
      the caller's behalf, so ``save("scene")`` no longer quietly writes ``scene.png``.

    The suffix match is case-insensitive throughout (``SCENE.HTML`` exports a page).

    **It returns the path it wrote**, like every other tier's ``save()``, so a caller can chain on the
    result without rebuilding the filename — and ``.html`` returns the *normalised* name, which is not
    always the one passed in.

    **Changed, with no transition: it used to return the RGB frame** for a raster suffix, and ``None``
    for an export — a return type that depended on the suffix, and gave the one branch producing a
    useful value no counterpart on the others. Ask for the frame by name instead:
    :meth:`screenshot` writes the same file *and* hands back the array, so ``frame = scene.save(out)``
    becomes ``frame = scene.screenshot(out)`` — one call, the same two effects. Unlike the renamed
    keywords in this batch, which keep their old spelling for a release, a return *type* has no shim to
    offer: a value contrived to read as both a ``Path`` and an array would be worse than the break, so
    this one is announced rather than eased.

    Args:
        path: Output file, as a string or ``os.PathLike``. Its suffix selects the branch.
        **kwargs: Forwarded to the branch that runs — :meth:`screenshot` for a raster frame, the
            ``pyvista.Plotter`` exporter for a scene export (e.g. ``inline_data=False`` for ``.gltf``);
            ignored for HTML.

    Returns:
        pathlib.Path: the file that was written — ``path`` itself for every branch but ``.html``, which
        returns the suffix-normalised name :meth:`export_html` actually wrote.

    Raises:
        ValueError: when ``path`` has no suffix, or one outside the dispatch table; the message names both
            families' supported suffixes. Also when the installed pyvista lacks the exporter a supported
            scene suffix needs.

    Examples:
        - A raster suffix screenshots, and hands back the path it wrote — not the frame:
            ```python
            >>> import os, tempfile, pyvista as pv
            >>> from digitalearth.three_d.core.base import Scene3DBase
            >>> with tempfile.TemporaryDirectory() as folder:
            ...     scene = Scene3DBase(off_screen=True, window_size=(200, 150))
            ...     _ = scene.add_mesh(pv.Sphere())
            ...     out = os.path.join(folder, "scene.png")
            ...     written = scene.save(out)
            ...     scene.close()
            ...     written.name, written.is_file()
            ('scene.png', True)

            ```
        - A scene-export suffix writes the geometry through PyVista's own exporter, and returns its path
          the same way:
            ```python
            >>> import os, tempfile, pyvista as pv
            >>> from digitalearth.three_d.core.base import Scene3DBase
            >>> with tempfile.TemporaryDirectory() as folder:
            ...     scene = Scene3DBase(off_screen=True)
            ...     _ = scene.add_mesh(pv.Sphere())
            ...     written = scene.save(os.path.join(folder, "scene.gltf"))
            ...     scene.close()
            ...     written.suffix, written.stat().st_size > 0
            ('.gltf', True)

            ```
        - An ``.html`` suffix exports an interactive page instead. The match is case-insensitive, and
          :meth:`export_html` normalises the suffix it writes — so ``SCENE.HTML`` lands as ``SCENE.html``
          and the returned path is the normalised one, not the name that was passed:
            ```python
            >>> import os, tempfile, pyvista as pv
            >>> from digitalearth.three_d.core.base import Scene3DBase
            >>> with tempfile.TemporaryDirectory() as folder:
            ...     scene = Scene3DBase(off_screen=True)
            ...     _ = scene.add_mesh(pv.Sphere())
            ...     written = scene.save(os.path.join(folder, "SCENE.HTML"))
            ...     scene.close()
            ...     written.name, sorted(os.listdir(folder))
            ('SCENE.html', ['SCENE.html'])

            ```
        - A suffix-less destination is an error, not a silent ``.png``:
            ```python
            >>> from digitalearth.three_d.core.base import Scene3DBase
            >>> scene = Scene3DBase(off_screen=True)
            >>> try:
            ...     scene.save("scene")
            ... except ValueError as error:
            ...     print(str(error).split(";")[0])
            ... finally:
            ...     scene.close()
            save() cannot infer a format from 'scene': it has no suffix

            ```

    See Also:
        screenshot: the raster-frame branch, where its ``**kwargs`` end up, and the only method that
            returns the rendered array.
        export_html: the interactive-page branch.
    """
    suffix = Path(str(path)).suffix.lower()
    if suffix == HTML_SUFFIX:
        # export_html normalises the suffix it writes, so report the name it actually produced rather
        # than the one that was asked for.
        return Path(self.export_html(path))
    if suffix in IMAGE_SUFFIXES:
        self.screenshot(path=path, **kwargs)
        return Path(str(path))
    exporter_name = SCENE_EXPORTERS.get(suffix)
    if exporter_name is not None:
        # Guarded with getattr rather than assumed: the exporter set is a pyvista capability, and a
        # version that lacks one must say so plainly instead of failing on a missing attribute.
        exporter = getattr(self.plotter, exporter_name, None)
        if exporter is None:
            import pyvista as pv

            raise ValueError(
                f"the installed pyvista ({pv.__version__}) has no Plotter.{exporter_name}, so {suffix!r} "
                f"cannot be exported; {supported_destinations()}"
            )
        exporter(str(path), **kwargs)
        return Path(str(path))
    if suffix in VECTOR_SUFFIXES:
        # A vector graphic routes through save_graphic, which takes none of save()'s **kwargs — so refuse
        # them by name rather than drop them silently (a raster suffix forwards them to screenshot).
        if kwargs:
            raise ValueError(
                f"save() passes no keywords to a vector export; got {sorted(kwargs)} with {suffix!r}. "
                "Drop them, or render a high-resolution raster master with screenshot(scale=N)"
            )
        return self.export_vector(path)
    reason = (
        "it has no suffix"
        if not suffix
        else f"{suffix!r} is not a format it can write"
    )
    raise ValueError(
        f"save() cannot infer a format from {str(path)!r}: {reason}; {supported_destinations()}"
    )

export_html(path) #

Export the scene to a self-contained interactive HTML page (via trame/vtk.js).

The page embeds the whole mesh, so it grows with the geometry rather than with the rendered image: about a 1 MB vtk.js floor plus ~19 bytes per point (a 12x12 grid gives 1.1 MB, 512x512 gives 6 MB, and a 4700x4700 DEM gives ~430 MB). Past a modest tile the result is technically interactive but too heavy to sit beside a notebook or in docs — prefer :meth:digitalearth.three_d.Scene3D.orbit, which writes a compact GIF/MP4 fly-through of the same scene.

The destination is normalised to a .html suffix before writing, and that normalised path is what comes back. pyvista's own behaviour here differs by version — the trame-pyvista component used from 0.49 rewrites a non-.html suffix, while 0.48's native export honours the name it was given — so normalising up front is what makes the two agree and keeps the returned path the file that exists.

Parameters:

Name Type Description Default
path Destination

Destination file. A suffix other than .html (including .HTML) is replaced with .html; a name with no suffix gains one. Replacement is :meth:pathlib.Path.with_suffix, matching what trame-pyvista does, so a dotted stem loses its last segment (report.v2 becomes report.html). Note :meth:save dispatches only on a literal .html suffix, so save("x.htm") raises on the unknown suffix while export_html("x.htm") writes x.html.

required

Returns:

Type Description
str

The .html path written, as a string.

Raises:

Type Description
ImportError

If the trame/vtk.js export stack is missing. pyvista raises this itself and its message names the package to install; the 3d extra pulls the stack via pyvista[jupyter]. Note pyvista's registry turns a failing plugin import into a UserWarning and drops the entry, so a broken-but-installed trame-pyvista reports that same message — when the package is present, read the warning for the real cause.

RuntimeError

If trame and pyvista are bound to different VTK builds — the message names VTK_MODULE_NAME, the variable that reconciles them.

Examples:

  • Export a small scene. Asking for scene.HTML writes scene.html, and the returned path is the normalised one — the page that exists, on either pyvista — so it can be passed straight on:
    >>> import os, tempfile, pyvista as pv
    >>> from digitalearth.three_d.core.base import Scene3DBase
    >>> with tempfile.TemporaryDirectory() as folder:
    ...     scene = Scene3DBase(off_screen=True)
    ...     _ = scene.add_mesh(pv.Sphere())
    ...     out = scene.export_html(os.path.join(folder, "scene.HTML"))
    ...     scene.close()
    ...     os.path.basename(out), os.path.getsize(out) > 0, sorted(os.listdir(folder))
    ('scene.html', True, ['scene.html'])
    
See Also

digitalearth.three_d.Scene3D.orbit: a compact GIF/MP4 fly-through, the better choice for a heavy scene. save: routes here automatically for a *.html destination.

Source code in src/digitalearth/three_d/core/base.py
def export_html(self, path: Destination) -> str:
    """Export the scene to a self-contained interactive HTML page (via trame/vtk.js).

    The page embeds the whole mesh, so it grows with the geometry rather than with the rendered image: about
    a 1 MB vtk.js floor plus ~19 bytes per point (a 12x12 grid gives 1.1 MB, 512x512 gives 6 MB, and a
    4700x4700 DEM gives ~430 MB). Past a modest tile the result is technically interactive but too heavy to
    sit beside a notebook or in docs — prefer :meth:`digitalearth.three_d.Scene3D.orbit`, which writes a
    compact GIF/MP4 fly-through of the same scene.

    The destination is normalised to a ``.html`` suffix before writing, and that normalised path is what
    comes back. pyvista's own behaviour here differs by version — the ``trame-pyvista`` component used from
    0.49 rewrites a non-``.html`` suffix, while 0.48's native export honours the name it was given — so
    normalising up front is what makes the two agree and keeps the returned path the file that exists.

    Args:
        path: Destination file. A suffix other than ``.html`` (including ``.HTML``) is replaced with
            ``.html``; a name with no suffix gains one. Replacement is :meth:`pathlib.Path.with_suffix`,
            matching what ``trame-pyvista`` does, so a dotted stem loses its last segment
            (``report.v2`` becomes ``report.html``). Note :meth:`save` dispatches only on a literal
            ``.html`` suffix, so ``save(\"x.htm\")`` raises on the unknown suffix while
            ``export_html(\"x.htm\")`` writes ``x.html``.

    Returns:
        The ``.html`` path written, as a string.

    Raises:
        ImportError: If the trame/vtk.js export stack is missing. pyvista raises this itself and its message
            names the package to install; the ``3d`` extra pulls the stack via ``pyvista[jupyter]``.
            Note pyvista's registry turns a *failing* plugin import into a ``UserWarning`` and drops the
            entry, so a broken-but-installed ``trame-pyvista`` reports that same message — when the
            package is present, read the warning for the real cause.
        RuntimeError: If trame and pyvista are bound to different VTK builds — the message names
            ``VTK_MODULE_NAME``, the variable that reconciles them.

    Examples:
        - Export a small scene. Asking for ``scene.HTML`` writes ``scene.html``, and the returned path is
          the normalised one — the page that exists, on either pyvista — so it can be passed straight on:
            ```python
            >>> import os, tempfile, pyvista as pv
            >>> from digitalearth.three_d.core.base import Scene3DBase
            >>> with tempfile.TemporaryDirectory() as folder:
            ...     scene = Scene3DBase(off_screen=True)
            ...     _ = scene.add_mesh(pv.Sphere())
            ...     out = scene.export_html(os.path.join(folder, "scene.HTML"))
            ...     scene.close()
            ...     os.path.basename(out), os.path.getsize(out) > 0, sorted(os.listdir(folder))
            ('scene.html', True, ['scene.html'])

            ```

    See Also:
        digitalearth.three_d.Scene3D.orbit: a compact GIF/MP4 fly-through, the better choice for a heavy
            scene.
        save: routes here automatically for a ``*.html`` destination.
    """
    # pyvista >=0.49 moved trame support out into the separate `trame-pyvista` package: the export now lives
    # on a registered `trame` plotter component and `Plotter.export_html` is deprecated. This is a capability
    # switch, not a version one — 0.48 ships the same component registry, so a 0.48 user who installs
    # trame-pyvista takes the component branch too. Falling back (rather than raising here) hands the
    # not-installed case to pyvista's own actionable ImportError. The VTK-build check runs before either
    # branch: 0.49 makes it inside the deprecated Plotter.export_html we no longer call, and 0.48 makes
    # it nowhere at all, so doing it here is what guards both versions rather than neither.
    destination = str(Path(path).with_suffix(HTML_SUFFIX))
    _require_one_vtk_build()
    component = getattr(self.plotter, "trame", None)
    if component is None:
        self.plotter.export_html(destination)
    else:
        component.export_html(destination)
    return destination

show(**kwargs) #

Display the scene interactively (or render a frame off-screen).

Parameters:

Name Type Description Default
**kwargs Any

Forwarded to :meth:pyvista.Plotter.show.

{}

Returns:

Name Type Description
Whatever Any

meth:pyvista.Plotter.show returns.

Examples:

  • Off-screen (as in CI, or under :data:pyvista.OFF_SCREEN) it renders a frame and returns without opening a window. What comes back is pyvista's own return value, which its return_cpos theme setting decides — do not rely on it:
    >>> import pyvista as pv
    >>> from digitalearth.three_d.core.base import Scene3DBase
    >>> scene = Scene3DBase(off_screen=True)
    >>> _ = scene.add_mesh(pv.Sphere())
    >>> _ = scene.show()
    >>> scene.close()
    
  • Keyword arguments reach :meth:pyvista.Plotter.show, so the camera can be framed on the way in:
    >>> import pyvista as pv
    >>> from digitalearth.three_d.core.base import Scene3DBase
    >>> scene = Scene3DBase(off_screen=True)
    >>> _ = scene.add_mesh(pv.Cube())
    >>> _ = scene.show(cpos="xy")
    >>> scene.close()
    
See Also

screenshot: returns the rendered frame as an array instead of displaying it.

Source code in src/digitalearth/three_d/core/base.py
def show(self, **kwargs: Any) -> Any:
    """Display the scene interactively (or render a frame off-screen).

    Args:
        **kwargs: Forwarded to :meth:`pyvista.Plotter.show`.

    Returns:
        Whatever :meth:`pyvista.Plotter.show` returns.

    Examples:
        - Off-screen (as in CI, or under :data:`pyvista.OFF_SCREEN`) it renders a frame and returns without
          opening a window. What comes back is pyvista's own return value, which its ``return_cpos``
          theme setting decides — do not rely on it:
            ```python
            >>> import pyvista as pv
            >>> from digitalearth.three_d.core.base import Scene3DBase
            >>> scene = Scene3DBase(off_screen=True)
            >>> _ = scene.add_mesh(pv.Sphere())
            >>> _ = scene.show()
            >>> scene.close()

            ```
        - Keyword arguments reach :meth:`pyvista.Plotter.show`, so the camera can be framed on the way in:
            ```python
            >>> import pyvista as pv
            >>> from digitalearth.three_d.core.base import Scene3DBase
            >>> scene = Scene3DBase(off_screen=True)
            >>> _ = scene.add_mesh(pv.Cube())
            >>> _ = scene.show(cpos="xy")
            >>> scene.close()

            ```

    See Also:
        screenshot: returns the rendered frame as an array instead of displaying it.
    """
    self._apply_camera()
    return self.plotter.show(**kwargs)

close() #

Close the wrapped plotter and free its render window.

Closing twice is harmless, so a scene can be closed explicitly inside a with block that will close it again on exit. A scene that never drew has no render window, and closing it opens none.

Examples:

  • Free the render window when the scene is finished with:
    >>> import pyvista as pv
    >>> from digitalearth.three_d.core.base import Scene3DBase
    >>> scene = Scene3DBase(off_screen=True)
    >>> _ = scene.add_mesh(pv.Sphere())
    >>> scene.close()
    >>> len(scene.layers)
    1
    
  • A second close is a no-op, not an error:
    >>> from digitalearth.three_d.core.base import Scene3DBase
    >>> scene = Scene3DBase(off_screen=True)
    >>> scene.close()
    >>> scene.close()
    
See Also

exit: calls this on the way out of a with block.

Source code in src/digitalearth/three_d/core/base.py
def close(self) -> None:
    """Close the wrapped plotter and free its render window.

    Closing twice is harmless, so a scene can be closed explicitly inside a ``with`` block that will close
    it again on exit. A scene that never drew has no render window, and closing it opens none.

    Examples:
        - Free the render window when the scene is finished with:
            ```python
            >>> import pyvista as pv
            >>> from digitalearth.three_d.core.base import Scene3DBase
            >>> scene = Scene3DBase(off_screen=True)
            >>> _ = scene.add_mesh(pv.Sphere())
            >>> scene.close()
            >>> len(scene.layers)
            1

            ```
        - A second close is a no-op, not an error:
            ```python
            >>> from digitalearth.three_d.core.base import Scene3DBase
            >>> scene = Scene3DBase(off_screen=True)
            >>> scene.close()
            >>> scene.close()

            ```

    See Also:
        __exit__: calls this on the way out of a ``with`` block.
    """
    # A scene that never drew has no render window to free, and must not open one in order to close it.
    if self._plotter is not None:
        self._plotter.close()
    # And the data goes with it. The registry holds strong references, so a session that builds scenes
    # keeps every dataset they drew until something says otherwise — and this is the caller saying so
    # (review M1/M2). A captured `figure_spec` cannot resolve an `object:` source afterwards, which is
    # what "closed" means for a figure whose data lived only in this process.
    forget_namespace(self._objects_ns)