7 · Time cubes & projections¶
timecube turns a DatasetCollection into a map with a time slider; play adds an animation player
and save_animation writes a GIF. projection re-renders the map in a non-Mercator projection and
graticule adds lon/lat grid lines. We use the 12-month WorldClim temperature stack.
Setup — backends and the 12 monthly global-temperature rasters as a DatasetCollection.
import warnings
warnings.filterwarnings("ignore") # hide backend-mismatch style warnings in the docs
from pathlib import Path
# Resolve the repo root so the bundled sample data is found whether this runs from
# docs/examples/interactive/ (mkdocs) or the repository root.
ROOT = Path.cwd()
while not (ROOT / "examples" / "data" / "LisbonElevation.tif").exists() and ROOT != ROOT.parent:
ROOT = ROOT.parent
DATA = ROOT / "examples" / "data"
import io
from IPython.display import Image
import matplotlib.pyplot as plt
import holoviews as hv
hv.extension("bokeh", "matplotlib") # Bokeh = interactive; matplotlib = static (projection/barbs)
def show(m, static=False, dpi=96):
"""Display the map — **interactive Bokeh** by default (pan / zoom / hover).
RUN THIS NOTEBOOK (Run All / Shift-Enter) to see the live interactive maps: a saved .ipynb only
shows interactive plots once the viewer executes their JavaScript (a running kernel, or a trusted
notebook). Pass ``static=True`` (used for the matplotlib-only layers — projection, streamlines,
wind barbs, which have no Bokeh glyph) to render a static 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=dpi, bbox_inches="tight")
plt.close(fig)
return Image(data=buf.getvalue())
return m.render() # interactive Bokeh object
from pyramids.dataset import Dataset, GeoReference
from pyramids.dataset.collection import DatasetCollection
from digitalearth.interactive import InteractiveMap
LABELS = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
# The 12-month WorldClim stack lives in the gitignored examples/data/global/; `cube` is None when the sample
# is absent (CI / a fresh clone), in which case every cell below skips with a note.
_tavg = DATA / "global" / "wc2.1_10m_tavg_01.tif"
months = [str(DATA / "global" / f"wc2.1_10m_tavg_{m:02d}.tif") for m in range(1, 13)]
cube = DatasetCollection.from_files(months) if _tavg.exists() else None
timecube — a time slider¶
In the live map a time slider steps through the 12 months with a shared colour range. The static image below shows the first frame (January).
if cube is not None:
m = InteractiveMap(crs=4326, title="monthly mean temperature")
m.timecube(cube, labels=LABELS, cmap="inferno")
display(show(m))
else:
print("skipped — the WorldClim sample (examples/data/global/) is not bundled with the repo")
skipped — the WorldClim sample (examples/data/global/) is not bundled with the repo
play — an animation player¶
play returns a Panel layout with a player widget (▶) over the time cube. It is interactive-only; the static image shows the underlying map.
if cube is not None:
m = InteractiveMap(crs=4326, title="temperature animation")
m.timecube(cube, labels=LABELS, cmap="inferno")
player = m.play(fps=4) # a Panel player over the cube (live only)
display(show(m))
else:
print("skipped — the WorldClim sample (examples/data/global/) is not bundled with the repo")
skipped — the WorldClim sample (examples/data/global/) is not bundled with the repo
save_animation — write a GIF¶
Render the cube to a GIF on disk (one frame per member). We write to a temporary folder so the docs tree stays clean.
import tempfile
if cube is not None:
m = InteractiveMap(crs=4326)
m.timecube(cube, labels=LABELS, cmap="inferno")
out = m.save_animation(str(Path(tempfile.mkdtemp()) / "temperature.gif"), fps=4)
print("wrote", Path(out).name, "—", Path(out).stat().st_size, "bytes")
else:
print("skipped — the WorldClim sample (examples/data/global/) is not bundled with the repo")
skipped — the WorldClim sample (examples/data/global/) is not bundled with the repo
projection + graticule — non-Mercator frame¶
projection(name) requests a non-Mercator coordinate reference (Robinson, Orthographic, Mollweide, …) and graticule() adds a lon/lat grid; both render through the matplotlib backend (GeoViews + cartopy under the hood). Here the global July mean temperature with a graticule. For a true rotating globe, run the projected map in a live Bokeh/Matplotlib session.
import numpy as np
_tavg7 = DATA / "global" / "wc2.1_10m_tavg_07.tif"
if _tavg7.exists():
raw = Dataset.read_file(str(_tavg7))
a = np.where(raw.read_array(band=0).astype("float32") < -1e30, np.nan, raw.read_array(band=0))
temp = Dataset.from_array(
arr=a.astype("float32"),
geo_ref=GeoReference(geo=raw.geotransform, epsg=raw.epsg),
no_data_value=np.nan,
)
m = InteractiveMap(crs=4326, title="July mean temperature + graticule")
m.field(temp, cmap="inferno").projection("Robinson").graticule()
display(show(m))
else:
print("skipped — the WorldClim sample (examples/data/global/) is not bundled with the repo")
skipped — the WorldClim sample (examples/data/global/) is not bundled with the repo