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 box plot selection support (#9010)

axsselb73a370f66b7
diff --git a/docs/api/plotting.md b/docs/api/plotting.md
index f30128230b..b38dcc79d4 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,
- violin plots, histograms, waterfall charts, heatmaps, treemaps, and sunburst charts. If you require other kinds of
+ box plots, violin plots, strip charts, histograms, funnel charts, funnelarea charts, 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/box_chart.py b/examples/third_party/plotly/box_chart.py
new file mode 100644
index 0000000000..6c172e9cbc
--- /dev/null
+++ b/examples/third_party/plotly/box_chart.py
@@ -0,0 +1,306 @@
+# /// 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.express as px
+ import plotly.graph_objects as go
+
+ return go, mo, pd, px
+
+
+def _(mo):
+ mo.md("""
+ # Reactive Plotly Box Plot Selection
+
+ This example demonstrates reactive box plot selections with `mo.ui.plotly`.
+
+ Try:
+ - **Drag a box** over jittered sample points to select them
+ - **Click** a box element (median line, whisker, or box body) to select the
+ entire group
+ - Watch the table and stats below update from your selection
+
+ The `customdata` field embeds the original row ID (`sample_id`) so selected
+ points map back to the source DataFrame without relying on raw indices.
+ """)
+ return
+
+
+def _(pd):
+ rows = [
+ ("ENG-01", "Engineering", "Day", "West", 72),
+ ("ENG-02", "Engineering", "Day", "West", 78),
+ ("ENG-03", "Engineering", "Day", "East", 81),
+ ("ENG-04", "Engineering", "Night", "East", 75),
+ ("ENG-05", "Engineering", "Night", "West", 84),
+ ("ENG-06", "Engineering", "Night", "Central", 89),
+ ("SAL-01", "Sales", "Day", "West", 61),
+ ("SAL-02", "Sales", "Day", "Central", 66),
+ ("SAL-03", "Sales", "Day", "East", 70),
+ ("SAL-04", "Sales", "Night", "West", 64),
+ ("SAL-05", "Sales", "Night", "East", 73),
+ ("SAL-06", "Sales", "Night", "Central", 77),
+ ("SUP-01", "Support", "Day", "East", 58),
+ ("SUP-02", "Support", "Day", "Central", 62),
+ ("SUP-03", "Support", "Day", "West", 68),
+ ("SUP-04", "Support", "Night", "East", 60),
+ ("SUP-05", "Support", "Night", "Central", 65),
+ ("SUP-06", "Support", "Night", "West", 71),
+ ]
+ df = pd.DataFrame(rows, columns=["sample_id", "team", "shift", "region", "score"])
+ df["passed"] = df["score"] >= 75
+ return (df,)
+
+
+def _():
+ def selected_rows(selection, data):
+ """Map a mo.ui.plotly selection back to rows in the source DataFrame."""
+ empty = data.iloc[0:0].copy()
+ if not selection:
+ return empty
+
+ # Prefer sample_id embedded via customdata.
+ # Box-body clicks embed sample_id as customdata[0], not a top-level key.
+ ids = []
+ for row in selection:
+ if isinstance(row.get("sample_id"), str):
+ ids.append(row["sample_id"])
+ else:
+ cd = row.get("customdata")
+ if isinstance(cd, (list, tuple)) and cd and isinstance(cd[0], str):
+ ids.append(cd[0])
+ if ids:
+ return (
+ data[data["sample_id"].isin(ids)]
+ .drop_duplicates("sample_id")
+ .sort_values("sample_id")
+ )
+
+ # Fall back to pointIndex
+ indices = sorted({
+ row["pointIndex"]
+ for row in selection
+ if isinstance(row.get("pointIndex"), int)
+ and 0 <= row["pointIndex"] < len(data)
+ })
+ if indices:
+ return data.iloc[indices].copy()
+
+ return empty
+
+ return (selected_rows,)
+
+
+def _(df, go, mo):
+ mo.md("## Single-Trace Box Plot")
+
+ fig_single = go.Figure(
+ data=go.Box(
+ x=df["team"],
+ y=df["score"],
+ customdata=df[["sample_id", "shift", "region", "passed"]],
+ boxpoints="all",
+ jitter=0.35,
+ pointpos=0,
+ marker=dict(size=10, opacity=0.8, color="#1f77b4"),
+ line=dict(color="#1f77b4"),
+ hovertemplate=(
+ "sample_id=%{customdata[0]}<br>"
+ "team=%{x}<br>"
+ "score=%{y}<br>"
+ "shift=%{customdata[1]}<br>"
+ "region=%{customdata[2]}<br>"
+ "passed=%{customdata[3]}<extra></extra>"
+ ),
+ name="score",
+ )
+ )
+ fig_single.update_layout(
+ title="Score by Team — drag over points or click a box",
+ xaxis_title="Team",
+ yaxis_title="Score",
+ dragmode="select",
+ )
+
+ box_single = mo.ui.plotly(fig_single)
+ box_single
+ return (box_single,)
+
+
+def _(box_single, df, mo, selected_rows):
+ _sel = selected_rows(box_single.value, df)
+
+ _summary = (
+ f"{len(_sel)} rows selected — "
+ f"avg score: {_sel['score'].mean():.1f} — "
+ f"pass rate: {_sel['passed'].mean():.0%}"
+ if not _sel.empty
+ else "No rows selected yet."
+ )
+
+ mo.md(f"""
+ ### Single-Trace Selection
+
+ **{_summary}**
+
+ **Indices:** {box_single.indices}
+ """)
+ return
+
+
+def _(box_single, df, mo, selected_rows):
+ mo.ui.table(selected_rows(box_single.value, df))
+ return
+
+
+def _(df, mo, px):
+ mo.md("## Grouped Box Plot")
+
+ fig_grouped = px.box(
+ df,
+ x="team",
+ y="score",
+ color="shift",
+ points="all",
+ custom_data=["sample_id", "shift", "region", "passed"],
+ title="Score by Team and Shift — drag to compare groups",
+ )
+ fig_grouped.update_traces(
+ jitter=0.35,
+ pointpos=0,
+ hovertemplate=(
+ "sample_id=%{customdata[0]}<br>"
+ "team=%{x}<br>"
+ "score=%{y}<br>"
+ "shift=%{customdata[1]}<br>"
+ "region=%{customdata[2]}<br>"
+ "passed=%{customdata[3]}<extra></extra>"
+ ),
+ )
+ fig_grouped.update_layout(dragmode="select", xaxis_title="Team", yaxis_title="Score")
+
+ box_grouped = mo.ui.plotly(fig_grouped)
+ box_grouped
+ return (box_grouped,)
+
+
+def _(box_grouped, df, mo, selected_rows):
+ _sel_g = selected_rows(box_grouped.value, df)
+
+ _summary_g = (
+ f"{len(_sel_g)} rows — "
+ + ", ".join(
+ f"{team}: {count}"
+ for team, count in _sel_g.groupby("team").size().items()
+ )
+ if not _sel_g.empty
+ else "No rows selected yet."
+ )
+
+ mo.md(f"""
+ ### Grouped Selection
+
+ **{_summary_g}**
+
+ **Indices:** {box_grouped.indices}
+
+ **Range:** {box_grouped.ranges}
+ """)
+ return
+
+
+def _(box_grouped, df, mo, selected_rows):
+ mo.ui.table(selected_rows(box_grouped.value, df))
+ return
+
+
+def _(df, go, mo):
+ mo.md("## Horizontal Box Plot")
+
+ fig_horizontal = go.Figure(
+ data=go.Box(
+ x=df["score"],
+ y=df["team"],
+ orientation="h",
+ customdata=df[["sample_id", "shift", "region", "passed"]],
+ boxpoints="all",
+ jitter=0.35,
+ pointpos=0,
+ marker=dict(size=10, opacity=0.8, color="#2a9d8f"),
+ line=dict(color="#2a9d8f"),
+ hovertemplate=(
+ "sample_id=%{customdata[0]}<br>"
+ "team=%{y}<br>"
+ "score=%{x}<br>"
+ "shift=%{customdata[1]}<br>"
+ "region=%{customdata[2]}<br>"
+ "passed=%{customdata[3]}<extra></extra>"
+ ),
+ name="score",
+ )
+ )
+ fig_horizontal.update_layout(
+ title="Score by Team (horizontal) — same data, transposed",
+ xaxis_title="Score",
+ yaxis_title="Team",
+ dragmode="select",
+ )
+
+ box_horizontal = mo.ui.plotly(fig_horizontal)
+ box_horizontal
+ return (box_horizontal,)
+
+
+def _(box_horizontal, df, mo, selected_rows):
+ _sel_h = selected_rows(box_horizontal.value, df)
+
+ _summary_h = (
+ f"{len(_sel_h)} rows — avg score: {_sel_h['score'].mean():.1f}"
+ if not _sel_h.empty
+ else "No rows selected yet."
+ )
+
+ mo.md(f"""
+ ### Horizontal Selection
+
+ **{_summary_h}**
+
+ **Indices:** {box_horizontal.indices}
+ """)
+ return
+
+
+def _(box_horizontal, df, mo, selected_rows):
+ mo.ui.table(selected_rows(box_horizontal.value, df))
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/examples/third_party/plotly/funnel_chart.py b/examples/third_party/plotly/funnel_chart.py
new file mode 100644
index 0000000000..ee9d7dc015
--- /dev/null
+++ b/examples/third_party/plotly/funnel_chart.py
@@ -0,0 +1,215 @@
+# /// script
+# requires-python = ">=3.10"
+# dependencies = [
+# "marimo",
+# "pandas==2.3.0",
+# "plotly==6.0.1",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.20.2"
+app = marimo.App(width="medium")
+
+
+def _():
+ import marimo as mo
+ import pandas as pd
+ import plotly.express as px
+ import plotly.graph_objects as go
+
+ return go, mo, pd, px
+
+
+def _(mo):
+ mo.md("""
+ # Reactive Plotly Funnel Chart Selection
+
+ This example demonstrates reactive funnel chart selections with `mo.ui.plotly`.
+
+ Funnel charts visualise drop-off at each stage of a sequential process (e.g. a
+ sales pipeline or marketing funnel). Each segment represents one stage; the bar
+ width shows the absolute count and the percent metrics show retention relative to
+ the initial, previous, and overall totals.
+
+ Try:
+ - **Click** any funnel stage to select it — the table below updates instantly
+ - **Drag a box** (set `dragmode="select"`) over multiple stages to select a range
+ - Switch between the multi-trace and `FunnelArea` tabs to explore variants
+ """)
+ return
+
+
+def _(pd):
+ pipeline_data = pd.DataFrame(
+ {
+ "stage": [
+ "Leads",
+ "Qualified",
+ "Proposal",
+ "Negotiation",
+ "Closed Won",
+ ],
+ "count": [5000, 2800, 1400, 620, 310],
+ "region": ["Global"] * 5,
+ }
+ )
+ return (pipeline_data,)
+
+
+def _(mo, pipeline_data, px):
+ mo.md("## Single-Trace Funnel (`px.funnel`)")
+
+ fig_funnel = px.funnel(
+ pipeline_data,
+ x="count",
+ y="stage",
+ title="Sales Pipeline — click a stage to inspect it",
+ labels={"count": "Leads", "stage": "Stage"},
+ )
+ fig_funnel.update_layout(
+ dragmode="select",
+ margin=dict(l=120),
+ )
+
+ funnel_plot = mo.ui.plotly(fig_funnel)
+ funnel_plot
+ return (funnel_plot,)
+
+
+def _(funnel_plot, mo, pipeline_data):
+ _pts = funnel_plot.value
+
+ if _pts:
+ _stage = _pts[0].get("y") or _pts[0].get("label")
+ _row = pipeline_data[pipeline_data["stage"] == _stage]
+ _pct_initial = _pts[0].get("percentInitial", 1.0)
+ _summary = (
+ f"**{_stage}** — "
+ f"{_row['count'].iloc[0]:,} leads — "
+ f"{_pct_initial:.0%} retention from start"
+ )
+ else:
+ _summary = "Click any funnel stage to inspect it."
+
+ mo.md(f"""
+ ### Selected Stage
+
+ {_summary}
+
+ **Raw selection:** {funnel_plot.value}
+ """)
+ return
+
+
+def _(mo, pd):
+ mo.md("## Multi-Trace Funnel — Regional Breakdown")
+
+ regional = pd.DataFrame(
+ {
+ "stage": [
+ "Leads", "Qualified", "Proposal", "Negotiation", "Closed Won",
+ "Leads", "Qualified", "Proposal", "Negotiation", "Closed Won",
+ ],
+ "count": [3000, 1600, 900, 380, 190, 2000, 1200, 500, 240, 120],
+ "region": ["North America"] * 5 + ["Europe"] * 5,
+ }
+ )
+ return (regional,)
+
+
+def _(mo, px, regional):
+ fig_regional = px.funnel(
+ regional,
+ x="count",
+ y="stage",
+ color="region",
+ title="Regional Pipeline — select stages to compare regions",
+ )
+ fig_regional.update_layout(dragmode="select")
+
+ regional_plot = mo.ui.plotly(fig_regional)
+ regional_plot
+ return (regional_plot,)
+
+
+def _(mo, regional, regional_plot):
+ _pts = regional_plot.value
+
+ if _pts:
+ _rows = regional[
+ regional["stage"].isin(
+ [p.get("y") or p.get("label") for p in _pts if p]
+ )
+ ]
+ _table = mo.ui.table(_rows.reset_index(drop=True))
+ else:
+ _table = mo.ui.table(regional.iloc[0:0])
+
+ mo.vstack([
+ mo.md(f"**{len(_pts)} stage(s) selected** | Indices: {regional_plot.indices}"),
+ _table,
+ ])
+ return
+
+
+def _(go, mo):
+ mo.md("## Funnel Area Chart (`go.Funnelarea`)")
+
+ fig_area = go.Figure(
+ go.Funnelarea(
+ labels=["Awareness", "Interest", "Consideration", "Intent", "Purchase"],
+ values=[10000, 6000, 3000, 1200, 400],
+ textinfo="label+percent",
+ hovertemplate=(
+ "<b>%{label}</b><br>"
+ "Count: %{value:,}<br>"
+ "Retention from start: %{percentInitial:.1%}<br>"
+ "Retention from previous: %{percentPrevious:.1%}"
+ "<extra></extra>"
+ ),
+ )
+ )
+ fig_area.update_layout(title="Marketing Funnel Area — click a segment")
+
+ area_plot = mo.ui.plotly(fig_area)
+ area_plot
+ return (area_plot,)
+
+
+def _(area_plot, mo):
+ _pts = area_plot.value
+
+ if _pts:
+ _p = _pts[0]
+ _detail = (
+ f"**{_p.get('label')}** — "
+ f"{_p.get('value', 0):,} users — "
+ f"{_p.get('percentInitial', 1.0):.1%} of total"
+ )
+ else:
+ _detail = "Click any segment to inspect it."
+
+ mo.md(f"""
+ ### Selected Segment
+
+ {_detail}
+
+ **Raw selection:** {area_plot.value}
+ """)
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/examples/third_party/plotly/strip_chart.py b/examples/third_party/plotly/strip_chart.py
new file mode 100644
index 0000000000..762e8449d2
--- /dev/null
+++ b/examples/third_party/plotly/strip_chart.py
@@ -0,0 +1,310 @@
+# /// 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.express as px
+ import plotly.graph_objects as go
+
+ return go, mo, pd, px
+
+
+def _(mo):
+ mo.md("""
+ # Reactive Plotly Strip Chart Selection
+
+ This example demonstrates reactive strip chart selections with `mo.ui.plotly`.
+
+ Strip charts (also called dot plots or jitter plots) show every individual data
+ point, making them ideal for small-to-medium datasets where you want to see the
+ full distribution without aggregation.
+
+ Try:
+ - **Drag a box or lasso** over points to select a subset
+ - **Click** an individual point to select it
+ - Watch the table and stats below update in real time
+
+ The `customdata` field embeds `sample_id` so selected points map back to the
+ source DataFrame without relying on raw indices.
+ """)
+ return
+
+
+def _(pd):
+ rows = [
+ ("ENG-01", "Engineering", "Day", "West", 72),
+ ("ENG-02", "Engineering", "Day", "West", 78),
+ ("ENG-03", "Engineering", "Day", "East", 81),
+ ("ENG-04", "Engineering", "Night", "East", 75),
+ ("ENG-05", "Engineering", "Night", "West", 84),
+ ("ENG-06", "Engineering", "Night", "Central", 89),
+ ("SAL-01", "Sales", "Day", "West", 61),
+ ("SAL-02", "Sales", "Day", "Central", 66),
+ ("SAL-03", "Sales", "Day", "East", 70),
+ ("SAL-04", "Sales", "Night", "West", 64),
+ ("SAL-05", "Sales", "Night", "East", 73),
+ ("SAL-06", "Sales", "Night", "Central", 77),
+ ("SUP-01", "Support", "Day", "East", 58),
+ ("SUP-02", "Support", "Day", "Central", 62),
+ ("SUP-03", "Support", "Day", "West", 68),
+ ("SUP-04", "Support", "Night", "East", 60),
+ ("SUP-05", "Support", "Night", "Central", 65),
+ ("SUP-06", "Support", "Night", "West", 71),
+ ]
+ df = pd.DataFrame(rows, columns=["sample_id", "team", "shift", "region", "score"])
+ df["passed"] = df["score"] >= 75
+ return (df,)
+
+
+def _():
+ def selected_rows(selection, data):
+ """Map a mo.ui.plotly selection back to rows in the source DataFrame."""
+ empty = data.iloc[0:0].copy()
+ if not selection:
+ return empty
+
+ # Prefer sample_id embedded via customdata.
+ # Fallback-path selections embed sample_id as customdata[0] (a
+ # list/tuple), not as a parsed top-level key.
+ ids = []
+ for row in selection:
+ if isinstance(row.get("sample_id"), str):
+ ids.append(row["sample_id"])
+ else:
+ cd = row.get("customdata")
+ if isinstance(cd, (list, tuple)) and cd and isinstance(cd[0], str):
+ ids.append(cd[0])
+ if ids:
+ return (
+ data[data["sample_id"].isin(ids)]
+ .drop_duplicates("sample_id")
+ .sort_values("sample_id")
+ )
+
+ # Fall back to pointIndex
+ indices = sorted({
+ row["pointIndex"]
+ for row in selection
+ if isinstance(row.get("pointIndex"), int)
+ and 0 <= row["pointIndex"] < len(data)
+ })
+ if indices:
+ return data.iloc[indices].copy()
+
+ return empty
+
+ return (selected_rows,)
+
+
+def _(df, mo, px):
+ mo.md("## Strip Chart (px.strip)")
+
+ fig_strip = px.strip(
+ df,
+ x="team",
+ y="score",
+ color="shift",
+ custom_data=["sample_id", "shift", "region", "passed"],
+ title="Score by Team — drag a box or click individual points",
+ labels={"score": "Score", "team": "Team", "shift": "Shift"},
+ )
+ fig_strip.update_traces(
+ marker=dict(size=10, opacity=0.8),
+ hovertemplate=(
+ "sample_id=%{customdata[0]}<br>"
+ "team=%{x}<br>"
+ "score=%{y}<br>"
+ "shift=%{customdata[1]}<br>"
+ "region=%{customdata[2]}<br>"
+ "passed=%{customdata[3]}<extra></extra>"
+ ),
+ )
+ fig_strip.update_layout(dragmode="select")
+
+ strip_plot = mo.ui.plotly(fig_strip)
+ strip_plot
+ return (strip_plot,)
+
+
+def _(df, mo, selected_rows, strip_plot):
+ _sel = selected_rows(strip_plot.value, df)
+
+ _summary = (
+ f"{len(_sel)} rows selected — "
+ f"avg score: {_sel['score'].mean():.1f} — "
+ f"pass rate: {_sel['passed'].mean():.0%}"
+ if not _sel.empty
+ else "No rows selected yet."
+ )
+
+ mo.md(f"""
+ ### Strip Chart Selection
+
+ **{_summary}**
+
+ **Indices:** {strip_plot.indices}
+
+ **Range:** {strip_plot.ranges}
+ """)
+ return
+
+
+def _(df, mo, selected_rows, strip_plot):
+ mo.ui.table(selected_rows(strip_plot.value, df))
+ return
+
+
+def _(df, go, mo):
+ mo.md("## Single-Trace Strip Chart (go.Box with boxpoints='all')")
+
+ fig_single = go.Figure(
+ data=go.Box(
+ x=df["team"],
+ y=df["score"],
+ boxpoints="all",
+ jitter=0.4,
+ pointpos=0,
+ fillcolor="rgba(0,0,0,0)",
+ line=dict(color="rgba(0,0,0,0)"),
+ marker=dict(size=10, opacity=0.8, color="#e76f51"),
+ customdata=df[["sample_id", "shift", "region", "passed"]],
+ hovertemplate=(
+ "sample_id=%{customdata[0]}<br>"
+ "team=%{x}<br>"
+ "score=%{y}<br>"
+ "shift=%{customdata[1]}<br>"
+ "region=%{customdata[2]}<br>"
+ "passed=%{customdata[3]}<extra></extra>"
+ ),
+ name="score",
+ )
+ )
+ fig_single.update_layout(
+ title="Score by Team (single trace) — select any points",
+ xaxis_title="Team",
+ yaxis_title="Score",
+ dragmode="select",
+ showlegend=False,
+ )
+
+ strip_single = mo.ui.plotly(fig_single)
+ strip_single
+ return (strip_single,)
+
+
+def _(df, mo, selected_rows, strip_single):
+ _sel_s = selected_rows(strip_single.value, df)
+
+ _summary_s = (
+ f"{len(_sel_s)} rows — avg score: {_sel_s['score'].mean():.1f} — "
+ f"pass rate: {_sel_s['passed'].mean():.0%}"
+ if not _sel_s.empty
+ else "No rows selected yet."
+ )
+
+ mo.md(f"""
+ ### Single-Trace Selection
+
+ **{_summary_s}**
+
+ **Indices:** {strip_single.indices}
+ """)
+ return
+
+
+def _(df, mo, selected_rows, strip_single):
+ mo.ui.table(selected_rows(strip_single.value, df))
+ return
+
+
+def _(df, go, mo):
+ mo.md("## Horizontal Strip Chart")
+
+ fig_horizontal = go.Figure(
+ data=go.Box(
+ x=df["score"],
+ y=df["team"],
+ orientation="h",
+ boxpoints="all",
+ jitter=0.4,
+ pointpos=0,
+ fillcolor="rgba(0,0,0,0)",
+ line=dict(color="rgba(0,0,0,0)"),
+ marker=dict(size=10, opacity=0.8, color="#2a9d8f"),
+ customdata=df[["sample_id", "shift", "region", "passed"]],
+ hovertemplate=(
+ "sample_id=%{customdata[0]}<br>"
+ "team=%{y}<br>"
+ "score=%{x}<br>"
+ "shift=%{customdata[1]}<br>"
+ "region=%{customdata[2]}<br>"
+ "passed=%{customdata[3]}<extra></extra>"
+ ),
+ name="score",
+ )
+ )
+ fig_horizontal.update_layout(
+ title="Score by Team (horizontal) — same data, transposed",
+ xaxis_title="Score",
+ yaxis_title="Team",
+ dragmode="select",
+ showlegend=False,
+ )
+
+ strip_horizontal = mo.ui.plotly(fig_horizontal)
+ strip_horizontal
+ return (strip_horizontal,)
+
+
+def _(df, mo, selected_rows, strip_horizontal):
+ _sel_h = selected_rows(strip_horizontal.value, df)
+
+ _summary_h = (
+ f"{len(_sel_h)} rows — avg score: {_sel_h['score'].mean():.1f}"
+ if not _sel_h.empty
+ else "No rows selected yet."
+ )
+
+ mo.md(f"""
+ ### Horizontal Selection
+
+ **{_summary_h}**
+
+ **Indices:** {strip_horizontal.indices}
+ """)
+ return
+
+
+def _(df, mo, selected_rows, strip_horizontal):
+ mo.ui.table(selected_rows(strip_horizontal.value, df))
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/frontend/src/plugins/impl/plotly/__tests__/PlotlyPlugin.test.tsx b/frontend/src/plugins/impl/plotly/__tests__/PlotlyPlugin.test.tsx
index 21b9a62dbd..b717e0413d 100644
--- a/frontend/src/plugins/impl/plotly/__tests__/PlotlyPlugin.test.tsx
+++ b/frontend/src/plugins/impl/plotly/__tests__/PlotlyPlugin.test.tsx
@@ -112,6 +112,56 @@ describe("PlotlyPlugin", () => {
});
});
+ it("clicking a box element triggers onClick", async () => {
+ const setValue = vi.fn<Setter<unknown>>();
+
+ render(
+ <Suspense fallback={null}>
+ <PlotlyComponent
+ figure={{
+ data: [{ type: "box" }],
+ layout: {},
+ frames: null,
+ }}
+ value={undefined}
+ setValue={setValue}
+ host={document.createElement("div")}
+ config={{}}
+ />
+ </Suspense>,
+ );
+
+ await waitFor(() => {
+ expect(capturedPlotProps).not.toBeNull();
+ });
+
+ act(() => {
+ capturedPlotProps?.onClick?.({
+ points: [
+ {
+ data: { type: "box" },
+ x: "Group A",
+ y: 3,
+ pointIndex: 0,
+ pointNumber: 0,
+ curveNumber: 0,
+ },
+ ],
+ });
+ });
+
+ expect(setValue).toHaveBeenCalledTimes(1);
+ const updater = setValue.mock.calls[0][0] as (value: unknown) => unknown;
+ expect(updater({})).toEqual({
+ selections: [],
+ points: [
+ { x: "Group A", y: 3, curveNumber: 0, pointNumber: 0, pointIndex: 0 },
+ ],
+ indices: [0],
+ range: undefined,
+ });
+ });
+
it("clicking a violin element triggers onClick", async () => {
const setValue = vi.fn<Setter<unknown>>();
diff --git a/frontend/src/plugins/impl/plotly/__tests__/selection.test.ts b/frontend/src/plugins/impl/plotly/__tests__/selection.test.ts
index f9cdb3f02f..83f3c4c2e1 100644
--- a/frontend/src/plugins/impl/plotly/__tests__/selection.test.ts
+++ b/frontend/src/plugins/impl/plotly/__tests__/selection.test.ts
@@ -102,6 +102,14 @@ describe("shouldHandleClickSelection", () => {
expect(shouldHandleClickSelection([heatmapPoint])).toBe(true);
});
+ it("accepts box clicks", () => {
+ const boxPoint = createPlotDatum({
+ data: { type: "box" },
+ });
+
+ expect(shouldHandleClickSelection([boxPoint])).toBe(true);
+ });
+
it("accepts violin clicks", () => {
const violinPoint = createPlotDatum({
data: { type: "violin" },
@@ -126,6 +134,22 @@ describe("shouldHandleClickSelection", () => {
expect(shouldHandleClickSelection([linePoint])).toBe(true);
});
+ it("accepts funnel clicks", () => {
+ const funnelPoint = createPlotDatum({
+ data: { type: "funnel" },
+ });
+
+ expect(shouldHandleClickSelection([funnelPoint])).toBe(true);
+ });
+
+ it("accepts funnelarea clicks", () => {
+ const funnelAreaPoint = createPlotDatum({
+ data: { type: "funnelarea" },
+ });
+
+ expect(shouldHandleClickSelection([funnelAreaPoint])).toBe(true);
+ });
+
it("accepts waterfall clicks", () => {
const waterfallPoint = createPlotDatum({
data: { type: "waterfall" },
@@ -214,6 +238,64 @@ describe("extractPoints", () => {
expect(extractPoints([point])).toEqual([{ x: 1, y: 2, z: 3 }]);
});
+ it("returns funnel-specific fields for funnel traces", () => {
+ const point = createPlotDatum({
+ x: 1000,
+ y: "Visit",
+ label: "Visit",
+ value: 1000,
+ percentInitial: 1.0,
+ percentPrevious: 1.0,
+ percentTotal: 1.0,
+ curveNumber: 0,
+ pointIndex: 0,
+ pointNumber: 0,
+ data: { type: "funnel" },
+ });
+
+ expect(extractPoints([point])).toEqual([
+ {
+ x: 1000,
+ y: "Visit",
+ label: "Visit",
+ value: 1000,
+ percentInitial: 1.0,
+ percentPrevious: 1.0,
+ percentTotal: 1.0,
+ curveNumber: 0,
+ pointIndex: 0,
+ pointNumber: 0,
+ },
+ ]);
+ });
+
+ it("returns funnelarea-specific fields without x/y for funnelarea traces", () => {
+ const point = createPlotDatum({
+ label: "Stage A",
+ value: 500,
+ percentInitial: 0.5,
+ percentPrevious: 0.8,
+ percentTotal: 0.5,
+ curveNumber: 0,
+ pointNumber: 1,
+ x: 99,
+ y: 99,
+ data: { type: "funnelarea" },
+ });
+
+ expect(extractPoints([point])).toEqual([
+ {
+ label: "Stage A",
+ value: 500,
+ percentInitial: 0.5,
+ percentPrevious: 0.8,
+ percentTotal: 0.5,
+ curveNumber: 0,
+ pointNumber: 1,
+ },
+ ]);
+ });
+
it("returns x/y/pointIndex for waterfall clicks", () => {
const point = createPlotDatum({
x: "Revenue",
diff --git a/frontend/src/plugins/impl/plotly/selection.ts b/frontend/src/plugins/impl/plotly/selection.ts
index 853e583a09..21838ffd7f 100644
--- a/frontend/src/plugins/impl/plotly/selection.ts
+++ b/frontend/src/plugins/impl/plotly/selection.ts
@@ -24,6 +24,32 @@ const SUNBURST_DATA_KEYS: (keyof Plotly.SunburstPlotDatum)[] = [
"value",
] as const;
+// Fields emitted by go.Funnel click events: includes x/y coordinates plus
+// funnel-specific percent metrics.
+const FUNNEL_DATA_KEYS: string[] = [
+ "curveNumber",
+ "pointIndex",
+ "pointNumber",
+ "x",
+ "y",
+ "label",
+ "value",
+ "percentInitial",
+ "percentPrevious",
+ "percentTotal",
+] as const;
+
+// Fields emitted by go.FunnelArea click events: sector-based, no x/y.
+const FUNNEL_AREA_DATA_KEYS: string[] = [
+ "curveNumber",
+ "pointNumber",
+ "label",
+ "value",
+ "percentInitial",
+ "percentPrevious",
+ "percentTotal",
+] as const;
+
const LINE_CLICK_TRACE_TYPES = new Set(["scatter", "scattergl"]);
const STANDARD_POINT_KEYS: string[] = [
@@ -256,10 +282,13 @@ export function shouldHandleClickSelection(
const type = getTraceSource(point).type;
return (
type === "bar" ||
+ type === "box" ||
+ type === "funnel" ||
+ type === "funnelarea" ||
type === "heatmap" ||
type === "histogram" ||
- type === "waterfall" ||
type === "violin" ||
+ type === "waterfall" ||
isLinePoint(point)
);
});
@@ -329,13 +358,43 @@ export function extractPoints(
let parser: PlotlyTemplateParser | undefined;
return points.map((point) => {
+ const trace = getTraceSource(point);
+
+ // FunnelArea: sector-based chart with no x/y coordinates.
+ // Pick funnel-area-specific keys, then merge any hovertemplate-parsed
+ // fields (e.g. customdata columns) so user-defined fields are preserved.
+ if (trace.type === "funnelarea") {
+ const base = pick(point, FUNNEL_AREA_DATA_KEYS);
+ const ht = Array.isArray(trace.hovertemplate)
+ ? trace.hovertemplate[0]
+ : trace.hovertemplate;
+ if (!ht) {
+ return base;
+ }
+ parser = parser ? parser.update(ht) : createParser(ht);
+ return { ...base, ...parser.parse(point) };
+ }
+
+ // Funnel: bar-like chart with x/y plus per-stage percent metrics.
+ // Pick funnel-specific keys, then merge hovertemplate-parsed fields so
+ // callers get both percentInitial et al. and any user-defined columns.
+ if (trace.type === "funnel") {
+ const base = pick(point, FUNNEL_DATA_KEYS);
+ const ht = Array.isArray(trace.hovertemplate)
+ ? trace.hovertemplate[0]
+ : trace.hovertemplate;
+ if (!ht) {
+ return base;
+ }
+ parser = parser ? parser.update(ht) : createParser(ht);
+ return { ...base, ...parser.parse(point) };
+ }
+
const standardPointFields = withInferredXY(
point,
pick(point, STANDARD_POINT_KEYS),
);
- const trace = getTraceSource(point);
-
// Get the first hovertemplate
const hovertemplate = Array.isArray(trace.hovertemplate)
? trace.hovertemplate[0]
diff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.py
index 5b31d829b9..6f4847fef6 100644
--- a/marimo/_plugins/ui/_impl/plotly.py
+++ b/marimo/_plugins/ui/_impl/plotly.py
@@ -205,8 +205,9 @@ 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, violin plots, histograms, waterfall charts, treemap charts, sunburst
- charts, and heatmaps.
+ charts, bar charts, box plots, violin plots, strip charts, histograms,
+ funnel charts, funnelarea charts, waterfall charts, treemap charts,
+ sunburst charts, and heatmaps.
Examples:
```python
@@ -328,7 +329,10 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):
for trace in figure.data:
# Skip trace types handled separately in _convert_value
if getattr(trace, "type", None) in (
+ "box",
"violin",
+ "funnel",
+ "funnelarea",
"heatmap",
"bar",
"histogram",
@@ -504,18 +508,27 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):
self._figure, self._selection_data
)
- has_violin = any(
- getattr(trace, "type", None) == "violin"
+ has_funnel = any(
+ getattr(trace, "type", None) == "funnel"
for trace in self._figure.data
)
- # For violin plots: expand pointNumbers from click events into individual
- # data points, and extract underlying points from range selections.
- if has_violin:
- _append_violin_points_to_selection(
+ # For funnel charts, extract stages that fall within a range selection
+ # or pass through click data supplied by the frontend.
+ if has_funnel:
+ _append_funnel_points_to_selection(
self._figure, self._selection_data
)
+ has_funnelarea = any(
+ getattr(trace, "type", None) == "funnelarea"
+ for trace in self._figure.data
+ )
+
+ # For funnelarea, pass through the click data from the frontend.
+ if has_funnelarea:
+ _append_funnelarea_points_to_selection(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")):
@@ -535,6 +548,28 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):
self._figure, self._selection_data
)
+ has_box = any(
+ getattr(trace, "type", None) == "box"
+ for trace in self._figure.data
+ )
+
+ # For box plots (including strip charts which use go.Box traces),
+ # expand click pointNumbers and range selections into individual sample rows.
+ if has_box:
+ _append_box_points_to_selection(self._figure, self._selection_data)
+
+ has_violin = any(
+ getattr(trace, "type", None) == "violin"
+ for trace in self._figure.data
+ )
+
+ # For violin plots, expand click pointNumbers and range selections
+ # into individual sample rows.
+ if has_violin:
+ _append_violin_points_to_selection(
+ self._figure, self._selection_data
+ )
+
# Check for map-based scatter traces (scattermap, scattermapbox, scattergeo)
# These use lat/lon instead of x/y
map_scatter_types = ("scattermap", "scattermapbox", "scattergeo")
@@ -2275,6 +2310,75 @@ def _extract_waterfall_bars_fallback(
return selected
+def _append_map_scatter_points_to_selection(
+ figure: go.Figure, selection_data: dict[str, Any]
+) -> None:
+ """Extract points from map scatter traces (scattermap, scattermapbox, scattergeo).
+
+ These traces use lat/lon instead of x/y. If the frontend already sent
+ points with lat/lon, we preserve them. Otherwise, we extract from trace data.
+ """
+ existing_points = [p for p in selection_data.get("points", []) if p]
+ indices = selection_data.get("indices", [])
+
+ # If frontend already sent lat/lon points, nothing to do
+ if existing_points and any(
+ "lat" in p or "lon" in p for p in existing_points
+ ):
+ return
+
+ # Extract points from trace data using indices
+ if not indices or existing_points:
+ return
+
+ map_types = ("scattermap", "scattermapbox", "scattergeo")
+ extracted: list[dict[str, Any]] = []
+
+ for trace_idx, trace in enumerate(figure.data):
+ if getattr(trace, "type", None) not in map_types:
+ continue
+
+ lat_data = getattr(trace, "lat", None)
+ lon_data = getattr(trace, "lon", None)
+ if lat_data is None or lon_data is None:
+ continue
+
+ for idx in indices:
+ if not (0 <= idx < len(lat_data)):
+ continue
+
+ point: dict[str, Any] = {
+ "lat": lat_data[idx],
+ "lon": lon_data[idx],
+ "pointIndex": idx,
+ "curveNumber": trace_idx,
+ }
+
+ # Add optional fields
+ customdata = getattr(trace, "customdata", None)
+ if customdata is not None and idx < len(customdata):
+ point["customdata"] = customdata[idx]
+
+ text = getattr(trace, "text", None)
+ if text is not None:
+ point["text"] = text if isinstance(text, str) else text[idx]
+
+ hovertext = getattr(trace, "hovertext", None)
+ if hovertext is not None:
+ point["hovertext"] = (
+ hovertext if isinstance(hovertext, str) else hovertext[idx]
+ )
+
+ name = getattr(trace, "name", None)
+ if name:
+ point["name"] = name
+
+ extracted.append(point)
+
+ if extracted:
+ selection_data["points"] = extracted
+
+
def _append_violin_points_to_selection(
figure: go.Figure, selection_data: dict[str, Any]
) -> None:
@@ -2626,101 +2730,611 @@ def _build_waterfall_point(
return point
-def _extract_violin_points_fallback(
- figure: go.Figure, range_data: dict[str, Any]
-) -> list[dict[str, Any]]:
- """Extract violin plot data points from a selection range (pure Python).
+def _append_box_points_to_selection(
+ figure: go.Figure, selection_data: dict[str, Any]
+) -> None:
+ """Expand box plot selections into individual underlying data points.
- Filters by both the category axis (which violin group falls inside the
- selection box) and the value axis (which individual sample values fall
- inside the selection box). Used when numpy is unavailable.
- """
- x_range = range_data.get("x")
- y_range = range_data.get("y")
+ Handles three cases:
+ - Range/lasso with individual points already sent by Plotly (``boxpoints``
+ enabled): Plotly already delivered the right individual data points via
+ the ``onSelected`` event; pass them through unchanged.
+ - Range/lasso without individual points (``boxpoints`` disabled): extract
+ all underlying sample rows whose category position overlaps the selection
+ range from the figure data.
+ - Click events (no range/lasso): the frontend sends ``pointNumbers`` for
+ the clicked box/whisker element; expand these into one dict per sample
+ row so Python callers get row-level data.
- selected: list[dict[str, Any]] = []
+ This also handles strip charts (``px.strip()``) which are rendered as
+ ``go.Box`` traces with ``boxpoints="all"`` and transparent fills.
+ """
+ all_points = cast(list[dict[str, Any]], selection_data.get("points", []))
+ all_indices = cast(list[Any], selection_data.get("indices", []))
- for trace_idx, trace in enumerate(figure.data):
- if getattr(trace, "type", None) != "violin":
- continue
+ box_curve_numbers = {
+ trace_idx
+ for trace_idx, trace in enumerate(figure.data)
+ if getattr(trace, "type", None) == "box"
+ }
+ if not box_curve_numbers:
+ return
- orientation = getattr(trace, "orientation", "v") or "v"
- if orientation == "h":
- cat_range = y_range
- val_range = x_range
- cat_data = getattr(trace, "y", None)
- val_data = getattr(trace, "x", None)
- else:
- cat_range = x_range
- val_range = y_range
- cat_data = getattr(trace, "x", None)
- val_data = getattr(trace, "y", None)
+ range_value = selection_data.get("range")
+ lasso_value = selection_data.get("lasso")
- if val_data is None:
- continue
+ # --- Range/lasso selection path (onSelected event) ---
+ if isinstance(range_value, dict) or isinstance(lasso_value, dict):
+ # Partition existing points by whether they come from a box trace.
+ existing_box = [
+ p
+ for p in all_points
+ if p and p.get("curveNumber") in box_curve_numbers
+ ]
+ existing_non_box = [
+ p
+ for p in all_points
+ if p and p.get("curveNumber") not in box_curve_numbers
+ ]
+ existing_non_box_indices = [
+ idx
+ for idx, p in zip(all_indices, all_points, strict=False)
+ if p and p.get("curveNumber") not in box_curve_numbers
+ ]
- n = len(val_data)
- if n == 0:
- continue
+ if existing_box:
+ # Plotly already sent the individual selected data points because
+ # boxpoints is enabled. Use them as-is; do NOT re-extract from
+ # the range (which can fail on categorical axes and would discard
+ # richer hovertemplate fields like sample_id).
+ clean_points = existing_box + existing_non_box
+ # Preserve incoming indices from the frontend payload rather than
+ # recomputing from pointIndex only — Plotly may send pointNumber
+ # instead. Map each point object to its original index by identity.
+ incoming_index_map = {
+ id(p): idx
+ for idx, p in zip(all_indices, all_points, strict=False)
+ if p
+ }
+ 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:
+ pid = _get_selection_point_id(p)
+ if pid is not None:
+ clean_indices.append(pid[1])
+ selection_data["points"] = clean_points
+ selection_data["indices"] = clean_indices
+ return
- if cat_data is None:
- cat_list: list[Any] = [getattr(trace, "name", trace_idx)] * n
- elif hasattr(cat_data, "__len__") and len(cat_data) == n:
- cat_list = list(cat_data)
- else:
- scalar = (
- cat_data[0] if hasattr(cat_data, "__getitem__") else cat_data
- )
- cat_list = [scalar] * n
+ # No individual points from Plotly → boxpoints is disabled.
+ # Only extract from a range selection; lasso events without a range
+ # dict would pass an empty range_dict and incorrectly select all rows.
+ if not isinstance(range_value, dict):
+ return
+ box_points = _extract_box_points_from_range(
+ figure, cast(dict[str, Any], range_value)
+ )
- if cat_range:
- cat_min, cat_max = min(cat_range), max(cat_range)
- seen_order: dict[Any, int] = {}
- for v in cat_list:
- try:
- if v not in seen_order:
- seen_order[v] = len(seen_order)
- except TypeError:
- pass
+ if box_points or existing_non_box:
+ seen: set[tuple[int, int]] = set()
+ merged_points: list[dict[str, Any]] = []
+ merged_indices: list[int] = []
- for i, cat_val in enumerate(cat_list):
- if cat_range:
- 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:
- try:
- pos = seen_order.get(cat_val)
- except TypeError:
- continue
- if pos is None:
- continue
- if not (cat_max > pos - 0.5 and cat_min < pos + 0.5):
+ for idx, point in zip(
+ existing_non_box_indices, existing_non_box, strict=False
+ ):
+ 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 isinstance(idx, int):
+ merged_indices.append(idx)
+ elif point_id is not None:
+ merged_indices.append(point_id[1])
- if val_range:
- val_min_f = float(min(val_range))
- val_max_f = float(max(val_range))
- try:
- val_f = float(val_data[i])
- if not (val_min_f <= val_f <= val_max_f):
+ for point in box_points:
+ point_id = _get_selection_point_id(point)
+ if point_id is not None:
+ if point_id in seen:
continue
- except (TypeError, ValueError):
- pass # non-numeric value; skip value filtering
-
- sample = _build_violin_sample_point(trace, trace_idx, i)
- if sample is not None:
- selected.append(sample)
+ seen.add(point_id)
+ merged_indices.append(point_id[1])
+ merged_points.append(point)
- return selected
+ selection_data["points"] = merged_points
+ selection_data["indices"] = merged_indices
+ else:
+ # No box points and no non-box points in range: clear any frontend
+ # placeholder dicts that may have leaked into points/indices.
+ selection_data["points"] = []
+ selection_data["indices"] = []
+ return
+ # --- Click event path ---
+ # Box/whisker clicks include pointNumbers (all raw-data indices in the group).
+ # Expand each such click-point into individual sample rows.
+ has_box_click_with_numbers = any(
+ p.get("curveNumber") in box_curve_numbers and "pointNumbers" in p
+ for p in all_points
+ if p
+ )
+ if not has_box_click_with_numbers:
+ return
-def _build_violin_sample_point(
+ expanded_points: list[dict[str, Any]] = []
+ expanded_indices: list[int] = []
+ seen_ids: set[tuple[int, int]] = set()
+
+ for point in all_points:
+ if not point:
+ continue
+
+ curve_number = point.get("curveNumber")
+
+ # Passthrough non-box points unchanged
+ if curve_number not in box_curve_numbers:
+ point_id = _get_selection_point_id(point)
+ if point_id is not None and point_id in seen_ids:
+ continue
+ if point_id is not None:
+ seen_ids.add(point_id)
+ expanded_indices.append(point_id[1])
+ expanded_points.append(point)
+ continue
+
+ point_numbers = point.get("pointNumbers")
+ if not isinstance(point_numbers, list) or not (
+ 0 <= cast(int, curve_number) < len(figure.data)
+ ):
+ # No pointNumbers – pass through as-is
+ point_id = _get_selection_point_id(point)
+ if point_id is not None:
+ expanded_indices.append(point_id[1])
+ expanded_points.append(point)
+ continue
+
+ trace = figure.data[cast(int, curve_number)]
+ for raw_idx in point_numbers:
+ if not isinstance(raw_idx, int):
+ continue
+ sample = _build_box_sample_point(
+ trace, cast(int, curve_number), raw_idx
+ )
+ if sample is None:
+ continue
+ point_id = _get_selection_point_id(sample)
+ if point_id is not None and point_id in seen_ids:
+ continue
+ if point_id is not None:
+ seen_ids.add(point_id)
+ expanded_points.append(sample)
+ expanded_indices.append(raw_idx)
+
+ selection_data["points"] = expanded_points
+ selection_data["indices"] = expanded_indices
+
+
+def _build_global_category_order(
+ figure: go.Figure, trace_type: str
+) -> dict[Any, float]:
+ """Build a category-to-float-position mapping across all traces of the given type.
+
+ Using per-trace first-seen order causes the same category to get different
+ numeric positions in different traces (common with Plotly Express faceting/
+ coloring). A single pre-built order from all traces ensures the positions
+ are consistent with the axis-global ordering Plotly uses for range values.
+ """
+ order: dict[Any, float] = {}
+ for trace_idx, trace in enumerate(figure.data):
+ if getattr(trace, "type", None) != trace_type:
+ continue
+ orientation = getattr(trace, "orientation", "v") or "v"
+ cat_data = getattr(trace, "y" if orientation == "h" else "x", None)
+ val_data = getattr(trace, "x" if orientation == "h" else "y", None)
+ if val_data is None:
+ continue
+ n = len(val_data) if hasattr(val_data, "__len__") else 0
+ if n == 0:
+ continue
+ if cat_data is None:
+ cats: list[Any] = [getattr(trace, "name", None) or trace_idx]
+ elif isinstance(cat_data, (str, bytes)):
+ cats = [cat_data]
+ elif hasattr(cat_data, "__len__") and len(cat_data) == n:
+ cats = list(cat_data)
+ else:
+ try:
+ cats = [cat_data[0]]
+ except (TypeError, IndexError, KeyError):
+ cats = [cat_data]
+ for v in cats:
+ try:
+ if v not in order:
+ order[v] = float(len(order))
+ except TypeError:
+ pass
+ return order
+
+
+def _extract_box_points_from_range(
+ figure: go.Figure, range_data: dict[str, Any]
+) -> list[dict[str, Any]]:
+ """Extract box plot underlying data points that fall within a selection range.
+
+ For each box trace the category position (x for vertical, y for horizontal)
+ is compared against the selection range. Only samples whose value coordinate
+ also falls within the selection rectangle are returned.
+ """
+ if DependencyManager.numpy.has():
+ return _extract_box_points_numpy(figure, range_data)
+ return _extract_box_points_fallback(figure, range_data)
+
+
+def _extract_box_points_numpy(
+ figure: go.Figure, range_data: dict[str, Any]
+) -> list[dict[str, Any]]:
+ """Extract box plot data points from a selection range using numpy."""
+ import numpy as np
+
+ x_range = range_data.get("x")
+ y_range = range_data.get("y")
+
+ selected: list[dict[str, Any]] = []
+
+ # Build global category order once so that the same category gets the same
+ # numeric position across all traces (px faceting can produce traces with
+ # different/missing categories, making per-trace first-seen order wrong).
+ global_cat_order = _build_global_category_order(figure, "box")
+
+ for trace_idx, trace in enumerate(figure.data):
+ if getattr(trace, "type", None) != "box":
+ continue
+
+ orientation = getattr(trace, "orientation", "v") or "v"
+ # For vertical boxes: x is the category axis, y holds data values.
+ # For horizontal boxes: y is the category axis, x holds data values.
+ if orientation == "h":
+ cat_range = y_range
+ val_range = x_range
+ cat_data = getattr(trace, "y", None)
+ val_data = getattr(trace, "x", None)
+ else:
+ cat_range = x_range
+ val_range = y_range
+ cat_data = getattr(trace, "x", None)
+ val_data = getattr(trace, "y", None)
+
+ if val_data is None:
+ continue
+
+ val_arr = np.asarray(val_data)
+ n = len(val_arr)
+ if n == 0:
+ continue
+
+ # Build per-sample category array. A box trace can have:
+ # - cat_data as an array (one category per sample, same length as val)
+ # - cat_data as a scalar / None (all samples share one category)
+ if cat_data is None:
+ # No explicit category; Plotly uses the trace name / index.
+ cat_arr: list[Any] = [getattr(trace, "name", trace_idx)] * n
+ else:
+ cat_arr_raw = np.asarray(cat_data)
+ if cat_arr_raw.ndim == 0 or len(cat_arr_raw) != n:
+ # Scalar category
+ cat_val = (
+ cat_arr_raw.item()
+ if hasattr(cat_arr_raw, "item") and cat_arr_raw.ndim == 0
+ else (cat_arr_raw[0] if len(cat_arr_raw) > 0 else None)
+ )
+ cat_arr = [cat_val] * n
+ else:
+ cat_arr = cat_arr_raw.tolist()
+
+ # --- Category filter ---
+ if cat_range:
+ cat_min, cat_max = min(cat_range), max(cat_range)
+ cat_np = np.asarray(cat_arr)
+ cat_is_orderable = _is_orderable_axis(cat_np, cat_min)
+
+ if cat_is_orderable:
+ cat_min_p = _parse_datetime_bound(cat_min)
+ cat_max_p = _parse_datetime_bound(cat_max)
+ cat_mask = np.array(
+ [
+ cat_min_p <= _parse_datetime_bound(v) <= cat_max_p
+ if _is_orderable_value(v)
+ else False
+ for v in cat_arr
+ ]
+ )
+ else:
+ # Use the global order so positions are consistent across traces
+ positions = np.array(
+ [
+ _safe_category_get(global_cat_order, v, -1)
+ for v in cat_arr
+ ],
+ dtype=np.float64,
+ )
+ cat_mask = (cat_max > positions - 0.5) & (
+ cat_min < positions + 0.5
+ )
+ else:
+ cat_mask = np.ones(n, dtype=bool)
+
+ # --- Value filter ---
+ # Exclude samples whose value coordinate falls outside the selection
+ # rectangle (category match alone is insufficient).
+ if val_range:
+ val_min_p = _parse_datetime_bound(min(val_range))
+ val_max_p = _parse_datetime_bound(max(val_range))
+ val_mask = np.array(
+ [
+ val_min_p <= parsed_v <= val_max_p
+ if _is_orderable_value(parsed_v)
+ else False
+ for parsed_v in (
+ _parse_datetime_bound(v) for v in val_arr.tolist()
+ )
+ ]
+ )
+ cat_mask = cat_mask & val_mask
+
+ selected_indices = np.where(cat_mask)[0]
+ for i in selected_indices:
+ sample = _build_box_sample_point(trace, trace_idx, int(i))
+ if sample is not None:
+ selected.append(sample)
+
+ return selected
+
+
+def _extract_box_points_fallback(
+ figure: go.Figure, range_data: dict[str, Any]
+) -> list[dict[str, Any]]:
+ """Extract box plot data points from a selection range (pure Python)."""
+ x_range = range_data.get("x")
+ y_range = range_data.get("y")
+
+ selected: list[dict[str, Any]] = []
+
+ # Global category order for consistent positions across all box traces
+ global_cat_order = _build_global_category_order(figure, "box")
+
+ for trace_idx, trace in enumerate(figure.data):
+ if getattr(trace, "type", None) != "box":
+ continue
+
+ orientation = getattr(trace, "orientation", "v") or "v"
+ if orientation == "h":
+ cat_range = y_range
+ val_range = x_range
+ cat_data = getattr(trace, "y", None)
+ val_data = getattr(trace, "x", None)
+ else:
+ cat_range = x_range
+ val_range = y_range
+ cat_data = getattr(trace, "x", None)
+ val_data = getattr(trace, "y", None)
+
+ if val_data is None:
+ continue
+
+ n = len(val_data)
+ if n == 0:
+ continue
+
+ # Build per-sample category list
+ if cat_data is None:
+ cat_list: list[Any] = [getattr(trace, "name", trace_idx)] * n
+ elif isinstance(cat_data, (str, bytes)):
+ cat_list = [cat_data] * n
+ elif hasattr(cat_data, "__len__") and len(cat_data) == n:
+ cat_list = list(cat_data)
+ else:
+ try:
+ scalar: Any = cat_data[0]
+ except (TypeError, IndexError, KeyError):
+ scalar = cat_data
+ cat_list = [scalar] * n
+
+ if cat_range:
+ cat_min, cat_max = min(cat_range), max(cat_range)
+
+ if val_range:
+ val_min_p = _parse_datetime_bound(min(val_range))
+ val_max_p = _parse_datetime_bound(max(val_range))
+
+ for i, cat_val in enumerate(cat_list):
+ # --- Category filter ---
+ if cat_range:
+ 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:
+ pos = _safe_category_get(global_cat_order, cat_val, -1)
+ if pos < 0:
+ continue
+ if not (cat_max > pos - 0.5 and cat_min < pos + 0.5):
+ continue
+
+ # --- Value filter ---
+ if val_range:
+ val_v = (
+ val_data[i] if hasattr(val_data, "__getitem__") else None
+ )
+ val_v_p = _parse_datetime_bound(val_v)
+ if val_v is None or not (
+ _is_orderable_value(val_v_p)
+ and val_min_p <= val_v_p <= val_max_p
+ ):
+ continue
+
+ sample = _build_box_sample_point(trace, trace_idx, i)
+ if sample is not None:
+ selected.append(sample)
+
+ return selected
+
+
+def _build_box_sample_point(
+ trace: Any, trace_idx: int, point_idx: int
+) -> dict[str, Any] | None:
+ """Build a row-level selection payload for a single box plot data point."""
+ orientation = getattr(trace, "orientation", "v") or "v"
+ if orientation == "h":
+ val_key, cat_key = "x", "y"
+ else:
+ val_key, cat_key = "y", "x"
+
+ val_value = _get_indexed_value(getattr(trace, val_key, None), point_idx)
+ if val_value is None:
+ return None
+
+ cat_source = getattr(trace, cat_key, None)
+ if cat_source is None:
+ cat_value: Any = getattr(trace, "name", None) or trace_idx
+ elif isinstance(cat_source, (str, bytes)):
+ cat_value = cat_source
+ else:
+ try:
+ cat_len = (
+ len(cat_source) if hasattr(cat_source, "__len__") else None
+ )
+ except TypeError:
+ cat_len = None
+ if cat_len == len(getattr(trace, val_key, [])):
+ cat_value = _get_indexed_value(cat_source, point_idx)
+ else:
+ indexed = _get_indexed_value(cat_source, 0)
+ cat_value = indexed if indexed is not None else cat_source
+
+ point: dict[str, Any] = {
+ val_key: val_value,
+ "pointIndex": point_idx,
+ "curveNumber": trace_idx,
+ }
+ if cat_value is not None:
+ point[cat_key] = cat_value
+
+ 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 _extract_violin_points_fallback(
+ figure: go.Figure, range_data: dict[str, Any]
+) -> list[dict[str, Any]]:
+ """Extract violin plot data points from a selection range (pure Python).
+
+ Filters by both the category axis (which violin group falls inside the
+ selection box) and the value axis (which individual sample values fall
+ inside the selection box). Used when numpy is unavailable.
+ """
+ x_range = range_data.get("x")
+ y_range = range_data.get("y")
+
+ selected: list[dict[str, Any]] = []
+
+ for trace_idx, trace in enumerate(figure.data):
+ if getattr(trace, "type", None) != "violin":
+ continue
+
+ orientation = getattr(trace, "orientation", "v") or "v"
+ if orientation == "h":
+ cat_range = y_range
+ val_range = x_range
+ cat_data = getattr(trace, "y", None)
+ val_data = getattr(trace, "x", None)
+ else:
+ cat_range = x_range
+ val_range = y_range
+ cat_data = getattr(trace, "x", None)
+ val_data = getattr(trace, "y", None)
+
+ if val_data is None:
+ continue
+
+ n = len(val_data)
+ if n == 0:
+ continue
+
+ if cat_data is None:
+ cat_list: list[Any] = [getattr(trace, "name", trace_idx)] * n
+ elif hasattr(cat_data, "__len__") and len(cat_data) == n:
+ cat_list = list(cat_data)
+ else:
+ scalar = (
+ cat_data[0] if hasattr(cat_data, "__getitem__") else cat_data
+ )
+ cat_list = [scalar] * n
+
+ if cat_range:
+ cat_min, cat_max = min(cat_range), max(cat_range)
+ seen_order: dict[Any, int] = {}
+ for v in cat_list:
+ try:
+ if v not in seen_order:
+ seen_order[v] = len(seen_order)
+ except TypeError:
+ pass
+
+ for i, cat_val in enumerate(cat_list):
+ if cat_range:
+ 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:
+ try:
+ pos = seen_order.get(cat_val)
+ except TypeError:
+ continue
+ if pos is None:
+ continue
+ if not (cat_max > pos - 0.5 and cat_min < pos + 0.5):
+ continue
+
+ if val_range:
+ val_min_f = float(min(val_range))
+ val_max_f = float(max(val_range))
+ try:
+ val_f = float(val_data[i])
+ if not (val_min_f <= val_f <= val_max_f):
+ continue
+ except (TypeError, ValueError):
+ pass # non-numeric value; skip value filtering
+
+ sample = _build_violin_sample_point(trace, trace_idx, i)
+ if sample is not None:
+ selected.append(sample)
+
+ return selected
+
+
+def _build_violin_sample_point(
trace: Any, trace_idx: int, point_idx: int
) -> dict[str, Any] | None:
"""Build a row-level selection payload for a single violin plot data point."""
@@ -2773,70 +3387,320 @@ def _build_violin_sample_point(
return point
-def _append_map_scatter_points_to_selection(
+def _append_funnel_points_to_selection(
figure: go.Figure, selection_data: dict[str, Any]
) -> None:
- """Extract points from map scatter traces (scattermap, scattermapbox, scattergeo).
+ """Handle selection data for go.Funnel traces.
- These traces use lat/lon instead of x/y. If the frontend already sent
- points with lat/lon, we preserve them. Otherwise, we extract from trace data.
+ Two cases:
+ 1. Range selection (dragmode="select"): extract funnel stages whose
+ position and value overlap the selection rectangle.
+ 2. Click selection: points are already populated by the frontend with
+ x, y, label, value, and percent metrics — pass them through after
+ filtering empty placeholders and re-syncing indices.
"""
- existing_points = [p for p in selection_data.get("points", []) if p]
- indices = selection_data.get("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 frontend already sent lat/lon points, nothing to do
- if existing_points and any(
- "lat" in p or "lon" in p for p in existing_points
- ):
- return
+ if isinstance(range_value, dict):
+ # Range selection: extract funnel stages within the rectangle.
+ funnel_items = _extract_funnel_stages_from_range(
+ figure, cast(dict[str, Any], range_value)
+ )
+ has_real_points = any(all_points)
+ if not has_real_points and not funnel_items:
+ selection_data["points"] = []
+ selection_data["indices"] = []
+ return
- # Extract points from trace data using indices
- if not indices or existing_points:
- return
+ seen: set[tuple[int, int]] = set()
+ merged_points: list[dict[str, Any]] = []
+ merged_indices: list[int] = []
- map_types = ("scattermap", "scattermapbox", "scattergeo")
- extracted: list[dict[str, Any]] = []
+ 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 funnel_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 selection: clean up empty-dict placeholders from the frontend.
+ clean_points = [p for p in all_points if p]
+ if not clean_points:
+ selection_data["points"] = []
+ selection_data["indices"] = []
+ return
+ # Re-sync indices: prefer what the frontend sent, fall back to pointIndex.
+ incoming_index_map = {
+ id(p): idx
+ for idx, p in zip(all_indices, all_points, strict=False)
+ 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_funnel_stages_from_range(
+ figure: go.Figure, range_data: dict[str, Any]
+) -> list[dict[str, Any]]:
+ """Extract funnel stages that fall within a box-selection range.
+
+ go.Funnel is structurally identical to a horizontal/vertical bar chart:
+ default orientation has x = numeric values, y = categorical stage labels.
+ A stage is selected when its category position is within the y-range AND
+ its value bar (from 0 to x) overlaps the x-range.
+ """
+ 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_funnel_stages_numpy(figure, x_min, x_max, y_min, y_max)
+ return _extract_funnel_stages_fallback(figure, x_min, x_max, y_min, y_max)
+
+
+def _extract_funnel_stages_numpy(
+ figure: go.Figure,
+ x_min: float,
+ x_max: float,
+ y_min: float,
+ y_max: float,
+) -> list[dict[str, Any]]:
+ """Extract funnel stages 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) not in map_types:
+ if getattr(trace, "type", None) != "funnel":
continue
- lat_data = getattr(trace, "lat", None)
- lon_data = getattr(trace, "lon", None)
- if lat_data is None or lon_data is None:
+ x_data = getattr(trace, "x", None)
+ y_data = getattr(trace, "y", None)
+ if x_data is None or y_data is None:
continue
- for idx in indices:
- if not (0 <= idx < len(lat_data)):
- continue
+ orientation = getattr(trace, "orientation", "h") or "h"
+ if orientation == "h":
+ val_data = x_data
+ cat_min, cat_max = y_min, y_max
+ val_min, val_max = x_min, x_max
+ else:
+ val_data = y_data
+ cat_min, cat_max = x_min, x_max
+ val_min, val_max = y_min, y_max
- point: dict[str, Any] = {
- "lat": lat_data[idx],
- "lon": lon_data[idx],
- "pointIndex": idx,
- "curveNumber": trace_idx,
- }
+ n = len(val_data) if hasattr(val_data, "__len__") else 0
+ if n == 0:
+ continue
- # Add optional fields
- customdata = getattr(trace, "customdata", None)
- if customdata is not None and idx < len(customdata):
- point["customdata"] = customdata[idx]
+ try:
+ val_arr = np.asarray(val_data, dtype=np.float64)
+ except (TypeError, ValueError):
+ # Non-numeric entries (e.g. None) in val_data — fall back to the
+ # element-wise path so that non-numeric stages are silently skipped.
+ numeric_val_min = _to_numeric_bar_value(val_min)
+ for i, val in enumerate(val_data):
+ if not (cat_max > i - 0.5 and cat_min < i + 0.5):
+ continue
+ numeric_val = _to_numeric_bar_value(val)
+ if numeric_val is None or (
+ numeric_val_min is not None
+ and numeric_val < numeric_val_min
+ ):
+ continue
+ selected.append(
+ _build_funnel_stage_point(
+ trace, trace_idx, i, x_data, y_data
+ )
+ )
+ continue
- text = getattr(trace, "text", None)
- if text is not None:
- point["text"] = text if isinstance(text, str) else text[idx]
+ # Category axis: each stage occupies position index ± 0.5
+ cat_positions = np.arange(n, dtype=np.float64)
+ cat_mask = (cat_max > cat_positions - 0.5) & (
+ cat_min < cat_positions + 0.5
+ )
- hovertext = getattr(trace, "hovertext", None)
- if hovertext is not None:
- point["hovertext"] = (
- hovertext if isinstance(hovertext, str) else hovertext[idx]
+ # Value axis: funnel bar spans [0, v]; selected if bar overlaps [val_min, val_max].
+ # Overlap condition: val_min <= v AND val_max > 0
+ if val_max <= 0:
+ continue # selection is entirely in negative space — no overlap possible
+ val_mask = val_arr >= val_min
+
+ mask = cat_mask & val_mask
+ for i in np.where(mask)[0]:
+ selected.append(
+ _build_funnel_stage_point(
+ trace, trace_idx, int(i), x_data, y_data
)
+ )
- name = getattr(trace, "name", None)
- if name:
- point["name"] = name
+ return selected
- extracted.append(point)
- if extracted:
- selection_data["points"] = extracted
+def _extract_funnel_stages_fallback(
+ figure: go.Figure,
+ x_min: float,
+ x_max: float,
+ y_min: float,
+ y_max: float,
+) -> list[dict[str, Any]]:
+ """Extract funnel stages 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) != "funnel":
+ continue
+
+ x_data = getattr(trace, "x", None)
+ y_data = getattr(trace, "y", None)
+ if x_data is None or y_data is None:
+ continue
+
+ orientation = getattr(trace, "orientation", "h") or "h"
+ if orientation == "h":
+ val_data = x_data
+ cat_min, cat_max = y_min, y_max
+ val_min, val_max = x_min, x_max
+ else:
+ val_data = y_data
+ cat_min, cat_max = x_min, x_max
+ val_min, val_max = y_min, y_max
+
+ # Value axis: funnel bar spans [0, v]; no overlap possible if val_max ≤ 0
+ numeric_val_max = _to_numeric_bar_value(val_max)
+ if numeric_val_max is None or numeric_val_max <= 0:
+ continue
+
+ numeric_val_min = _to_numeric_bar_value(val_min)
+
+ for i, val in enumerate(val_data):
+ # Category check: stage i spans (i-0.5, i+0.5)
+ cat_in_range = not (cat_max <= i - 0.5 or cat_min >= i + 0.5)
+ if not cat_in_range:
+ continue
+
+ # Value check: bar [0, val] overlaps selection [val_min, val_max]
+ # Overlap: val_min <= val (bar reaches into or touches selection range)
+ numeric_val = _to_numeric_bar_value(val)
+ if numeric_val is None or (
+ numeric_val_min is not None and numeric_val < numeric_val_min
+ ):
+ continue
+
+ selected.append(
+ _build_funnel_stage_point(trace, trace_idx, i, x_data, y_data)
+ )
+
+ return selected
+
+
+def _build_funnel_stage_point(
+ trace: Any,
+ trace_idx: int,
+ point_idx: int,
+ x_data: Any,
+ y_data: Any,
+) -> dict[str, Any]:
+ """Build a selection point dict for a single funnel stage."""
+ x_val = _get_indexed_value(x_data, point_idx)
+ y_val = _get_indexed_value(y_data, point_idx)
+ # For horizontal funnels (default): y=category label, x=numeric value.
+ # For vertical funnels: x=category label, y=numeric value.
+ orientation = getattr(trace, "orientation", "h")
+ if orientation == "v":
+ label = x_val
+ value = y_val
+ else:
+ label = y_val
+ value = x_val
+ point: dict[str, Any] = {
+ "x": x_val,
+ "y": y_val,
+ "label": label,
+ "value": value,
+ "curveNumber": trace_idx,
+ "pointIndex": point_idx,
+ "pointNumber": point_idx,
+ }
+ for field in ("customdata", "text", "hovertext"):
+ val = _get_indexed_value(getattr(trace, field, None), point_idx)
+ if val is not None:
+ point[field] = val
+ name = getattr(trace, "name", None)
+ if name:
+ point["name"] = name
+ return point
+
+
+def _append_funnelarea_points_to_selection(
+ selection_data: dict[str, Any],
+) -> None:
+ """Pass through click data for go.FunnelArea traces.
+
+ FunnelArea is a sector-based chart (like sunburst) with no x/y axes, so
+ range/lasso selection is not applicable. The frontend already populates
+ selection_data with label, value, and percent metrics on click; this
+ function only strips empty-dict placeholders and syncs indices.
+ """
+ all_points = cast(list[dict[str, Any]], selection_data.get("points", []))
+ all_indices = cast(list[Any], selection_data.get("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, strict=False)
+ 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("pointNumber")
+ if isinstance(pi, int):
+ clean_indices.append(pi)
+ selection_data["points"] = clean_points
+ selection_data["indices"] = clean_indices
diff --git a/tests/_plugins/ui/_impl/test_plotly.py b/tests/_plugins/ui/_impl/test_plotly.py
index e54191b0f4..56fa0d969c 100644
--- a/tests/_plugins/ui/_impl/test_plotly.py
+++ b/tests/_plugins/ui/_impl/test_plotly.py
@@ -19,6 +19,10 @@ from marimo._plugins.ui._impl.plotly import (
_compute_waterfall_bar_extents,
_extract_bars_fallback,
_extract_bars_numpy,
+ _extract_box_points_fallback,
+ _extract_box_points_numpy,
+ _extract_funnel_stages_fallback,
+ _extract_funnel_stages_numpy,
_extract_heatmap_cells_fallback,
_extract_heatmap_cells_numpy,
_extract_histogram_points_fallback,
@@ -3019,6 +3023,638 @@ def test_bar_chart_preserves_indices_when_empty_points_exist() -> None:
assert plot.indices == [1]
+# ============================================================================
+# Box Plot Tests
+# ============================================================================
+
+
+def test_box_plot_basic_creation() -> None:
+ """Test that a box plot can be created and has empty initial selection."""
+ fig = go.Figure(data=go.Box(y=[1, 2, 3, 4, 5], name="Group A"))
+ plot = plotly(fig)
+
+ assert plot is not None
+ assert plot.value == []
+ assert plot.ranges == {}
+ assert plot.points == []
+ assert plot.indices == []
+
+
+def test_box_plot_click_expands_point_numbers() -> None:
+ """Clicking a box/whisker sends pointNumbers; Python expands them to rows."""
+ fig = go.Figure()
+ fig.add_trace(go.Box(x=["A", "A", "A", "B", "B"], y=[1, 2, 3, 4, 5]))
+ plot = plotly(fig)
+
+ selection = {
+ "points": [
+ {
+ "x": "A",
+ "y": 2,
+ "pointIndex": 0,
+ "pointNumbers": [0, 1, 2],
+ "curveNumber": 0,
+ }
+ ],
+ "indices": [0],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 3
+ assert all(r["x"] == "A" for r in result)
+ assert [r["y"] for r in result] == [1, 2, 3]
+ assert [r["pointIndex"] for r in result] == [0, 1, 2]
+ assert all(r["curveNumber"] == 0 for r in result)
+
+
+def test_box_plot_click_without_point_numbers_passthrough() -> None:
+ """When pointNumbers is absent (individual boxpoint click), pass through."""
+ fig = go.Figure()
+ fig.add_trace(go.Box(x=["A", "A", "B"], y=[1, 2, 3]))
+ plot = plotly(fig)
+
+ selection = {
+ "points": [{"x": "A", "y": 1, "pointIndex": 0, "curveNumber": 0}],
+ "indices": [0],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 1
+ assert result[0]["pointIndex"] == 0
+
+
+def test_extract_box_points_numpy_categorical() -> None:
+ """Numpy path: select category 'A' by index position."""
+ fig = go.Figure()
+ fig.add_trace(go.Box(x=["A", "A", "A", "B", "B"], y=[1, 2, 3, 4, 5]))
+
+ range_data = {"x": [-0.4, 0.4], "y": [0, 10]}
+ result = _extract_box_points_numpy(fig, range_data)
+
+ assert len(result) == 3
+ assert all(r["x"] == "A" for r in result)
+ assert [r["y"] for r in result] == [1, 2, 3]
+ assert [r["pointIndex"] for r in result] == [0, 1, 2]
+ assert all(r["curveNumber"] == 0 for r in result)
+
+
+def test_extract_box_points_fallback_categorical() -> None:
+ """Pure-Python path: mirrors numpy categorical selection."""
+ fig = go.Figure()
+ fig.add_trace(go.Box(x=["A", "A", "A", "B", "B"], y=[1, 2, 3, 4, 5]))
+
+ range_data = {"x": [-0.4, 0.4], "y": [0, 10]}
+ result = _extract_box_points_fallback(fig, range_data)
+
+ assert len(result) == 3
+ assert all(r["x"] == "A" for r in result)
+ assert [r["y"] for r in result] == [1, 2, 3]
+
+
+def test_extract_box_points_numpy_all_categories() -> None:
+ """Select all categories when x range covers the full axis."""
+ fig = go.Figure()
+ fig.add_trace(go.Box(x=["A", "A", "B", "B"], y=[1, 2, 3, 4]))
+
+ range_data = {"x": [-1, 5], "y": [0, 10]}
+ result = _extract_box_points_numpy(fig, range_data)
+
+ assert len(result) == 4
+
+
+def test_extract_box_points_numpy_second_category() -> None:
+ """Select only the second category; numpy and fallback agree."""
+ fig = go.Figure()
+ fig.add_trace(go.Box(x=["A", "A", "B", "B"], y=[1, 2, 3, 4]))
+
+ range_data = {"x": [0.6, 1.4], "y": [0, 10]}
+ result_numpy = _extract_box_points_numpy(fig, range_data)
+ result_fallback = _extract_box_points_fallback(fig, range_data)
+
+ assert len(result_numpy) == 2
+ assert all(r["x"] == "B" for r in result_numpy)
+ assert result_numpy == result_fallback
+
+
+def test_box_plot_range_selection_with_individual_points() -> None:
+ """When Plotly sends individual points via onSelected, pass them through."""
+ fig = go.Figure()
+ fig.add_trace(go.Box(x=["A", "A", "B", "B"], y=[10, 20, 30, 40]))
+ plot = plotly(fig)
+
+ selection: dict[str, Any] = {
+ "range": {"x": [-0.4, 0.4], "y": [0, 50]},
+ "points": [
+ {"x": "A", "y": 10, "pointIndex": 0, "curveNumber": 0},
+ {"x": "A", "y": 20, "pointIndex": 1, "curveNumber": 0},
+ ],
+ "indices": [0, 1],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 2
+ assert all(r["x"] == "A" for r in result)
+ assert {r["y"] for r in result} == {10, 20}
+ assert {r["pointIndex"] for r in result} == {0, 1}
+
+
+def test_box_plot_range_selection_fallback_no_points() -> None:
+ """When no individual points are sent (boxpoints disabled), extract from range."""
+ fig = go.Figure()
+ fig.add_trace(go.Box(x=["A", "A", "B", "B"], y=[10, 20, 30, 40]))
+ plot = plotly(fig)
+
+ selection: dict[str, Any] = {
+ "range": {"x": [-0.4, 0.4], "y": [0, 50]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 2
+ assert all(r["x"] == "A" for r in result)
+ assert {r["y"] for r in result} == {10, 20}
+
+
+def test_box_plot_no_category_data() -> None:
+ """Box trace without explicit x uses trace name as category."""
+ fig = go.Figure()
+ fig.add_trace(go.Box(y=[5, 10, 15], name="Group X"))
+ plot = plotly(fig)
+
+ selection: dict[str, Any] = {
+ "range": {"y": [0, 20]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 3
+ assert all(r.get("x") == "Group X" for r in result)
+
+
+def test_box_plot_horizontal_orientation() -> None:
+ """Horizontal box plots swap x/y roles for category and value."""
+ fig = go.Figure()
+ fig.add_trace(
+ go.Box(x=[1, 2, 3, 4, 5], y=["A", "A", "A", "B", "B"], orientation="h")
+ )
+
+ range_data = {"y": [-0.4, 0.4], "x": [0, 10]}
+ result_numpy = _extract_box_points_numpy(fig, range_data)
+ result_fallback = _extract_box_points_fallback(fig, range_data)
+
+ assert len(result_numpy) == 3
+ assert all(r["y"] == "A" for r in result_numpy)
+ assert [r["x"] for r in result_numpy] == [1, 2, 3]
+ assert result_numpy == result_fallback
+
+
+def test_box_plot_multiple_traces() -> None:
+ """Range selection across multiple box traces."""
+ fig = go.Figure()
+ fig.add_trace(go.Box(x=["A", "A"], y=[1, 2], name="trace0"))
+ fig.add_trace(go.Box(x=["A", "A"], y=[3, 4], name="trace1"))
+
+ range_data = {"x": [-0.4, 0.4], "y": [0, 10]}
+ result = _extract_box_points_numpy(fig, range_data)
+
+ assert len(result) == 4
+ assert {r["curveNumber"] for r in result} == {0, 1}
+
+
+def test_box_plot_click_deduplication() -> None:
+ """Duplicate sample indices within pointNumbers are not repeated."""
+ fig = go.Figure()
+ fig.add_trace(go.Box(x=["A", "A", "A"], y=[1, 2, 3]))
+ plot = plotly(fig)
+
+ selection = {
+ "points": [
+ {
+ "x": "A",
+ "y": 1,
+ "pointIndex": 0,
+ "pointNumbers": [0, 1, 2],
+ "curveNumber": 0,
+ },
+ {
+ "x": "A",
+ "y": 1,
+ "pointIndex": 0,
+ "pointNumbers": [0, 1, 2],
+ "curveNumber": 0,
+ },
+ ],
+ "indices": [0, 0],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 3
+ assert sorted(r["pointIndex"] for r in result) == [0, 1, 2]
+
+
+# ============================================================================
+# Violin Plot Tests
+# ============================================================================
+
+
+def test_violin_plot_basic_creation() -> None:
+ """Test that a violin plot can be created and has empty initial selection."""
+ fig = go.Figure(data=go.Violin(y=[1, 2, 3, 4, 5], name="Group A"))
+ plot = plotly(fig)
+
+ assert plot is not None
+ assert plot.value == []
+ assert plot.ranges == {}
+ assert plot.points == []
+ assert plot.indices == []
+
+
+def test_violin_click_expands_point_numbers() -> None:
+ """Clicking a violin body sends pointNumbers; Python expands them to rows."""
+ fig = go.Figure()
+ fig.add_trace(go.Violin(x=["A", "A", "A", "B", "B"], y=[1, 2, 3, 4, 5]))
+ plot = plotly(fig)
+
+ selection = {
+ "points": [
+ {
+ "x": "A",
+ "y": 2,
+ "pointIndex": 0,
+ "pointNumbers": [0, 1, 2],
+ "curveNumber": 0,
+ }
+ ],
+ "indices": [0],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 3
+ assert all(r["x"] == "A" for r in result)
+ assert [r["y"] for r in result] == [1, 2, 3]
+ assert [r["pointIndex"] for r in result] == [0, 1, 2]
+ assert all(r["curveNumber"] == 0 for r in result)
+
+
+def test_violin_click_without_point_numbers_passthrough() -> None:
+ """When pointNumbers is absent (individual point click), pass through."""
+ fig = go.Figure()
+ fig.add_trace(go.Violin(x=["A", "A", "B"], y=[1, 2, 3]))
+ plot = plotly(fig)
+
+ selection = {
+ "points": [{"x": "A", "y": 1, "pointIndex": 0, "curveNumber": 0}],
+ "indices": [0],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 1
+ assert result[0]["pointIndex"] == 0
+
+
+def test_extract_violin_points_numpy_categorical() -> None:
+ """Numpy path: select category 'A' by index position."""
+ fig = go.Figure()
+ fig.add_trace(go.Violin(x=["A", "A", "A", "B", "B"], y=[1, 2, 3, 4, 5]))
+
+ range_data = {"x": [-0.4, 0.4], "y": [0, 10]}
+ result = _extract_violin_points_numpy(fig, range_data)
+
+ assert len(result) == 3
+ assert all(r["x"] == "A" for r in result)
+ assert [r["y"] for r in result] == [1, 2, 3]
+ assert [r["pointIndex"] for r in result] == [0, 1, 2]
+ assert all(r["curveNumber"] == 0 for r in result)
+
+
+def test_extract_violin_points_fallback_categorical() -> None:
+ """Pure-Python path: mirrors numpy categorical selection."""
+ fig = go.Figure()
+ fig.add_trace(go.Violin(x=["A", "A", "A", "B", "B"], y=[1, 2, 3, 4, 5]))
+
+ range_data = {"x": [-0.4, 0.4], "y": [0, 10]}
+ result = _extract_violin_points_fallback(fig, range_data)
+
+ assert len(result) == 3
+ assert all(r["x"] == "A" for r in result)
+ assert [r["y"] for r in result] == [1, 2, 3]
+
+
+def test_extract_violin_points_numpy_second_category() -> None:
+ """Select only the second category; numpy and fallback agree."""
+ fig = go.Figure()
+ fig.add_trace(go.Violin(x=["A", "A", "B", "B"], y=[1, 2, 3, 4]))
+
+ range_data = {"x": [0.6, 1.4], "y": [0, 10]}
+ result_numpy = _extract_violin_points_numpy(fig, range_data)
+ result_fallback = _extract_violin_points_fallback(fig, range_data)
+
+ assert len(result_numpy) == 2
+ assert all(r["x"] == "B" for r in result_numpy)
+ assert result_numpy == result_fallback
+
+
+def test_violin_range_selection_with_individual_points() -> None:
+ """When Plotly sends individual points via onSelected, pass them through."""
+ fig = go.Figure()
+ fig.add_trace(go.Violin(x=["A", "A", "B", "B"], y=[10, 20, 30, 40]))
+ plot = plotly(fig)
+
+ selection: dict[str, Any] = {
+ "range": {"x": [-0.4, 0.4], "y": [0, 50]},
+ "points": [
+ {"x": "A", "y": 10, "pointIndex": 0, "curveNumber": 0},
+ {"x": "A", "y": 20, "pointIndex": 1, "curveNumber": 0},
+ ],
+ "indices": [0, 1],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 2
+ assert all(r["x"] == "A" for r in result)
+ assert {r["pointIndex"] for r in result} == {0, 1}
+
+
+def test_violin_range_selection_fallback_no_points() -> None:
+ """When no individual points are sent (points disabled), extract from range."""
+ fig = go.Figure()
+ fig.add_trace(go.Violin(x=["A", "A", "B", "B"], y=[10, 20, 30, 40]))
+ plot = plotly(fig)
+
+ selection: dict[str, Any] = {
+ "range": {"x": [-0.4, 0.4], "y": [0, 50]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 2
+ assert all(r["x"] == "A" for r in result)
+ assert {r["y"] for r in result} == {10, 20}
+
+
+def test_violin_no_category_data() -> None:
+ """Violin trace without explicit x uses trace name as category."""
+ fig = go.Figure()
+ fig.add_trace(go.Violin(y=[5, 10, 15], name="Group X"))
+ plot = plotly(fig)
+
+ selection: dict[str, Any] = {
+ "range": {"y": [0, 20]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 3
+ assert all(r.get("x") == "Group X" for r in result)
+
+
+def test_violin_horizontal_orientation() -> None:
+ """Horizontal violin plots swap x/y roles for category and value."""
+ fig = go.Figure()
+ fig.add_trace(
+ go.Violin(
+ x=[1, 2, 3, 4, 5],
+ y=["A", "A", "A", "B", "B"],
+ orientation="h",
+ )
+ )
+
+ range_data = {"y": [-0.4, 0.4], "x": [0, 10]}
+ result_numpy = _extract_violin_points_numpy(fig, range_data)
+ result_fallback = _extract_violin_points_fallback(fig, range_data)
+
+ assert len(result_numpy) == 3
+ assert all(r["y"] == "A" for r in result_numpy)
+ assert [r["x"] for r in result_numpy] == [1, 2, 3]
+ assert result_numpy == result_fallback
+
+
+def test_violin_multiple_traces() -> None:
+ """Range selection across multiple violin traces."""
+ fig = go.Figure()
+ fig.add_trace(go.Violin(x=["A", "A"], y=[1, 2], name="trace0"))
+ fig.add_trace(go.Violin(x=["A", "A"], y=[3, 4], name="trace1"))
+
+ range_data = {"x": [-0.4, 0.4], "y": [0, 10]}
+ result = _extract_violin_points_numpy(fig, range_data)
+
+ assert len(result) == 4
+ assert {r["curveNumber"] for r in result} == {0, 1}
+
+
+def test_violin_click_deduplication() -> None:
+ """Duplicate sample indices within pointNumbers are not repeated."""
+ fig = go.Figure()
+ fig.add_trace(go.Violin(x=["A", "A", "A"], y=[1, 2, 3]))
+ plot = plotly(fig)
+
+ selection = {
+ "points": [
+ {
+ "x": "A",
+ "y": 1,
+ "pointIndex": 0,
+ "pointNumbers": [0, 1, 2],
+ "curveNumber": 0,
+ },
+ {
+ "x": "A",
+ "y": 1,
+ "pointIndex": 0,
+ "pointNumbers": [0, 1, 2],
+ "curveNumber": 0,
+ },
+ ],
+ "indices": [0, 0],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 3
+ assert sorted(r["pointIndex"] for r in result) == [0, 1, 2]
+
+
+# ============================================================================
+# Strip Chart Tests (px.strip uses go.Box traces with boxpoints="all")
+# ============================================================================
+
+
+def test_strip_chart_basic_creation() -> None:
+ """Test that a strip chart can be created and has empty initial selection."""
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {
+ "category": ["A", "A", "B", "B", "C"],
+ "value": [1.0, 2.0, 3.0, 4.0, 5.0],
+ }
+ )
+ fig = px.strip(df, x="category", y="value")
+ plot = plotly(fig)
+
+ assert plot is not None
+ assert plot.value == []
+ assert plot.ranges == {}
+ assert plot.points == []
+ assert plot.indices == []
+
+
+def test_strip_chart_uses_box_traces() -> None:
+ """Verify that px.strip produces go.Box traces (type='box')."""
+ import pandas as pd
+
+ df = pd.DataFrame({"cat": ["A", "A", "B"], "val": [1, 2, 3]})
+ fig = px.strip(df, x="cat", y="val")
+
+ trace_types = [getattr(t, "type", None) for t in fig.data]
+ assert all(t == "box" for t in trace_types)
+
+
+def test_strip_chart_individual_point_click() -> None:
+ """Clicking an individual strip point (boxpoints='all') passes through directly."""
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {"cat": ["A", "A", "A", "B", "B"], "val": [1.0, 2.0, 3.0, 4.0, 5.0]}
+ )
+ fig = px.strip(df, x="cat", y="val")
+ plot = plotly(fig)
+
+ # Individual point click – no pointNumbers, just pointIndex
+ selection = {
+ "points": [{"x": "A", "y": 1.0, "pointIndex": 0, "curveNumber": 0}],
+ "indices": [0],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 1
+ assert result[0]["pointIndex"] == 0
+ assert result[0]["y"] == 1.0
+
+
+def test_strip_chart_range_selection_with_individual_points() -> None:
+ """Box/lasso selection on a strip chart returns the individual points Plotly sent."""
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {
+ "cat": ["A", "A", "A", "B", "B"],
+ "val": [1.0, 2.0, 3.0, 4.0, 5.0],
+ }
+ )
+ fig = px.strip(df, x="cat", y="val")
+ plot = plotly(fig)
+
+ # Simulate onSelected: Plotly sends category-A points + range
+ selection: dict[str, Any] = {
+ "range": {"x": [-0.4, 0.4], "y": [0, 10]},
+ "points": [
+ {"x": "A", "y": 1.0, "pointIndex": 0, "curveNumber": 0},
+ {"x": "A", "y": 2.0, "pointIndex": 1, "curveNumber": 0},
+ {"x": "A", "y": 3.0, "pointIndex": 2, "curveNumber": 0},
+ ],
+ "indices": [0, 1, 2],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 3
+ assert all(r["x"] == "A" for r in result)
+ assert {r["y"] for r in result} == {1.0, 2.0, 3.0}
+
+
+def test_strip_chart_range_selection_no_individual_points() -> None:
+ """When Plotly sends no individual points, extract from range using box logic."""
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {"cat": ["A", "A", "B", "B"], "val": [10.0, 20.0, 30.0, 40.0]}
+ )
+ fig = px.strip(df, x="cat", y="val")
+ plot = plotly(fig)
+
+ selection: dict[str, Any] = {
+ "range": {"x": [-0.4, 0.4], "y": [0, 50]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 2
+ assert all(r["x"] == "A" for r in result)
+ assert {r["y"] for r in result} == {10.0, 20.0}
+
+
+def test_strip_chart_grouped_selection() -> None:
+ """Range selection that spans two strip groups returns all matching rows."""
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {
+ "cat": ["A", "A", "B", "B"],
+ "val": [1.0, 2.0, 3.0, 4.0],
+ "grp": ["X", "X", "Y", "Y"],
+ }
+ )
+ fig = px.strip(df, x="cat", y="val", color="grp")
+ plot = plotly(fig)
+
+ # Select all — range covers all category positions
+ selection: dict[str, Any] = {
+ "range": {"x": [-1, 5], "y": [0, 10]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ # All 4 rows should be returned (2 from each strip trace)
+ assert len(result) == 4
+
+
+def test_strip_chart_customdata_preserved() -> None:
+ """Customdata fields are included in selected strip points."""
+ fig = go.Figure()
+ fig.add_trace(
+ go.Box(
+ x=["A", "A", "B"],
+ y=[1.0, 2.0, 3.0],
+ boxpoints="all",
+ customdata=["id_0", "id_1", "id_2"],
+ )
+ )
+ plot = plotly(fig)
+
+ selection: dict[str, Any] = {
+ "range": {"x": [-0.4, 0.4], "y": [0, 10]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 2
+ assert result[0]["customdata"] == "id_0"
+ assert result[1]["customdata"] == "id_1"
+
+
# ============================================================================
# Waterfall chart tests
# ============================================================================
@@ -3338,232 +3974,312 @@ def test_waterfall_customdata_included() -> None:
# ============================================================================
-# Violin Plot Tests
+# Funnel chart tests
# ============================================================================
-def test_violin_plot_basic_creation() -> None:
- """Test that a violin plot can be created and has empty initial selection."""
- fig = go.Figure(data=go.Violin(y=[1, 2, 3, 4, 5], name="Group A"))
+def test_funnel_basic() -> None:
+ """Funnel plot with no selection starts with empty value."""
+ fig = go.Figure(
+ data=go.Funnel(
+ y=["Visit", "Cart", "Purchase"],
+ x=[1000, 800, 600],
+ )
+ )
plot = plotly(fig)
-
- assert plot is not None
assert plot.value == []
- assert plot.ranges == {}
- assert plot.points == []
assert plot.indices == []
-def test_violin_click_expands_point_numbers() -> None:
- """Clicking a violin body sends pointNumbers; Python expands them to rows."""
- fig = go.Figure()
- fig.add_trace(go.Violin(x=["A", "A", "A", "B", "B"], y=[1, 2, 3, 4, 5]))
+def test_funnel_click_selection() -> None:
+ """Click on a funnel stage passes through with all funnel-specific fields."""
+ fig = go.Figure(
+ data=go.Funnel(
+ y=["Visit", "Cart", "Purchase"],
+ x=[1000, 800, 600],
+ )
+ )
plot = plotly(fig)
selection = {
"points": [
{
- "x": "A",
- "y": 2,
- "pointIndex": 0,
- "pointNumbers": [0, 1, 2],
+ "x": 1000,
+ "y": "Visit",
+ "label": "Visit",
+ "value": 1000,
+ "percentInitial": 1.0,
+ "percentPrevious": 1.0,
+ "percentTotal": 1.0,
"curveNumber": 0,
+ "pointIndex": 0,
+ "pointNumber": 0,
}
],
"indices": [0],
}
-
result = plot._convert_value(selection)
-
- assert len(result) == 3
- assert all(r["x"] == "A" for r in result)
- assert [r["y"] for r in result] == [1, 2, 3]
- assert [r["pointIndex"] for r in result] == [0, 1, 2]
- assert all(r["curveNumber"] == 0 for r in result)
+ assert len(result) == 1
+ assert result[0]["x"] == 1000
+ assert result[0]["y"] == "Visit"
+ assert result[0]["percentInitial"] == 1.0
+ assert plot.indices == [0]
-def test_violin_click_without_point_numbers_passthrough() -> None:
- """When pointNumbers is absent (individual point click), pass through."""
- fig = go.Figure()
- fig.add_trace(go.Violin(x=["A", "A", "B"], y=[1, 2, 3]))
+def test_funnel_range_selection() -> None:
+ """Box selection on funnel extracts stages whose bar overlaps the range."""
+ fig = go.Figure(
+ data=go.Funnel(
+ y=["Visit", "Cart", "Purchase"],
+ x=[1000, 800, 600],
+ )
+ )
plot = plotly(fig)
- selection = {
- "points": [{"x": "A", "y": 1, "pointIndex": 0, "curveNumber": 0}],
- "indices": [0],
+ # Range covers y positions 0 and 1 (Visit, Cart) with x overlap
+ selection: dict[str, Any] = {
+ "points": [],
+ "indices": [],
+ "range": {"x": [500, 1100], "y": [-0.5, 1.5]},
}
-
result = plot._convert_value(selection)
+ assert len(result) == 2
+ labels = [p["y"] for p in result]
+ assert "Visit" in labels
+ assert "Cart" in labels
+ assert "Purchase" not in labels
- assert len(result) == 1
- assert result[0]["pointIndex"] == 0
-
-
-def test_extract_violin_points_numpy_categorical() -> None:
- """Numpy path: select category 'A' by index position."""
- fig = go.Figure()
- fig.add_trace(go.Violin(x=["A", "A", "A", "B", "B"], y=[1, 2, 3, 4, 5]))
- range_data = {"x": [-0.4, 0.4], "y": [0, 10]}
- result = _extract_violin_points_numpy(fig, range_data)
+def test_funnel_range_selection_all_stages() -> None:
+ """Full range selects every funnel stage."""
+ fig = go.Figure(
+ data=go.Funnel(
+ y=["Visit", "Cart", "Purchase"],
+ x=[1000, 800, 600],
+ )
+ )
+ plot = plotly(fig)
+ selection: dict[str, Any] = {
+ "points": [],
+ "indices": [],
+ "range": {"x": [0, 1100], "y": [-0.5, 2.5]},
+ }
+ result = plot._convert_value(selection)
assert len(result) == 3
- assert all(r["x"] == "A" for r in result)
- assert [r["y"] for r in result] == [1, 2, 3]
- assert [r["pointIndex"] for r in result] == [0, 1, 2]
- assert all(r["curveNumber"] == 0 for r in result)
-def test_extract_violin_points_fallback_categorical() -> None:
- """Pure-Python path: mirrors numpy categorical selection."""
- fig = go.Figure()
- fig.add_trace(go.Violin(x=["A", "A", "A", "B", "B"], y=[1, 2, 3, 4, 5]))
+def test_funnel_range_selection_empty() -> None:
+ """Range that misses all stages returns empty selection."""
+ fig = go.Figure(
+ data=go.Funnel(
+ y=["Visit", "Cart", "Purchase"],
+ x=[1000, 800, 600],
+ )
+ )
+ plot = plotly(fig)
- range_data = {"x": [-0.4, 0.4], "y": [0, 10]}
- result = _extract_violin_points_fallback(fig, range_data)
+ # x range below all values
+ selection: dict[str, Any] = {
+ "points": [],
+ "indices": [],
+ "range": {"x": [-500, -1], "y": [-0.5, 2.5]},
+ }
+ result = plot._convert_value(selection)
+ assert result == []
+ assert plot.indices == []
- assert len(result) == 3
- assert all(r["x"] == "A" for r in result)
- assert [r["y"] for r in result] == [1, 2, 3]
+def test_funnel_numpy_and_fallback_match() -> None:
+ """numpy and fallback extraction produce identical results."""
+ fig = go.Figure(
+ data=go.Funnel(
+ y=["Visit", "Cart", "Purchase"],
+ x=[1000, 800, 600],
+ )
+ )
-def test_extract_violin_points_numpy_second_category() -> None:
- """Select only the second category; numpy and fallback agree."""
- fig = go.Figure()
- fig.add_trace(go.Violin(x=["A", "A", "B", "B"], y=[1, 2, 3, 4]))
+ x_min, x_max = 500.0, 1100.0
+ y_min, y_max = -0.5, 1.5
- range_data = {"x": [0.6, 1.4], "y": [0, 10]}
- result_numpy = _extract_violin_points_numpy(fig, range_data)
- result_fallback = _extract_violin_points_fallback(fig, range_data)
+ numpy_result = _extract_funnel_stages_numpy(
+ fig, x_min, x_max, y_min, y_max
+ )
+ fallback_result = _extract_funnel_stages_fallback(
+ fig, x_min, x_max, y_min, y_max
+ )
- assert len(result_numpy) == 2
- assert all(r["x"] == "B" for r in result_numpy)
- assert result_numpy == result_fallback
+ 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"]),
+ strict=True,
+ ):
+ assert np_pt["x"] == fb_pt["x"]
+ assert np_pt["y"] == fb_pt["y"]
+ assert np_pt["pointIndex"] == fb_pt["pointIndex"]
-def test_violin_range_selection_with_individual_points() -> None:
- """When Plotly sends individual points via onSelected, pass them through."""
- fig = go.Figure()
- fig.add_trace(go.Violin(x=["A", "A", "B", "B"], y=[10, 20, 30, 40]))
+def test_funnel_vertical_orientation() -> None:
+ """Vertical funnel (orientation='v') extracts stages correctly."""
+ fig = go.Figure(
+ data=go.Funnel(
+ x=["Visit", "Cart", "Purchase"],
+ y=[1000, 800, 600],
+ orientation="v",
+ )
+ )
plot = plotly(fig)
+ # For vertical funnel: x=labels (cat axis), y=values (val axis)
+ # y_range covers stages 0 and 1, x_range covers their positions
selection: dict[str, Any] = {
- "range": {"x": [-0.4, 0.4], "y": [0, 50]},
- "points": [
- {"x": "A", "y": 10, "pointIndex": 0, "curveNumber": 0},
- {"x": "A", "y": 20, "pointIndex": 1, "curveNumber": 0},
- ],
- "indices": [0, 1],
+ "points": [],
+ "indices": [],
+ "range": {"x": [-0.5, 1.5], "y": [500, 1100]},
}
-
result = plot._convert_value(selection)
-
assert len(result) == 2
- assert all(r["x"] == "A" for r in result)
- assert {r["pointIndex"] for r in result} == {0, 1}
+ labels = [p["x"] for p in result]
+ assert "Visit" in labels
+ assert "Cart" in labels
-def test_violin_range_selection_fallback_no_points() -> None:
- """When no individual points are sent (points disabled), extract from range."""
- fig = go.Figure()
- fig.add_trace(go.Violin(x=["A", "A", "B", "B"], y=[10, 20, 30, 40]))
+def test_funnel_multi_trace() -> None:
+ """Multiple funnel traces are each extracted independently."""
+ fig = go.Figure(
+ data=[
+ go.Funnel(y=["A", "B"], x=[100, 50], name="T1"),
+ go.Funnel(y=["A", "B"], x=[200, 80], name="T2"),
+ ]
+ )
plot = plotly(fig)
selection: dict[str, Any] = {
- "range": {"x": [-0.4, 0.4], "y": [0, 50]},
"points": [],
"indices": [],
+ "range": {"x": [0, 250], "y": [-0.5, 1.5]},
}
-
result = plot._convert_value(selection)
-
- assert len(result) == 2
- assert all(r["x"] == "A" for r in result)
- assert {r["y"] for r in result} == {10, 20}
+ curve_numbers = {p["curveNumber"] for p in result}
+ assert curve_numbers == {0, 1}
+ assert len(result) == 4
-def test_violin_no_category_data() -> None:
- """Violin trace without explicit x uses trace name as category."""
- fig = go.Figure()
- fig.add_trace(go.Violin(y=[5, 10, 15], name="Group X"))
+def test_funnel_customdata_included() -> None:
+ """customdata attached to funnel stages appears in extracted points."""
+ fig = go.Figure(
+ data=go.Funnel(
+ y=["Visit", "Cart"],
+ x=[1000, 800],
+ customdata=[["web", "US"], ["mobile", "EU"]],
+ )
+ )
plot = plotly(fig)
selection: dict[str, Any] = {
- "range": {"y": [0, 20]},
"points": [],
"indices": [],
+ "range": {"x": [0, 1100], "y": [-0.5, 1.5]},
}
-
result = plot._convert_value(selection)
+ assert any(p.get("customdata") is not None for p in result)
- assert len(result) == 3
- assert all(r.get("x") == "Group X" for r in result)
-
-
-def test_violin_horizontal_orientation() -> None:
- """Horizontal violin plots swap x/y roles for category and value."""
- fig = go.Figure()
- fig.add_trace(
- go.Violin(
- x=[1, 2, 3, 4, 5],
- y=["A", "A", "A", "B", "B"],
- orientation="h",
- )
- )
- range_data = {"y": [-0.4, 0.4], "x": [0, 10]}
- result_numpy = _extract_violin_points_numpy(fig, range_data)
- result_fallback = _extract_violin_points_fallback(fig, range_data)
+def test_funnel_click_empty_placeholder_stripped() -> None:
+ """Empty-dict placeholders from the frontend are stripped on click."""
+ fig = go.Figure(data=go.Funnel(y=["Visit", "Cart"], x=[1000, 800]))
+ plot = plotly(fig)
- assert len(result_numpy) == 3
- assert all(r["y"] == "A" for r in result_numpy)
- assert [r["x"] for r in result_numpy] == [1, 2, 3]
- assert result_numpy == result_fallback
+ selection = {
+ "points": [
+ {},
+ {"x": 1000, "y": "Visit", "curveNumber": 0, "pointIndex": 0},
+ ],
+ "indices": [999, 0],
+ }
+ result = plot._convert_value(selection)
+ assert len(result) == 1
+ assert result[0]["y"] == "Visit"
+ assert plot.indices == [0]
-def test_violin_multiple_traces() -> None:
- """Range selection across multiple violin traces."""
- fig = go.Figure()
- fig.add_trace(go.Violin(x=["A", "A"], y=[1, 2], name="trace0"))
- fig.add_trace(go.Violin(x=["A", "A"], y=[3, 4], name="trace1"))
+# ============================================================================
+# FunnelArea chart tests
+# ============================================================================
- range_data = {"x": [-0.4, 0.4], "y": [0, 10]}
- result = _extract_violin_points_numpy(fig, range_data)
- assert len(result) == 4
- assert {r["curveNumber"] for r in result} == {0, 1}
+def test_funnelarea_basic() -> None:
+ """FunnelArea plot starts with empty value."""
+ fig = go.Figure(
+ data=go.Funnelarea(
+ labels=["Visit", "Cart", "Purchase"],
+ values=[1000, 800, 600],
+ )
+ )
+ plot = plotly(fig)
+ assert plot.value == []
+ assert plot.indices == []
-def test_violin_click_deduplication() -> None:
- """Duplicate sample indices within pointNumbers are not repeated."""
- fig = go.Figure()
- fig.add_trace(go.Violin(x=["A", "A", "A"], y=[1, 2, 3]))
+def test_funnelarea_click_selection() -> None:
+ """Click on a funnelarea sector passes through label/value/percent fields."""
+ fig = go.Figure(
+ data=go.Funnelarea(
+ labels=["Visit", "Cart", "Purchase"],
+ values=[1000, 800, 600],
+ )
+ )
plot = plotly(fig)
selection = {
"points": [
{
- "x": "A",
- "y": 1,
- "pointIndex": 0,
- "pointNumbers": [0, 1, 2],
+ "label": "Cart",
+ "value": 800,
+ "percentInitial": 0.8,
+ "percentPrevious": 0.8,
+ "percentTotal": 0.8,
"curveNumber": 0,
- },
+ "pointNumber": 1,
+ }
+ ],
+ "indices": [1],
+ }
+ result = plot._convert_value(selection)
+ assert len(result) == 1
+ assert result[0]["label"] == "Cart"
+ assert result[0]["value"] == 800
+ assert result[0]["percentInitial"] == 0.8
+ assert plot.indices == [1]
+
+
+def test_funnelarea_click_empty_placeholder_stripped() -> None:
+ """Empty-dict placeholders are stripped for funnelarea clicks."""
+ fig = go.Figure(
+ data=go.Funnelarea(
+ labels=["Visit", "Cart"],
+ values=[1000, 800],
+ )
+ )
+ plot = plotly(fig)
+
+ selection = {
+ "points": [
+ {},
{
- "x": "A",
- "y": 1,
- "pointIndex": 0,
- "pointNumbers": [0, 1, 2],
+ "label": "Visit",
+ "value": 1000,
"curveNumber": 0,
+ "pointNumber": 0,
},
],
- "indices": [0, 0],
+ "indices": [999, 0],
}
-
result = plot._convert_value(selection)
-
- assert len(result) == 3
- assert sorted(r["pointIndex"] for r in result) == [0, 1, 2]
+ assert len(result) == 1
+ assert result[0]["label"] == "Visit"
+ assert plot.indices == [0]
def test_violin_and_bar_range_selection_interaction() -> None: