5 - Temporal layers and animation¶
A stack of rasters becomes a time cube you can scrub, play and export. timecube builds a slider-driven
layer from a DatasetCollection; frames generalises that to any sequence of elements (a moving vector
layer, say); play wraps either in a Panel player; and save_animation writes a GIF/MP4 or a scrubber HTML.
Setup and data - twelve months of global mean temperature as a DatasetCollection.
import warnings
warnings.filterwarnings("ignore") # deliberately silence all warnings to keep the rendered docs clean
import io
from pathlib import Path
import holoviews as hv
import matplotlib.pyplot as plt
from IPython.display import Image
hv.extension("bokeh", "matplotlib") # Bokeh = interactive (the default); matplotlib only for barbs / projection
# This notebook lives in docs/examples/interactive/guide/, so the bundled sample data at the repo-root
# examples/data/ is four levels up. The kernel's working directory is always the notebook's own folder
# (true for nbval, nbconvert and JupyterLab alike), so one clean relative path is all that is needed.
DATA = Path("../../../../examples/data")
from digitalearth.interactive import InteractiveMap
from pyramids.dataset import Dataset
def show(m, static=False):
"""Return the **live, interactive Bokeh map** - pan, zoom, hover, and the toolbar are all real.
Run the notebook (Run All / Shift-Enter), or open it in a trusted viewer, to see the maps draw; a saved
.ipynb only shows them once a kernel executes their JavaScript. A few layers have no Bokeh glyph
(``projection``, ``streamlines``, wind ``barbs``) and are drawn by matplotlib; for those pass
``static=True`` (projected maps switch automatically) to embed a PNG instead.
"""
if static or getattr(m, "_projection", None) is not None:
fig = hv.render(m.render(), backend="matplotlib")
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=110, bbox_inches="tight")
plt.close(fig)
return Image(data=buf.getvalue())
return m.render()
import numpy as np
from pyramids.dataset.collection import DatasetCollection
files = [str(DATA / "global" / f"ncep_tavg_{month:02d}.tif") for month in range(1, 13)]
cube = DatasetCollection.from_files(files)
LABELS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
_all = np.concatenate([Dataset.read_file(f).read_array(band=0).ravel() for f in files])
lo, hi = float(np.nanpercentile(_all, 1)), float(np.nanpercentile(_all, 99))
print("time cube:", len(files), "months | value range", round(lo), "..", round(hi))
time cube: 12 months | value range -58 .. 30
timecube - a scrub-able raster stack¶
timecube draws the stack as one layer with a time selector; drag the slider (live kernel) to step months.
A frozen clim keeps the colour scale constant across months so they are comparable.
m = InteractiveMap(crs=4326, title="global mean temperature by month")
m.timecube(cube, labels=LABELS, cmap="RdBu_r", clim=(lo, hi))
show(m)
play - a Panel player¶
play returns a Panel layout with an auto-advancing player bound to the cube's time dimension (it animates
live in a running kernel; the map itself shows below).
m = InteractiveMap(crs=4326, title="temperature animation")
m.timecube(cube, labels=LABELS, cmap="RdBu_r", clim=(lo, hi))
player = m.play(fps=4) # a Panel player over the cube (live only)
print("player:", type(player).__name__) # drag / press play in a running kernel to animate
show(m)
player: Column
save_animation - export a GIF / MP4 / scrubber HTML¶
The suffix picks the writer: .gif / .mp4 render via matplotlib (MP4 needs ffmpeg), .html writes a
client-side scrubber that plays offline with no server.
import tempfile
from pathlib import Path as _Path
m = InteractiveMap(crs=4326)
m.timecube(cube, labels=LABELS, cmap="RdBu_r", clim=(lo, hi))
out = m.save_animation(str(_Path(tempfile.mkdtemp()) / "temperature.gif"), fps=4)
print("wrote", _Path(out).name, "-", _Path(out).stat().st_size, "bytes")
wrote temperature.gif - 157590 bytes
frames - animate any sequence of elements¶
frames registers an arbitrary {key: element} mapping (or a sequence) as one animatable layer, so a
time-varying vector layer animates exactly like a raster cube - which timecube alone cannot do.
import holoviews as hv
moving = {step: hv.Points([(step, 0.5 * step)]) for step in range(6)}
m = InteractiveMap(title="a moving point (frames)")
m.frames(moving, dimension="step")
player = m.play(fps=4) # the same player drives a frames() layer (live only)
print("player:", type(player).__name__)
show(m)
player: Column