Sample script for interactive plotting of sonde variables (Plotly)¶
Plot vertical profiles and flight trajectories of one or more raw data directories with Plotly. All data are embedded in the figure, so it can be operated in an HTML page without Python (e.g. the documentation or a saved HTML file).
- Variables: switch the variable of each panel with the dropdown above it.
- Vertical axis: switch between height and pressure with the dropdown on the left.
- Profiles: click a legend entry to show/hide it, double-click to show only it. Show all / Hide all buttons are also available.
The profiles in the figure can be limited by the launch time (
LAUNCH_START,LAUNCH_END). - Range: drag to zoom, double-click to reset. The horizontal axes cannot be zoomed out beyond the range of each variable. Values are shown on hover.
- Trajectories: flight trajectories on a 2D map (drag to pan, scroll to zoom, change the background map with the dropdown) and in 3D with terrain (drag to rotate, scroll to zoom).
- Legend: the Legend on/off button of each figure shows/hides the legend.
Additional dependencies: numpy, plotly, pillow.
import base64
from bsod2 import Sondeset
import io
import json
import numpy as np
import pandas as pd
from pathlib import Path
from PIL import Image
import plotly.graph_objects as go
import plotly.io as pio
from plotly.subplots import make_subplots
import urllib.request
# show the figure in Jupyter and in HTML converted from the notebook
pio.renderers.default = "plotly_mimetype+notebook_connected"
Settings¶
Give one or more directories containing raw files (F*S*.CSV). Raw files themselves can be given as well.
An absolute path is the safest, since a relative path depends on the directory where Jupyter runs.
Only the profiles launched between LAUNCH_START and LAUNCH_END are plotted.
Give them in the same time as the launch time of the raw files (listed in the next cell), e.g. "2024-06-18 09:00".
None means no limit.
All the data are embedded in the figure, so the profiles are thinned to at most MAX_POINTS points
to keep the file small. Increase it for finer profiles.
RAW_DATA_DIRS = [
Path("Seisuimaru2407/raw_data"),
]
LAUNCH_START = None # e.g. "2024-06-18 09:00". None for no limit
LAUNCH_END = None # e.g. "2024-06-18 13:00". None for no limit
PANELS = ["t", "rh", "ws", "wd"] # initial variable of each panel (keys of VARIABLES)
VAXIS = "z" # initial vertical axis: "z" (height) or "p" (pressure)
ASCENDING_ONLY = True # True to remove descending records
MAX_POINTS = 400 # maximum number of points per profile
HTML_PATH = Path("interactive_profile_plotly.html") # HTML file of all the figures. None not to save it
Read observational data and perform quality control.¶
A relative path is searched from the current directory, its parents, and their sample directories,
so the sample data are found even if Jupyter is started outside the sample directory.
Each directory (or file) is read with Sondeset, and the profiles are combined in order of launch time.
def find_path(path):
path = Path(path).expanduser()
if path.is_absolute():
candidates = [path]
else:
ups = [Path(*[".."] * n) for n in range(len(Path.cwd().parents) + 1)] # ., .., ../.., ...
candidates = [up / sub / path for up in ups for sub in ("", "sample")]
for candidate in candidates:
if candidate.exists():
return candidate
raise FileNotFoundError(
f"{path} is not found from the current directory ({Path.cwd()}). "
"Set RAW_DATA_DIRS to the absolute path of the raw data directory."
)
sondes = {}
for path in RAW_DATA_DIRS:
path = find_path(path)
print(f"read {path}")
for sonde in Sondeset(path).sonde:
sondes[(sonde.sonde_no, sonde.launch_time)] = sonde # a profile given twice is used once
sondes = sorted(sondes.values(), key=lambda s: s.launch_time)
# select the profiles by the launch time
start = None if LAUNCH_START is None else pd.Timestamp(LAUNCH_START)
end = None if LAUNCH_END is None else pd.Timestamp(LAUNCH_END)
def in_launch_range(sonde):
return (start is None or sonde.launch_time >= start) and (end is None or sonde.launch_time <= end)
print(f"N={len(sondes)} (* : plotted)")
for s in sondes:
print(f"{'*' if in_launch_range(s) else ' '} {s.sonde_no} {s.launch_time:%Y-%m-%d %H:%M} ({len(s)} records)")
sondes = [s for s in sondes if in_launch_range(s)]
if not sondes:
raise ValueError(f"No profile was launched between {LAUNCH_START} and {LAUNCH_END}.")
read Seisuimaru2407/raw_data
N=8 (* : plotted) * 1101771 2024-06-18 06:01 (4174 records) * 1101323 2024-06-18 08:31 (4585 records) * 1101386 2024-06-18 09:31 (5002 records) * 1101322 2024-06-18 10:30 (1467 records) * 1101327 2024-06-18 11:47 (4732 records) * 1101772 2024-06-18 12:30 (3809 records) * 1101388 2024-06-18 13:29 (2471 records) * 1101326 2024-06-18 14:30 (3424 records)
Definitions of plotted variables¶
Each entry has a short name shown in the dropdowns, a label, a function returning the values of a Sonde,
and optionally the axis range. The horizontal axis cannot be zoomed out beyond range
(or beyond the range of the plotted data if range is not given).
Add an entry to make another variable selectable.
def elapsed_min(sonde):
# elapsed time from the launch [min]
return ((sonde.time - sonde.launch_time).dt.total_seconds() / 60).to_numpy()
# variables selectable for the horizontal axes
VARIABLES = {
"t": dict(short="Temp", label="Temperature [°C]", get=lambda s: s.t.m),
"td": dict(short="Dewpt", label="Dew point temperature [°C]", get=lambda s: s.td.m),
"rh": dict(short="RH", label="Relative humidity [%]", get=lambda s: s.rh.m, range=(0, 100)),
"ws": dict(short="WS", label="Wind speed [m/s]", get=lambda s: s.ws.m),
"wd": dict(short="WD", label="Wind direction", get=lambda s: s.wd.m, range=(0, 360), circular=True),
"u": dict(short="u", label="u [m/s]", get=lambda s: s.u.m),
"v": dict(short="v", label="v [m/s]", get=lambda s: s.v.m),
"p": dict(short="Pres", label="Pressure [hPa]", get=lambda s: s.p.m),
"z": dict(short="Height", label="Height [m]", get=lambda s: s.z.m),
"x": dict(short="x", label="x-displacement [km]", get=lambda s: s.x.to("km").m),
"y": dict(short="y", label="y-displacement [km]", get=lambda s: s.y.to("km").m),
"lat": dict(short="Lat", label="Latitude [°N]", get=lambda s: s.lat.m),
"lon": dict(short="Lon", label="Longitude [°E]", get=lambda s: s.lon.m),
"elapsed": dict(short="Time", label="Elapsed time [min]", get=elapsed_min),
}
# vertical axes (height or pressure)
VERTICAL_AXES = {
"z": dict(short="y: Height", label="Height [m]", get=lambda s: s.z.m),
"p": dict(short="y: Pres", label="Pressure [hPa]", get=lambda s: s.p.m, reversed=True),
}
Prepare the data¶
Remove the descending records, thin the profiles, and compute all the variables in advance.
def ascending_mask(sonde):
# True for the records whose height is the maximum so far
h = sonde.df["Height"]
return (h.cummax() == h).to_numpy()
def thinned_index(sonde):
idx = np.flatnonzero(ascending_mask(sonde)) if ASCENDING_ONLY else np.arange(len(sonde))
step = max(1, int(np.ceil(idx.size / MAX_POINTS)))
return idx[::step]
def get_values(sonde, spec, idx):
# e.g. dew point is undefined for RH = 0 (log of zero); such values become NaN
with np.errstate(divide="ignore", invalid="ignore"):
values = np.asarray(spec["get"](sonde), dtype=float)[idx]
values[~np.isfinite(values)] = np.nan
if spec.get("circular"):
# break the line at the discontinuities (e.g. 359 deg -> 0 deg)
jump = np.flatnonzero(np.abs(np.diff(values)) > 180) + 1
values[jump] = np.nan
return values.astype(np.float32)
def b64(values):
# base64-encoded typed array decoded by plotly.js, to keep the embedded data small
arr = np.ascontiguousarray(values, dtype="<f4")
return {"dtype": "f4", "bdata": base64.b64encode(arr.tobytes()).decode()}
index = [thinned_index(s) for s in sondes]
# color and name of each profile, shared by all the figures
palette = pio.templates["plotly"].layout.colorway
COLORS = [palette[i % len(palette)] for i in range(len(sondes))]
NAMES = [f"{s.sonde_no} ({s.launch_time:%m/%d %H:%M})" for s in sondes]
X = {k: [get_values(s, spec, i) for s, i in zip(sondes, index)] for k, spec in VARIABLES.items()}
Y = {k: [get_values(s, spec, i) for s, i in zip(sondes, index)] for k, spec in VERTICAL_AXES.items()}
Plot¶
def legend_toggle(**position):
"""button to show/hide the legend (first click hides it)"""
return dict(
type="buttons",
buttons=[dict(label="Legend on/off", method="relayout",
args=[{"showlegend": False}], args2=[{"showlegend": True}])],
active=-1, showactive=False, xanchor="left", yanchor="bottom", **position,
)
def x_limits(key):
"""range beyond which a horizontal axis showing VARIABLES[key] cannot be zoomed out"""
spec = VARIABLES[key]
if "range" in spec:
return [float(v) for v in spec["range"]]
values = np.concatenate(X[key])
values = values[np.isfinite(values)]
if values.size == 0:
return [None, None]
lo, hi = float(values.min()), float(values.max())
pad = 0.05 * (hi - lo) if hi > lo else 1.0
return [lo - pad, hi + pad]
def xaxis_layout(axis_name, key):
"""layout properties of a horizontal axis showing VARIABLES[key]"""
spec = VARIABLES[key]
lo, hi = x_limits(key)
layout = {
f"{axis_name}.title.text": spec["label"],
f"{axis_name}.range": None, # clear the previous range
f"{axis_name}.autorange": True,
# show the whole `range` and do not zoom out beyond the limits
f"{axis_name}.autorangeoptions.include": list(spec["range"]) if "range" in spec else None,
f"{axis_name}.minallowed": lo,
f"{axis_name}.maxallowed": hi,
}
if key == "wd":
layout[f"{axis_name}.tickmode"] = "array"
layout[f"{axis_name}.tickvals"] = [0, 90, 180, 270, 360]
layout[f"{axis_name}.ticktext"] = ["N", "E", "S", "W", "N"]
else:
layout[f"{axis_name}.tickmode"] = "auto"
return layout
def yaxis_layout(npanel, vkey):
"""layout properties of the vertical axes showing VERTICAL_AXES[vkey]"""
spec = VERTICAL_AXES[vkey]
layout = {"yaxis.title.text": spec["label"]}
for k in range(npanel):
name = f"yaxis{k + 1 if k else ''}"
# clear the previous range, otherwise a reversed range stays reversed
layout[f"{name}.range"] = None
layout[f"{name}.autorange"] = "reversed" if spec.get("reversed") else True
return layout
def plot_profiles_plotly(sondes, panels, vaxis="z"):
nprof, npanel = len(sondes), len(panels)
fig = make_subplots(rows=1, cols=npanel, shared_yaxes=True, horizontal_spacing=0.03)
# traces: panel k, profile i -> trace index k * nprof + i
for k, key in enumerate(panels):
for i, sonde in enumerate(sondes):
fig.add_trace(
go.Scatter(
x=X[key][i],
y=Y[vaxis][i],
mode="lines",
line=dict(width=1, color=COLORS[i]),
name=NAMES[i],
legendgroup=sonde.sonde_no, # show/hide a profile in all panels together
showlegend=(k == 0),
hovertemplate="<b>%{fullData.name}</b><br>x: %{x:.4g}<br>y: %{y:.5g}<extra></extra>",
),
row=1,
col=k + 1,
)
menus = []
# dropdown of the variable of each panel
for k, key in enumerate(panels):
axis_name = f"xaxis{k + 1 if k else ''}"
traces = list(range(k * nprof, (k + 1) * nprof))
buttons = [
dict(
label=spec["short"],
method="update",
args=[{"x": [b64(x) for x in X[vkey]]}, xaxis_layout(axis_name, vkey), traces],
)
for vkey, spec in VARIABLES.items()
]
domain = fig.layout[axis_name].domain
menus.append(dict(
buttons=buttons, active=list(VARIABLES).index(key),
x=domain[0], xanchor="left", y=1.02, yanchor="bottom",
showactive=True, pad=dict(t=0, r=0, b=0, l=0),
))
# dropdown of the vertical axis
buttons = [
dict(
label=spec["short"],
method="update",
args=[{"y": [b64(Y[vkey][i]) for _ in range(npanel) for i in range(nprof)]}, yaxis_layout(npanel, vkey)],
)
for vkey, spec in VERTICAL_AXES.items()
]
menus.append(dict(
buttons=buttons, active=list(VERTICAL_AXES).index(vaxis),
x=0, xanchor="left", y=1.13, yanchor="bottom",
))
# buttons to show/hide all the profiles
menus.append(dict(
type="buttons", direction="right",
buttons=[
dict(label="Show all", method="restyle", args=[{"visible": True}]),
dict(label="Hide all", method="restyle", args=[{"visible": "legendonly"}]),
],
x=1, xanchor="right", y=1.13, yanchor="bottom",
))
# button to show/hide the legend (right of the vertical axis dropdown)
menus.append(legend_toggle(x=0, y=1.13, pad=dict(l=110)))
fig.update_layout(
updatemenus=menus,
height=720,
margin=dict(t=110, l=70, r=20, b=40),
legend=dict(title="Profiles", font=dict(size=11), orientation="h",
x=0, xanchor="left", y=-0.15, yanchor="top"),
hovermode="closest",
template="plotly_white",
)
for k, key in enumerate(panels):
fig.update_layout(xaxis_layout(f"xaxis{k + 1 if k else ''}", key))
fig.update_layout(yaxis_layout(npanel, vaxis))
return fig
fig_profile = plot_profiles_plotly(sondes, PANELS, VAXIS)
fig_profile.show()
Flight trajectories¶
The trajectories of the same profiles are plotted on a 2D map and in 3D with terrain. Click a legend entry to show/hide a profile. Height, pressure, temperature, relative humidity and wind speed are shown on hover.
HOVER = (
"<b>%{fullData.name}</b><br>"
"Height: %{customdata[0]:.0f} m<br>Pressure: %{customdata[1]:.1f} hPa<br>"
"Temperature: %{customdata[2]:.1f} °C<br>RH: %{customdata[3]:.0f} %<br>"
"Wind speed: %{customdata[4]:.1f} m/s<extra></extra>"
)
def hover_data(i):
return np.stack([X[k][i] for k in ("z", "p", "t", "rh", "ws")], axis=-1)
def finite_values(key):
values = np.concatenate(X[key])
return values[np.isfinite(values)]
lats, lons = finite_values("lat"), finite_values("lon")
LAT0, LON0 = float(lats.min() + lats.max()) / 2, float(lons.min() + lons.max()) / 2 # center of the trajectories
2D map¶
Drag to pan and scroll to zoom. The background map can be changed with the dropdown (the map tiles are loaded from the internet). Circles are the launch points.
The CARTO map styles are modified so that the boundary lines are drawn under the water, i.e. they are hidden over the sea. If the styles cannot be downloaded, the original styles are used.
USER_AGENT = {"User-Agent": "bsod2-sample-notebook"}
# CARTO map styles: name in plotly -> name of the style
CARTO_STYLES = {"carto-positron": "positron", "carto-voyager": "voyager", "carto-darkmatter": "dark-matter"}
def download(url):
req = urllib.request.Request(url, headers=USER_AGENT)
with urllib.request.urlopen(req, timeout=20) as res:
return res.read()
def map_style(name):
"""CARTO style whose boundary lines are hidden over the sea (the original style name if it fails)"""
url = f"https://basemaps.cartocdn.com/gl/{CARTO_STYLES[name]}-gl-style/style.json"
try:
style = json.loads(download(url))
except Exception as e:
print(f"The original {name} style is used: failed to download it ({e}).")
return name
# move the boundary layers under the first water fill layer
layers = style["layers"]
boundaries = [l for l in layers if l.get("source-layer") == "boundaries"]
others = [l for l in layers if l.get("source-layer") != "boundaries"]
i = next(k for k, l in enumerate(others) if l.get("source-layer") == "water" and l["type"] == "fill")
style["layers"] = others[:i] + boundaries + others[i:]
return style
def plot_trajectory_map(sondes, style="carto-positron"):
styles = {name: map_style(name) for name in CARTO_STYLES}
fig = go.Figure()
for i, sonde in enumerate(sondes):
lat, lon = X["lat"][i], X["lon"][i]
fig.add_trace(go.Scattermap(
lat=lat, lon=lon, mode="lines", line=dict(width=2, color=COLORS[i]),
name=NAMES[i], legendgroup=sonde.sonde_no,
customdata=hover_data(i), hovertemplate=HOVER,
))
valid = np.flatnonzero(np.isfinite(lat) & np.isfinite(lon))
if valid.size:
fig.add_trace(go.Scattermap(
lat=[lat[valid[0]]], lon=[lon[valid[0]]], mode="markers",
marker=dict(size=10, color=COLORS[i]),
name=NAMES[i], legendgroup=sonde.sonde_no, showlegend=False,
hovertemplate="<b>%{fullData.name}</b><br>launch point<extra></extra>",
))
# zoom level showing all the trajectories
extent = max(np.ptp(lats), np.ptp(lons) * np.cos(np.deg2rad(LAT0)), 0.01) * 1.3
zoom = float(np.clip(np.log2(360 * 600 / 512 / extent), 1, 14))
fig.update_layout(
map=dict(style=styles[style], center=dict(lat=LAT0, lon=LON0), zoom=zoom),
updatemenus=[
dict(
buttons=[dict(label=name, method="relayout", args=[{"map.style": s}]) for name, s in styles.items()],
active=list(styles).index(style), x=0, xanchor="left", y=1.0, yanchor="bottom",
),
legend_toggle(x=0, y=1.0, pad=dict(l=170)),
],
height=600,
margin=dict(t=40, l=10, r=10, b=10),
legend=dict(title="Profiles", font=dict(size=11)),
)
return fig
fig_map = plot_trajectory_map(sondes)
fig_map.show()
3D with terrain¶
Drag to rotate and scroll to zoom. The trajectories are drawn above the terrain,
which is colored by a map. The dotted lines are the projections of the trajectories on the ground.
The horizontal axes have the same scale in km; the vertical axis is exaggerated if the trajectories are flat.
The terrain can be exaggerated further with TERRAIN_EXAGGERATION.
When this cell is run, the elevation (Terrain Tiles, the sea is drawn at 0 m)
and the map (TILE_SOURCE) are downloaded as map tiles (internet access is needed), and embedded in the figure.
If the download fails, the trajectories are drawn on a flat map, or without the map.
The map tiles of TILE_SOURCES have no boundary lines over the sea. Follow the terms of use of the tile servers.
# map tile servers: (URL, attribution)
TILE_SOURCES = {
"esri-topo": ("https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}",
"Map tiles © Esri"),
"esri-street": ("https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}",
"Map tiles © Esri"),
"esri-satellite": ("https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
"Map tiles © Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community"),
}
TILE_SOURCE = "esri-topo" # key of TILE_SOURCES. None for no map
# elevation tiles (Terrarium format): elevation = R * 256 + G + B / 256 - 32768 [m]
DEM_URL = "https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png" # None for a flat map
DEM_ATTRIBUTION = "Elevation: Terrain Tiles (Mapzen, AWS Open Data)"
TERRAIN_EXAGGERATION = 1.0 # vertical exaggeration of the terrain
MAX_TILES = 36 # maximum number of downloaded tiles of each kind
MAP_PIXELS = 400 # maximum size [px] of the map embedded in the figure
MAP_COLORS = 128 # number of colors of the map (up to 256)
def tile_xy(lon, lat, zoom):
"""lon/lat -> fractional tile numbers (Web Mercator)"""
n = 2 ** zoom
return (lon + 180) / 360 * n, (1 - np.arcsinh(np.tan(np.deg2rad(lat))) / np.pi) / 2 * n
def tile_lonlat(tx, ty, zoom):
"""fractional tile numbers -> lon/lat"""
n = 2 ** zoom
return tx / n * 360 - 180, np.rad2deg(np.arctan(np.sinh(np.pi * (1 - 2 * ty / n))))
def map_grid(lon_min, lon_max, lat_min, lat_max):
"""zoom level, tiles, crop box and lon/lat of the pixel centers of the area"""
# the highest zoom level not much finer than the embedded map
for zoom in range(15, -1, -1):
(x0, y0), (x1, y1) = tile_xy(lon_min, lat_max, zoom), tile_xy(lon_max, lat_min, zoom)
tiles_x, tiles_y = range(int(x0), int(x1) + 1), range(int(y0), int(y1) + 1)
if len(tiles_x) * len(tiles_y) <= MAX_TILES and max(x1 - x0, y1 - y0) * 256 <= 1.5 * MAP_PIXELS:
break
box = (int((x0 - tiles_x[0]) * 256), int((y0 - tiles_y[0]) * 256),
int(np.ceil((x1 - tiles_x[0]) * 256)), int(np.ceil((y1 - tiles_y[0]) * 256)))
scale = min(1.0, MAP_PIXELS / max(box[2] - box[0], box[3] - box[1]))
size = (max(2, round((box[2] - box[0]) * scale)), max(2, round((box[3] - box[1]) * scale)))
px = box[0] + (np.arange(size[0]) + 0.5) * (box[2] - box[0]) / size[0]
py = box[1] + (np.arange(size[1]) + 0.5) * (box[3] - box[1]) / size[1]
lon, _ = tile_lonlat(tiles_x[0] + px / 256, 0, zoom)
_, lat = tile_lonlat(0, tiles_y[0] + py / 256, zoom)
return dict(zoom=zoom, tiles_x=tiles_x, tiles_y=tiles_y, box=box, size=size, lon=lon, lat=lat)
def fetch_tiles(url_template, grid, mode="RGB", *, resize=True):
"""download the tiles, and crop and resize the image to the grid"""
img = Image.new(mode, (256 * len(grid["tiles_x"]), 256 * len(grid["tiles_y"])))
for i, tx in enumerate(grid["tiles_x"]):
for j, ty in enumerate(grid["tiles_y"]):
url = url_template.format(z=grid["zoom"], x=tx, y=ty)
img.paste(Image.open(io.BytesIO(download(url))).convert(mode), (256 * i, 256 * j))
img = img.crop(grid["box"])
if resize:
img = img.resize(grid["size"], Image.LANCZOS if mode == "RGB" else Image.BILINEAR)
return img
def fetch_elevation(grid):
"""elevation [m] of the grid (Terrarium tiles). 0 over the sea"""
# Decode before resizing: interpolating the RGB bytes corrupts heights.
rgb = np.asarray(fetch_tiles(DEM_URL, grid, resize=False), dtype=np.float32)
elevation = rgb[..., 0] * 256 + rgb[..., 1] + rgb[..., 2] / 256 - 32768
elevation = np.asarray(Image.fromarray(elevation).resize(grid["size"], Image.BILINEAR))
return np.clip(elevation, 0, None)
def terrain_surface(grid, img, elevation):
"""Surface trace of the terrain colored by the map image"""
# an image cannot be given to a Surface directly, so each pixel is colored
# by its index in a reduced palette with a stepwise colorscale
img = img.quantize(colors=MAP_COLORS)
index = np.asarray(img, dtype=np.uint8)
rgb = np.array(img.getpalette()[: 3 * MAP_COLORS]).reshape(-1, 3)
n = len(rgb)
colorscale = []
for k, (r, g, b) in enumerate(rgb):
# index k (between k - 0.5 and k + 0.5) -> color k
colorscale += [[k / n, f"rgb({r},{g},{b})"], [(k + 1) / n, f"rgb({r},{g},{b})"]]
return go.Surface(
x=grid["lon"], y=grid["lat"], z=np.round(elevation * TERRAIN_EXAGGERATION).astype(np.int16),
surfacecolor=index, cmin=-0.5, cmax=n - 0.5, colorscale=colorscale,
showscale=False, hoverinfo="skip", showlegend=False,
lighting=dict(ambient=0.75, diffuse=0.45, specular=0, roughness=1, fresnel=0),
contours=dict(x=dict(highlight=False), y=dict(highlight=False), z=dict(highlight=False)),
)
def ground_height(lon, lat, grid, elevation):
"""height of the terrain under the points (nearest pixel)"""
ix = np.interp(lon, grid["lon"], np.arange(grid["lon"].size))
iy = np.interp(lat, grid["lat"][::-1], np.arange(grid["lat"].size)[::-1])
valid = np.isfinite(ix) & np.isfinite(iy)
height = np.zeros(lon.shape, dtype=np.float32)
height[valid] = elevation[np.round(iy[valid]).astype(int), np.round(ix[valid]).astype(int)]
height[~valid] = np.nan
return height * TERRAIN_EXAGGERATION
def plot_trajectory_3d(sondes):
# area of the map: the trajectories with margins
pad = max(np.ptp(lats), np.ptp(lons), 0.05) * 0.1
lon_min, lon_max = float(lons.min() - pad), float(lons.max() + pad)
lat_min, lat_max = float(lats.min() - pad), float(lats.max() + pad)
zmax = float(finite_values("z").max()) # [m]
fig = go.Figure()
grid = map_grid(lon_min, lon_max, lat_min, lat_max)
elevation = np.zeros(grid["size"][::-1], dtype=np.float32)
attribution = []
if DEM_URL is not None:
try:
elevation = fetch_elevation(grid)
attribution.append(DEM_ATTRIBUTION)
except Exception as e:
print(f"The terrain is not drawn: failed to download the elevation tiles ({e}).")
if TILE_SOURCE is not None:
try:
img = fetch_tiles(TILE_SOURCES[TILE_SOURCE][0], grid)
fig.add_trace(terrain_surface(grid, img, elevation))
attribution.insert(0, TILE_SOURCES[TILE_SOURCE][1])
except Exception as e:
print(f"The map is not drawn: failed to download the map tiles ({e}).")
for i, sonde in enumerate(sondes):
lat, lon, z = X["lat"][i], X["lon"][i], X["z"][i]
fig.add_trace(go.Scatter3d(
x=lon, y=lat, z=z, mode="lines", line=dict(width=4, color=COLORS[i]),
name=NAMES[i], legendgroup=sonde.sonde_no,
customdata=hover_data(i), hovertemplate=HOVER,
))
# projection on the ground (slightly above the terrain)
fig.add_trace(go.Scatter3d(
x=lon, y=lat, z=ground_height(lon, lat, grid, elevation) + 0.005 * zmax, mode="lines",
line=dict(width=3, color=COLORS[i], dash="dot"),
name=NAMES[i], legendgroup=sonde.sonde_no, showlegend=False, hoverinfo="skip",
))
# aspect ratio: the same scale for the horizontal axes
dx = (lon_max - lon_min) * 111.32 * np.cos(np.deg2rad(LAT0)) # [km]
dy = (lat_max - lat_min) * 110.57 # [km]
h = max(dx, dy)
aspect = dict(x=float(dx / h), y=float(dy / h), z=float(np.clip(zmax / 1000 / h, 0.4, 1.0)))
fig.update_layout(
scene=dict(
xaxis=dict(title="Longitude [°E]", range=[lon_min, lon_max]),
yaxis=dict(title="Latitude [°N]", range=[lat_min, lat_max]),
zaxis=dict(title="Height [m]", range=[0, zmax * 1.05]),
aspectmode="manual", aspectratio=aspect,
),
updatemenus=[legend_toggle(x=0, y=1.0)],
annotations=[dict(text=" / ".join(attribution), x=0, y=0, xref="paper", yref="paper",
xanchor="left", yanchor="bottom", showarrow=False, font=dict(size=10))]
if attribution else [],
height=650,
margin=dict(t=40, l=10, r=10, b=10),
legend=dict(title="Profiles", font=dict(size=11)),
)
return fig
fig_3d = plot_trajectory_3d(sondes)
fig_3d.show()
Save as HTML¶
All the figures are saved in one HTML file, which can be opened in a web browser without Python (plotly.js is loaded from the internet).
def save_html(figs, path):
divs = [f.to_html(full_html=False, include_plotlyjs="cdn" if i == 0 else False) for i, f in enumerate(figs)]
html = '<html><head><meta charset="utf-8"></head><body>\n' + "\n".join(divs) + "\n</body></html>"
Path(path).write_text(html, encoding="utf-8")
if HTML_PATH is not None:
save_html([fig_profile, fig_map, fig_3d], HTML_PATH)
print(f"saved {HTML_PATH}")
saved interactive_profile_plotly.html