Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat(plotly): add reactive waterfall selection support (#9045)

axssel549785ed8960
diff --git a/docs/api/plotting.md b/docs/api/plotting.md
index 6555fa3300..975c3c3b9c 100644
--- a/docs/api/plotting.md
+++ b/docs/api/plotting.md
@@ -106,7 +106,7 @@ alt.data_transformers.enable('marimo_csv')
marimo can render any Plotly plot, but [`mo.ui.plotly`][marimo.ui.plotly] only
supports reactive selections for scatter/scattergl plots, pure line charts, bar charts,
- histograms, heatmaps, treemaps, and sunburst charts. If you require other kinds of
+ histograms, waterfall charts, heatmaps, treemaps, and sunburst charts. If you require other kinds of
selection, please [file an issue](https://github.com/marimo-team/marimo/issues).
::: marimo.ui.plotly
diff --git a/examples/third_party/plotly/waterfall_chart.py b/examples/third_party/plotly/waterfall_chart.py
new file mode 100644
index 0000000000..10cc68910a
--- /dev/null
+++ b/examples/third_party/plotly/waterfall_chart.py
@@ -0,0 +1,248 @@
+# /// script
+# requires-python = ">=3.10"
+# dependencies = [
+# "marimo",
+# "pandas==2.3.3",
+# "plotly==6.5.1",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.20.2"
+app = marimo.App(width="medium")
+
+
+def _():
+ import marimo as mo
+ import pandas as pd
+ import plotly.graph_objects as go
+
+ return go, mo, pd
+
+
+def _(mo):
+ mo.md("""
+ # Reactive Plotly Waterfall Chart Selection
+
+ This example demonstrates reactive waterfall chart selections with `mo.ui.plotly`.
+
+ Waterfall charts (also called bridge charts) decompose a starting value into
+ its contributing increments, making it easy to trace how individual drivers
+ move a KPI from one level to another.
+
+ Each bar has a **measure** type:
+ - **`absolute`** — starts at zero and sets the running total
+ - **`relative`** — adds to (or subtracts from) the running total
+ - **`total`** — shows the current running total as a reference bar
+
+ Try:
+ - **Click** any bar to select it
+ - **Drag a box** over multiple bars to select a range
+ - Watch the detail panel and table update reactively
+ """)
+ return
+
+
+def _(go, mo):
+ mo.md("## Annual P&L Bridge")
+
+ fig_pl = go.Figure(
+ go.Waterfall(
+ name="P&L",
+ orientation="v",
+ measure=[
+ "absolute",
+ "relative",
+ "relative",
+ "relative",
+ "relative",
+ "total",
+ "relative",
+ "relative",
+ "total",
+ ],
+ x=[
+ "Revenue",
+ "COGS",
+ "Gross Profit",
+ "R&D",
+ "S&M",
+ "EBITDA",
+ "D&A",
+ "Tax",
+ "Net Income",
+ ],
+ y=[4_200, -1_500, 0, -420, -310, 0, -180, -240, 0],
+ connector={"line": {"color": "rgb(63, 63, 63)"}},
+ increasing={"marker": {"color": "#2a9d8f"}},
+ decreasing={"marker": {"color": "#e76f51"}},
+ totals={"marker": {"color": "#264653", "line": {"color": "#264653"}}},
+ hovertemplate=(
+ "<b>%{x}</b><br>"
+ "Value: $%{y:,.0f}K<br>"
+ "<extra></extra>"
+ ),
+ )
+ )
+ fig_pl.update_layout(
+ title="Annual P&L Bridge — click or box-select bars",
+ yaxis_title="USD (thousands)",
+ dragmode="select",
+ showlegend=False,
+ )
+
+ pl_plot = mo.ui.plotly(fig_pl)
+ pl_plot
+ return (pl_plot,)
+
+
+def _(mo, pl_plot):
+ _pts = pl_plot.value
+
+ if _pts:
+ _total = sum(
+ p["y"] for p in _pts
+ if isinstance(p.get("y"), (int, float)) and p.get("measure") != "total"
+ )
+ _names = ", ".join(p["x"] for p in _pts if p.get("x"))
+ _detail = (
+ f"**{len(_pts)} bar(s) selected:** {_names} \n"
+ f"Net relative contribution: **${_total:,.0f}K**"
+ )
+ else:
+ _detail = "Click or drag to select bars."
+
+ mo.md(f"""
+ ### Selection Detail
+
+ {_detail}
+
+ **Indices:** {pl_plot.indices}
+
+ **Raw value:** {pl_plot.value}
+ """)
+ return
+
+
+def _(go, mo):
+ mo.md("## Regional Sales Waterfall — Multi-Trace")
+
+ fig_regional = go.Figure()
+
+ traces = [
+ ("North America", [800, 120, -40, 0], "#2a9d8f"),
+ ("Europe", [600, 80, -55, 0], "#e9c46a"),
+ ("Asia-Pacific", [450, 95, -30, 0], "#e76f51"),
+ ]
+ measures = ["absolute", "relative", "relative", "total"]
+ x_labels = ["Baseline", "Growth", "Churn", "Net"]
+
+ for region, values, colour in traces:
+ fig_regional.add_trace(
+ go.Waterfall(
+ name=region,
+ measure=measures,
+ x=x_labels,
+ y=values,
+ offsetgroup=region,
+ increasing={"marker": {"color": colour}},
+ totals={"marker": {"color": colour}},
+ )
+ )
+
+ fig_regional.update_layout(
+ title="Regional Sales Bridge — select bars across traces",
+ yaxis_title="Revenue ($M)",
+ barmode="group",
+ dragmode="select",
+ )
+
+ regional_plot = mo.ui.plotly(fig_regional)
+ regional_plot
+ return (regional_plot,)
+
+
+def _(mo, pd, regional_plot):
+ _pts = regional_plot.value
+
+ if _pts:
+ _rows = pd.DataFrame(
+ [
+ {
+ "Stage": p.get("x"),
+ "Region": p.get("name"),
+ "Value ($M)": p.get("y"),
+ "Type": p.get("measure"),
+ }
+ for p in _pts
+ if p
+ ]
+ )
+ else:
+ _rows = pd.DataFrame(columns=["Stage", "Region", "Value ($M)", "Type"])
+
+ mo.vstack([
+ mo.md(f"**{len(_pts)} bar(s) selected** | Indices: {regional_plot.indices}"),
+ mo.ui.table(_rows),
+ ])
+ return
+
+
+def _(go, mo):
+ mo.md("## Horizontal Budget Waterfall")
+
+ fig_h = go.Figure(
+ go.Waterfall(
+ orientation="h",
+ measure=["absolute", "relative", "relative", "relative", "total"],
+ y=["Budget", "Savings", "Overspend", "Reserve", "Actual"],
+ x=[500, -80, 120, -30, 0],
+ connector={"mode": "between", "line": {"width": 1, "color": "rgb(180,180,180)"}},
+ increasing={"marker": {"color": "#e76f51"}},
+ decreasing={"marker": {"color": "#2a9d8f"}},
+ totals={"marker": {"color": "#457b9d"}},
+ hovertemplate="<b>%{y}</b><br>Amount: $%{x:,.0f}K<extra></extra>",
+ )
+ )
+ fig_h.update_layout(
+ title="Budget vs Actual — horizontal bridge",
+ xaxis_title="USD (thousands)",
+ dragmode="select",
+ showlegend=False,
+ )
+
+ h_plot = mo.ui.plotly(fig_h)
+ h_plot
+ return (h_plot,)
+
+
+def _(h_plot, mo):
+ _pts = h_plot.value
+
+ if _pts:
+ _names = [p.get("y") for p in _pts if p.get("y")]
+ _summary = f"Selected: **{', '.join(_names)}**"
+ else:
+ _summary = "Click or drag to select budget items."
+
+ mo.md(f"""
+ ### Horizontal Selection
+
+ {_summary}
+
+ **Indices:** {h_plot.indices}
+ """)
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/frontend/src/plugins/impl/plotly/__tests__/selection.test.ts b/frontend/src/plugins/impl/plotly/__tests__/selection.test.ts
index ea56ce0f09..b238d2d6a5 100644
--- a/frontend/src/plugins/impl/plotly/__tests__/selection.test.ts
+++ b/frontend/src/plugins/impl/plotly/__tests__/selection.test.ts
@@ -117,6 +117,14 @@ describe("shouldHandleClickSelection", () => {
expect(shouldHandleClickSelection([linePoint])).toBe(true);
});
+ it("accepts waterfall clicks", () => {
+ const waterfallPoint = createPlotDatum({
+ data: { type: "waterfall" },
+ });
+
+ expect(shouldHandleClickSelection([waterfallPoint])).toBe(true);
+ });
+
it("rejects non-line scatter marker clicks", () => {
const markerPoint = createPlotDatum({
data: { type: "scatter", mode: "markers" },
@@ -196,4 +204,18 @@ describe("extractPoints", () => {
expect(extractPoints([point])).toEqual([{ x: 1, y: 2, z: 3 }]);
});
+
+ it("returns x/y/pointIndex for waterfall clicks", () => {
+ const point = createPlotDatum({
+ x: "Revenue",
+ y: 400,
+ pointIndex: 1,
+ curveNumber: 0,
+ data: { type: "waterfall" },
+ });
+
+ expect(extractPoints([point])).toEqual([
+ { x: "Revenue", y: 400, pointIndex: 1, curveNumber: 0 },
+ ]);
+ });
});
diff --git a/frontend/src/plugins/impl/plotly/selection.ts b/frontend/src/plugins/impl/plotly/selection.ts
index f0132eb761..b44a83dfa0 100644
--- a/frontend/src/plugins/impl/plotly/selection.ts
+++ b/frontend/src/plugins/impl/plotly/selection.ts
@@ -227,6 +227,7 @@ export function shouldHandleClickSelection(
type === "bar" ||
type === "heatmap" ||
type === "histogram" ||
+ type === "waterfall" ||
isLinePoint(point)
);
});
diff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.py
index d924fa764d..a10ee0eb36 100644
--- a/marimo/_plugins/ui/_impl/plotly.py
+++ b/marimo/_plugins/ui/_impl/plotly.py
@@ -205,7 +205,8 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):
cursor on the frontend, get them as a list of dicts in Python!
This function supports scatter plots, scattergl plots, line charts, area
- charts, bar charts, histograms, treemap charts, sunburst charts, and heatmaps.
+ charts, bar charts, histograms, waterfall charts, treemap charts, sunburst
+ charts, and heatmaps.
Examples:
```python
@@ -330,6 +331,7 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):
"heatmap",
"bar",
"histogram",
+ "waterfall",
):
continue
x_data = getattr(trace, "x", None)
@@ -486,6 +488,19 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):
if has_bar and value.get("range"):
_append_bar_items_to_selection(self._figure, self._selection_data)
+ has_waterfall = any(
+ getattr(trace, "type", None) == "waterfall"
+ for trace in self._figure.data
+ )
+
+ # For waterfall charts: extract bars within a range selection or pass
+ # through click data. Waterfall bars stack, so extraction uses
+ # cumulative-sum positions rather than raw trace.y values.
+ if has_waterfall:
+ _append_waterfall_bars_to_selection(
+ self._figure, self._selection_data
+ )
+
# For line/scatter charts, extract points from box/lasso selections.
# Plotly may not send point data for pure line charts, so we extract manually.
if has_scatter and (value.get("range") or value.get("lasso")):
@@ -1955,6 +1970,333 @@ def _build_bar_point(
return point
+def _compute_waterfall_bar_extents(
+ y_data: Any,
+ measures: Any,
+ base: float,
+) -> list[tuple[float, float]]:
+ """Return the visual (low, high) extent for each waterfall bar.
+
+ Waterfall bars stack on top of each other, so the visual position of
+ each bar depends on the cumulative sum of preceding relative bars:
+
+ * ``"absolute"`` — bar runs from *base* to y[i]; resets running total.
+ * ``"relative"`` — bar runs from running_total to running_total + y[i].
+ * ``"total"`` — bar runs from *base* to running_total (display only;
+ does not alter the running total).
+ """
+ running_total = base
+ extents: list[tuple[float, float]] = []
+
+ default_measure = "relative"
+ for i, y_val in enumerate(y_data):
+ try:
+ m = (
+ str(measures[i]).lower()
+ if measures is not None and i < len(measures)
+ else default_measure
+ )
+ except (IndexError, TypeError):
+ m = default_measure
+
+ try:
+ v = float(y_val)
+ except (TypeError, ValueError):
+ v = 0.0
+
+ if m == "absolute":
+ bar_lo, bar_hi = base, v
+ running_total = v
+ elif m == "total":
+ bar_lo, bar_hi = base, running_total
+ else: # relative
+ bar_lo = running_total
+ bar_hi = running_total + v
+ running_total = bar_hi
+
+ extents.append((min(bar_lo, bar_hi), max(bar_lo, bar_hi)))
+
+ return extents
+
+
+def _append_waterfall_bars_to_selection(
+ figure: go.Figure, selection_data: dict[str, Any]
+) -> None:
+ """Handle selection data for go.Waterfall traces.
+
+ Two cases:
+ 1. Range selection (dragmode="select"): extract waterfall bars whose
+ visual extent (accounting for stacking) overlaps the selection rectangle.
+ 2. Click selection: pass through frontend-supplied points, stripping
+ empty-dict placeholders and re-syncing indices.
+ """
+ range_value = selection_data.get("range")
+ all_points = cast(list[dict[str, Any]], selection_data.get("points", []))
+ all_indices = cast(list[Any], selection_data.get("indices", []))
+
+ if isinstance(range_value, dict):
+ waterfall_items = _extract_waterfall_bars_from_range(
+ figure, cast(dict[str, Any], range_value)
+ )
+ has_real_points = any(all_points)
+ if not has_real_points and not waterfall_items:
+ selection_data["points"] = []
+ selection_data["indices"] = []
+ return
+
+ seen: set[tuple[int, int]] = set()
+ merged_points: list[dict[str, Any]] = []
+ merged_indices: list[int] = []
+
+ for point_idx, point in enumerate(all_points):
+ if not point:
+ continue
+ point_id = _get_selection_point_id(point)
+ if point_id is not None:
+ if point_id in seen:
+ continue
+ seen.add(point_id)
+ merged_points.append(point)
+ if point_idx < len(all_indices) and isinstance(
+ all_indices[point_idx], int
+ ):
+ merged_indices.append(all_indices[point_idx])
+ elif point_id is not None:
+ merged_indices.append(point_id[1])
+
+ for point in waterfall_items:
+ point_id = _get_selection_point_id(point)
+ if point_id is not None:
+ if point_id in seen:
+ continue
+ seen.add(point_id)
+ merged_indices.append(point_id[1])
+ merged_points.append(point)
+
+ selection_data["points"] = merged_points
+ selection_data["indices"] = merged_indices
+ else:
+ # Click: strip empty placeholders, re-sync indices.
+ clean_points = [p for p in all_points if p]
+ if not clean_points:
+ selection_data["points"] = []
+ selection_data["indices"] = []
+ return
+ incoming_index_map = {
+ id(p): idx
+ for idx, p in zip(all_indices, all_points)
+ if p and isinstance(idx, int)
+ }
+ clean_indices: list[int] = []
+ for p in clean_points:
+ idx = incoming_index_map.get(id(p))
+ if isinstance(idx, int):
+ clean_indices.append(idx)
+ else:
+ pi = p.get("pointIndex", p.get("pointNumber"))
+ if isinstance(pi, int):
+ clean_indices.append(pi)
+ selection_data["points"] = clean_points
+ selection_data["indices"] = clean_indices
+
+
+def _extract_waterfall_bars_from_range(
+ figure: go.Figure, range_data: dict[str, Any]
+) -> list[dict[str, Any]]:
+ """Dispatch to numpy or fallback waterfall extraction."""
+ if not range_data.get("x") or not range_data.get("y"):
+ return []
+
+ x_range = range_data["x"]
+ y_range = range_data["y"]
+ x_min, x_max = min(x_range), max(x_range)
+ y_min, y_max = min(y_range), max(y_range)
+
+ if DependencyManager.numpy.has():
+ return _extract_waterfall_bars_numpy(
+ figure, x_min, x_max, y_min, y_max
+ )
+ return _extract_waterfall_bars_fallback(figure, x_min, x_max, y_min, y_max)
+
+
+def _extract_waterfall_bars_numpy(
+ figure: go.Figure,
+ x_min: float,
+ x_max: float,
+ y_min: float,
+ y_max: float,
+) -> list[dict[str, Any]]:
+ """Extract waterfall bars using numpy for vectorized filtering."""
+ import numpy as np
+
+ selected: list[dict[str, Any]] = []
+
+ for trace_idx, trace in enumerate(figure.data):
+ if getattr(trace, "type", None) != "waterfall":
+ continue
+
+ x_data = getattr(trace, "x", None)
+ y_data = getattr(trace, "y", None)
+ if x_data is None or y_data is None:
+ continue
+
+ n = len(y_data) if hasattr(y_data, "__len__") else 0
+ if n == 0:
+ continue
+
+ orientation = getattr(trace, "orientation", None) or "v"
+ measures = getattr(trace, "measure", None)
+ trace_base = getattr(trace, "base", None)
+ base = (
+ float(trace_base) if isinstance(trace_base, (int, float)) else 0.0
+ )
+
+ if orientation == "h":
+ # Horizontal: y=labels (categorical), x=values (stacking)
+ cat_data, val_data = y_data, x_data
+ cat_min, cat_max = y_min, y_max
+ val_min, val_max = x_min, x_max
+ else:
+ # Vertical (default): x=labels (categorical), y=values (stacking)
+ cat_data, val_data = x_data, y_data
+ cat_min, cat_max = x_min, x_max
+ val_min, val_max = y_min, y_max
+
+ # Category axis: orderable (numeric/datetime) or positional (categorical)
+ cat_arr = np.asarray(cat_data)
+ cat_is_orderable = _is_orderable_axis(cat_arr, cat_min)
+ if cat_is_orderable:
+ cat_min_p = _parse_datetime_bound(cat_min)
+ cat_max_p = _parse_datetime_bound(cat_max)
+ cat_mask = (cat_arr >= cat_min_p) & (cat_arr <= cat_max_p)
+ else:
+ cat_positions = np.arange(n, dtype=np.float64)
+ cat_mask = (cat_max > cat_positions - 0.5) & (
+ cat_min < cat_positions + 0.5
+ )
+
+ # Value axis: use stacked extents (low, high) for each bar
+ extents = _compute_waterfall_bar_extents(val_data, measures, base)
+ ext_arr = np.array(extents, dtype=np.float64) # shape (n, 2)
+ bar_lo = ext_arr[:, 0]
+ bar_hi = ext_arr[:, 1]
+ # Overlap condition: val_min < bar_hi AND val_max > bar_lo
+ val_mask = (val_min < bar_hi) & (val_max > bar_lo)
+
+ mask = cat_mask & val_mask
+ for i in np.where(mask)[0]:
+ selected.append(
+ _build_waterfall_point(
+ trace, trace_idx, int(i), x_data, y_data, measures
+ )
+ )
+
+ return selected
+
+
+def _extract_waterfall_bars_fallback(
+ figure: go.Figure,
+ x_min: float,
+ x_max: float,
+ y_min: float,
+ y_max: float,
+) -> list[dict[str, Any]]:
+ """Extract waterfall bars using pure Python (fallback when numpy unavailable)."""
+ selected: list[dict[str, Any]] = []
+
+ for trace_idx, trace in enumerate(figure.data):
+ if getattr(trace, "type", None) != "waterfall":
+ continue
+
+ x_data = getattr(trace, "x", None)
+ y_data = getattr(trace, "y", None)
+ if x_data is None or y_data is None:
+ continue
+
+ n = len(y_data) if hasattr(y_data, "__len__") else 0
+ if n == 0:
+ continue
+
+ orientation = getattr(trace, "orientation", None) or "v"
+ measures = getattr(trace, "measure", None)
+ trace_base = getattr(trace, "base", None)
+ base = (
+ float(trace_base) if isinstance(trace_base, (int, float)) else 0.0
+ )
+
+ if orientation == "h":
+ cat_data, val_data = y_data, x_data
+ cat_min, cat_max = y_min, y_max
+ val_min, val_max = x_min, x_max
+ else:
+ cat_data, val_data = x_data, y_data
+ cat_min, cat_max = x_min, x_max
+ val_min, val_max = y_min, y_max
+
+ extents = _compute_waterfall_bar_extents(val_data, measures, base)
+
+ for i, (bar_lo, bar_hi) in enumerate(extents):
+ # Category check: orderable (numeric/datetime) or positional
+ cat_val = _get_indexed_value(cat_data, i)
+ if _is_orderable_value(cat_val) and _is_orderable_value(cat_min):
+ cat_min_p = _parse_datetime_bound(cat_min)
+ cat_max_p = _parse_datetime_bound(cat_max)
+ cat_val_p = _parse_datetime_bound(cat_val)
+ if not (cat_min_p <= cat_val_p <= cat_max_p):
+ continue
+ else:
+ if cat_max <= i - 0.5 or cat_min >= i + 0.5:
+ continue
+ # Value check: bar [bar_lo, bar_hi] overlaps [val_min, val_max]
+ if val_min >= bar_hi or val_max <= bar_lo:
+ continue
+ selected.append(
+ _build_waterfall_point(
+ trace, trace_idx, i, x_data, y_data, measures
+ )
+ )
+
+ return selected
+
+
+def _build_waterfall_point(
+ trace: Any,
+ trace_idx: int,
+ point_idx: int,
+ x_data: Any,
+ y_data: Any,
+ measures: Any,
+) -> dict[str, Any]:
+ """Build a selection point dict for a single waterfall bar."""
+ x_val = _get_indexed_value(x_data, point_idx)
+ y_val = _get_indexed_value(y_data, point_idx)
+ point: dict[str, Any] = {
+ "x": x_val,
+ "y": y_val,
+ "curveNumber": trace_idx,
+ "pointIndex": point_idx,
+ "pointNumber": point_idx,
+ }
+ # Include the measure type so callers know if it's relative/absolute/total
+ try:
+ m = measures[point_idx] if measures is not None else None
+ except (IndexError, TypeError):
+ m = None
+ if m is not None:
+ point["measure"] = str(m)
+
+ name = getattr(trace, "name", None)
+ if name:
+ point["name"] = name
+
+ for field in ("customdata", "text", "hovertext"):
+ val = _get_indexed_value(getattr(trace, field, None), point_idx)
+ if val is not None:
+ point[field] = val
+
+ return point
+
+
def _append_map_scatter_points_to_selection(
figure: go.Figure, selection_data: dict[str, Any]
) -> None:
diff --git a/tests/_plugins/ui/_impl/test_plotly.py b/tests/_plugins/ui/_impl/test_plotly.py
index 37f7559145..252619bab2 100644
--- a/tests/_plugins/ui/_impl/test_plotly.py
+++ b/tests/_plugins/ui/_impl/test_plotly.py
@@ -16,6 +16,7 @@ import plotly.graph_objects as go
from marimo._plugins.ui._impl.plotly import (
_bar_value_in_selection_range,
+ _compute_waterfall_bar_extents,
_extract_bars_fallback,
_extract_bars_numpy,
_extract_heatmap_cells_fallback,
@@ -24,6 +25,8 @@ from marimo._plugins.ui._impl.plotly import (
_extract_histogram_points_numpy,
_extract_scatter_points_fallback,
_extract_scatter_points_numpy,
+ _extract_waterfall_bars_fallback,
+ _extract_waterfall_bars_numpy,
_to_numeric_coord,
plotly,
)
@@ -3012,3 +3015,320 @@ def test_bar_chart_preserves_indices_when_empty_points_exist() -> None:
assert result == [{"x": "B", "y": 20, "curveNumber": 0, "pointIndex": 1}]
assert plot.indices == [1]
+
+
+# ============================================================================
+# Waterfall chart tests
+# ============================================================================
+
+
+def test_waterfall_basic() -> None:
+ """Waterfall plot starts with empty value."""
+ fig = go.Figure(
+ data=go.Waterfall(
+ x=["Start", "Revenue", "Costs", "Net"],
+ y=[1000, 400, -150, 0],
+ measure=["absolute", "relative", "relative", "total"],
+ )
+ )
+ plot = plotly(fig)
+ assert plot.value == []
+ assert plot.indices == []
+
+
+def test_waterfall_click_selection() -> None:
+ """Click on a waterfall bar passes through x, y, and pointIndex."""
+ fig = go.Figure(
+ data=go.Waterfall(
+ x=["Start", "Revenue", "Costs", "Net"],
+ y=[1000, 400, -150, 0],
+ measure=["absolute", "relative", "relative", "total"],
+ )
+ )
+ plot = plotly(fig)
+
+ selection = {
+ "points": [
+ {
+ "x": "Revenue",
+ "y": 400,
+ "curveNumber": 0,
+ "pointIndex": 1,
+ "pointNumber": 1,
+ }
+ ],
+ "indices": [1],
+ }
+ result = plot._convert_value(selection)
+ assert len(result) == 1
+ assert result[0]["x"] == "Revenue"
+ assert result[0]["y"] == 400
+ assert plot.indices == [1]
+
+
+def test_waterfall_click_empty_placeholder_stripped() -> None:
+ """Empty-dict placeholders from the frontend are stripped on click."""
+ fig = go.Figure(
+ data=go.Waterfall(
+ x=["Start", "Revenue"],
+ y=[1000, 400],
+ measure=["absolute", "relative"],
+ )
+ )
+ plot = plotly(fig)
+
+ selection = {
+ "points": [
+ {},
+ {"x": "Revenue", "y": 400, "curveNumber": 0, "pointIndex": 1},
+ ],
+ "indices": [999, 1],
+ }
+ result = plot._convert_value(selection)
+ assert len(result) == 1
+ assert result[0]["x"] == "Revenue"
+ assert plot.indices == [1]
+
+
+def test_compute_waterfall_bar_extents_relative() -> None:
+ """Relative bars stack on top of each other."""
+ y = [100, 50, -30]
+ measures = ["relative", "relative", "relative"]
+ extents = _compute_waterfall_bar_extents(y, measures, base=0.0)
+ assert extents == [(0.0, 100.0), (100.0, 150.0), (120.0, 150.0)]
+
+
+def test_compute_waterfall_bar_extents_absolute_resets() -> None:
+ """An 'absolute' bar resets the running total."""
+ y = [100, 50, 200, -20]
+ measures = ["relative", "relative", "absolute", "relative"]
+ extents = _compute_waterfall_bar_extents(y, measures, base=0.0)
+ # After absolute bar at index 2: running_total = 200
+ assert extents[2] == (0.0, 200.0)
+ assert extents[3] == (180.0, 200.0)
+
+
+def test_compute_waterfall_bar_extents_total() -> None:
+ """A 'total' bar shows running total from base; does not change it."""
+ y = [500, 300, 0]
+ measures = ["absolute", "relative", "total"]
+ extents = _compute_waterfall_bar_extents(y, measures, base=0.0)
+ # running_total after absolute=500, after relative=800
+ # total bar = [0, 800]
+ assert extents[2] == (0.0, 800.0)
+
+
+def test_compute_waterfall_bar_extents_negative_relative() -> None:
+ """Negative relative bars extend downward; extents are sorted low-high."""
+ y = [400, -150]
+ measures = ["absolute", "relative"]
+ extents = _compute_waterfall_bar_extents(y, measures, base=0.0)
+ assert extents[0] == (0.0, 400.0)
+ # bar goes from 400 down to 250 → stored as (250, 400)
+ assert extents[1] == (250.0, 400.0)
+
+
+def test_waterfall_range_selection_partial() -> None:
+ """Box selection extracts only bars whose visual extent overlaps the range."""
+ fig = go.Figure(
+ data=go.Waterfall(
+ x=["Start", "Revenue", "Costs", "Net"],
+ y=[1000, 400, -150, 0],
+ measure=["absolute", "relative", "relative", "total"],
+ )
+ )
+ plot = plotly(fig)
+
+ # Visual extents:
+ # Start: [0, 1000] (absolute)
+ # Revenue: [1000, 1400] (relative)
+ # Costs: [1250, 1400] (relative, -150)
+ # Net: [0, 1250] (total)
+ #
+ # y_range [1100, 1500] overlaps Revenue and Costs but NOT Start or Net.
+ selection: dict[str, Any] = {
+ "points": [],
+ "indices": [],
+ "range": {"x": [-0.5, 2.5], "y": [1100.0, 1500.0]},
+ }
+ result = plot._convert_value(selection)
+ labels = [p["x"] for p in result]
+ assert "Revenue" in labels
+ assert "Costs" in labels
+ assert "Start" not in labels
+ assert "Net" not in labels
+
+
+def test_waterfall_range_selection_all_bars() -> None:
+ """Full y-range selects every bar."""
+ fig = go.Figure(
+ data=go.Waterfall(
+ x=["Start", "Revenue", "Costs", "Net"],
+ y=[1000, 400, -150, 0],
+ measure=["absolute", "relative", "relative", "total"],
+ )
+ )
+ plot = plotly(fig)
+
+ selection: dict[str, Any] = {
+ "points": [],
+ "indices": [],
+ "range": {"x": [-0.5, 3.5], "y": [0.0, 1500.0]},
+ }
+ result = plot._convert_value(selection)
+ assert len(result) == 4
+
+
+def test_waterfall_range_selection_empty() -> None:
+ """Range that misses all bars returns empty."""
+ fig = go.Figure(
+ data=go.Waterfall(
+ x=["Start", "Revenue"],
+ y=[1000, 400],
+ measure=["absolute", "relative"],
+ )
+ )
+ plot = plotly(fig)
+
+ selection: dict[str, Any] = {
+ "points": [],
+ "indices": [],
+ "range": {"x": [-0.5, 1.5], "y": [5000.0, 6000.0]},
+ }
+ result = plot._convert_value(selection)
+ assert result == []
+ assert plot.indices == []
+
+
+def test_waterfall_measure_included_in_range_extraction() -> None:
+ """Extracted points include the measure field."""
+ fig = go.Figure(
+ data=go.Waterfall(
+ x=["Start", "Revenue", "Net"],
+ y=[1000, 400, 0],
+ measure=["absolute", "relative", "total"],
+ )
+ )
+ plot = plotly(fig)
+
+ selection: dict[str, Any] = {
+ "points": [],
+ "indices": [],
+ "range": {"x": [-0.5, 2.5], "y": [0.0, 1500.0]},
+ }
+ result = plot._convert_value(selection)
+ measures = {p["x"]: p.get("measure") for p in result}
+ assert measures.get("Start") == "absolute"
+ assert measures.get("Revenue") == "relative"
+ assert measures.get("Net") == "total"
+
+
+def test_waterfall_numpy_and_fallback_match() -> None:
+ """numpy and fallback extraction produce identical results."""
+ fig = go.Figure(
+ data=go.Waterfall(
+ x=["Start", "Revenue", "Costs", "Net"],
+ y=[1000, 400, -150, 0],
+ measure=["absolute", "relative", "relative", "total"],
+ )
+ )
+
+ x_min, x_max = -0.5, 2.5
+ y_min, y_max = 1100.0, 1500.0
+
+ numpy_result = _extract_waterfall_bars_numpy(
+ fig, x_min, x_max, y_min, y_max
+ )
+ fallback_result = _extract_waterfall_bars_fallback(
+ fig, x_min, x_max, y_min, y_max
+ )
+
+ assert len(numpy_result) == len(fallback_result)
+ for np_pt, fb_pt in zip(
+ sorted(numpy_result, key=lambda p: p["pointIndex"]),
+ sorted(fallback_result, key=lambda p: p["pointIndex"]),
+ ):
+ assert np_pt["x"] == fb_pt["x"]
+ assert np_pt["y"] == fb_pt["y"]
+ assert np_pt["pointIndex"] == fb_pt["pointIndex"]
+
+
+def test_waterfall_horizontal_orientation() -> None:
+ """Horizontal waterfall (orientation='h') extracts bars correctly."""
+ fig = go.Figure(
+ data=go.Waterfall(
+ y=["Start", "Revenue", "Costs"],
+ x=[500, 200, -80],
+ measure=["absolute", "relative", "relative"],
+ orientation="h",
+ )
+ )
+ plot = plotly(fig)
+
+ # Visual extents on x-axis:
+ # Start: [0, 500]
+ # Revenue: [500, 700]
+ # Costs: [620, 700]
+ # x_range [550, 750] overlaps Revenue and Costs but not Start.
+ selection: dict[str, Any] = {
+ "points": [],
+ "indices": [],
+ "range": {"x": [550.0, 750.0], "y": [-0.5, 2.5]},
+ }
+ result = plot._convert_value(selection)
+ labels = [p["y"] for p in result]
+ assert "Revenue" in labels
+ assert "Costs" in labels
+ assert "Start" not in labels
+
+
+def test_waterfall_multi_trace() -> None:
+ """Multiple waterfall traces are each extracted independently."""
+ fig = go.Figure(
+ data=[
+ go.Waterfall(
+ x=["A", "B"],
+ y=[100, 50],
+ measure=["absolute", "relative"],
+ name="T1",
+ ),
+ go.Waterfall(
+ x=["A", "B"],
+ y=[200, -30],
+ measure=["absolute", "relative"],
+ name="T2",
+ ),
+ ]
+ )
+ plot = plotly(fig)
+
+ selection: dict[str, Any] = {
+ "points": [],
+ "indices": [],
+ "range": {"x": [-0.5, 1.5], "y": [0.0, 300.0]},
+ }
+ result = plot._convert_value(selection)
+ curve_numbers = {p["curveNumber"] for p in result}
+ assert curve_numbers == {0, 1}
+ assert len(result) == 4
+
+
+def test_waterfall_customdata_included() -> None:
+ """customdata attached to bars appears in extracted points."""
+ fig = go.Figure(
+ data=go.Waterfall(
+ x=["Start", "Revenue"],
+ y=[1000, 400],
+ measure=["absolute", "relative"],
+ customdata=[["dept_A"], ["dept_B"]],
+ )
+ )
+ plot = plotly(fig)
+
+ selection: dict[str, Any] = {
+ "points": [],
+ "indices": [],
+ "range": {"x": [-0.5, 1.5], "y": [0.0, 1500.0]},
+ }
+ result = plot._convert_value(selection)
+ assert all(p.get("customdata") is not None for p in result)