15 · 3-D visualization with PyVista¶
Digital-Earth's true-3D tier renders pyramids data as interactive 3-D scenes through Scene3D (a thin host over a pyvista.Plotter). Every plot is built from pyramids-sourced NumPy + geometry — no xarray/rasterio; pyramids owns all GIS/CRS.
This notebook renders each new plot type off-screen (so it runs headless in CI) and shows the resulting frame inline. The tier needs the optional 3d extra (pip install 'digitalearth[3d]' → pyvista, trame, geovista, imageio).
Setup. Render headless, locate the bundled sample data, and define a small helper that screenshots a scene and shows it inline (asserting the frame is not blank).
%matplotlib inline
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
import pyvista as pv
pv.OFF_SCREEN = True # headless: scenes render to an image, no interactive window
from pyramids.dataset import Dataset
from digitalearth.base.sources import get_source
from digitalearth.three_d import Scene3D
ROOT = Path.cwd()
while not (ROOT / 'examples' / 'data' / 'LisbonElevation.tif').exists() and ROOT != ROOT.parent:
ROOT = ROOT.parent
DATA = ROOT / 'examples' / 'data'
def show(scene, title=''):
"""Screenshot a Scene3D off-screen and show it inline (fails if the scene area is blank).
A bare ``img.any()`` check is too weak — a lone colour bar or a degenerate "needle" render on a plain
background still passes it. Instead we measure how much of the *scene area* (the frame minus the colour-bar
strip along the bottom) actually differs from the background, and fail if almost nothing does.
"""
img = scene.screenshot()
bg = img[0, 0].astype(int)
scene_area = img[: int(img.shape[0] * 0.8)] # drop the bottom strip where the colour bar lives
content = (np.abs(scene_area.astype(int) - bg).sum(-1) > 30).mean()
assert content > 0.01, f'render looks blank: only {content:.1%} of the scene area differs from the background'
plt.figure(figsize=(6, 4)); plt.imshow(img); plt.axis('off')
if title:
plt.title(title)
plt.show()
Terrain — a DEM as 3-D relief¶
Scene3D.terrain warps a raster by its elevation into a StructuredGrid. PyVista adds a scalar bar automatically.
dem = Dataset.read_file(str(DATA / 'LisbonElevation.tif'))
scene = Scene3D(off_screen=True)
scene.terrain(dem, z_exaggeration=8.0, cmap='terrain')
scene.plotter.add_axes()
show(scene, 'Lisbon DEM — 3-D terrain')
scene.close()
Point cloud — scattered points with eye-dome lighting¶
Scene3D.point_cloud renders an (N, 3) table (here the DEM sampled to xyz) as depth-cued points coloured by a scalar.
# The DEM's x/y are degrees but its elevation is metres; left as-is the cloud is a ~100,000:1 vertical
# needle. Scale z into degree-equivalent units (with an x8 exaggeration) so it reads as 3-D relief — the same
# convention Scene3D.terrain applies internally for geographic rasters. Colour stays the true elevation (metres).
arr = dem.read_array()[::4, ::4]
xx, yy = np.meshgrid(dem.x[::4], dem.y[::4])
finite = np.isfinite(arr.ravel())
elevation = arr.ravel()[finite]
zz = elevation / 111_320.0 * 8.0
pts = np.column_stack([xx.ravel()[finite], yy.ravel()[finite], zz])
scene = Scene3D(off_screen=True)
scene.point_cloud(pts, values=elevation, size=3.0, cmap='viridis')
show(scene, 'DEM as a coloured point cloud (eye-dome lighting)')
scene.close()
Volume & isosurfaces — a 3-D scalar field¶
Scene3D.volume ray-casts a 3-D NumPy cube (level, lat, lon); Scene3D.isosurface extracts shells of constant value.
axis = np.linspace(-3, 3, 28)
X, Y, Z = np.meshgrid(axis, axis, axis, indexing='ij')
cube = np.exp(-(X**2 + Y**2 + Z**2)) + 0.5 * np.exp(-((X - 1.5)**2 + (Y + 1.0)**2 + Z**2))
scene = Scene3D(off_screen=True)
scene.plotter.set_background('#101018') # ray-cast volumes read far better against a dark background
scene.volume(cube, cmap='viridis', opacity='sigmoid')
show(scene, 'Volumetric field (ray-cast)')
scene.close()
scene = Scene3D(off_screen=True)
# opacity<1 so the nested shells show through one another — the outer 0.2 shell maps to magma's near-black
# low end, so left opaque it hides the colourful inner shells and the whole thing reads as a solid black blob.
scene.isosurface(cube, isosurfaces=[0.2, 0.5, 0.8], cmap='magma', opacity=0.5)
scene.plotter.add_axes()
show(scene, 'Isosurfaces (shells of constant value)')
scene.close()
Vectors & extruded polygons¶
Scene3D.vectors draws a (u, v, w) field as arrow glyphs; Scene3D.extruded_polygons turns polygon footprints into 3-D prisms (height & colour by an attribute).
axis = np.linspace(-2, 2, 12)
X, Y = np.meshgrid(axis, axis)
anchors = np.column_stack([X.ravel(), Y.ravel(), np.zeros(X.size)])
field = np.column_stack([-Y.ravel(), X.ravel(), np.zeros(X.size)]) # rotational (u, v, w)
scene = Scene3D(off_screen=True)
scene.vectors(anchors, field, factor=0.3, cmap='coolwarm')
show(scene, '3-D vector field (arrow glyphs)')
scene.close()
import geopandas as gpd
from shapely.geometry import Polygon
squares = gpd.GeoDataFrame(
{'pop': [10.0, 25.0, 40.0, 15.0]},
geometry=[
Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]), Polygon([(2, 0), (3, 0), (3, 1), (2, 1)]),
Polygon([(0, 2), (1, 2), (1, 3), (0, 3)]), Polygon([(2, 2), (3, 2), (3, 3), (2, 3)]),
],
)
# Scale the extrusion height to the ~1-unit footprint so the prisms read as blocks, not skinny poles;
# still colour by the raw 'pop' attribute.
squares['height'] = squares['pop'] / 15.0
scene = Scene3D(off_screen=True)
scene.extruded_polygons(squares, height='height', column='pop', cmap='plasma')
scene.plotter.add_axes()
show(scene, 'Extruded polygons — height & colour by attribute')
scene.close()
Globe — a global field on a textured sphere¶
Scene3D.globe drapes a lon/lat field onto a WGS84 sphere (via the optional geovista) with Natural-Earth coastlines. The field must be in lon/lat — reproject upstream in pyramids (dataset.to_crs(4326)) for projected rasters.
lon = np.linspace(-180, 180, 73)
lat = np.linspace(-90, 90, 37)
global_field = np.add.outer(np.cos(np.deg2rad(lat)), 0.3 * np.sin(np.deg2rad(3 * lon)))
scene = Scene3D(off_screen=True)
scene.globe(get_source(global_field, x=lon, y=lat), cmap='coolwarm', coastlines=True)
show(scene, 'Global field on a textured sphere + coastlines')
scene.close()
Animation — an orbit fly-through¶
Scene3D.orbit sweeps the camera around the scene and writes a GIF/MP4. Here we orbit the Lisbon terrain and show the animated GIF inline.
import os, tempfile
from IPython.display import Image as IPyImage, display
scene = Scene3D(off_screen=True)
scene.terrain(dem, z_exaggeration=8.0, cmap='terrain')
gif = str(Path(tempfile.mkdtemp()) / 'lisbon_orbit.gif') # temp dir: no repo artifact
scene.orbit(gif, n_frames=12, fps=12)
scene.close()
print('orbit GIF bytes:', os.path.getsize(gif))
display(IPyImage(filename=gif))
orbit GIF bytes: 249607
<IPython.core.display.Image object>