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 violin plot selection support (#9011)

axssel8649f3b8e123
diff --git a/docs/api/plotting.md b/docs/api/plotting.md
index 975c3c3b9c..f30128230b 100644
--- a/docs/api/plotting.md
+++ b/docs/api/plotting.md
@@ -106,7 +106,7 @@ alt.data_transformers.enable('marimo_csv')
marimo can render any Plotly plot, but [`mo.ui.plotly`][marimo.ui.plotly] only
supports reactive selections for scatter/scattergl plots, pure line charts, bar charts,
- histograms, waterfall charts, heatmaps, treemaps, and sunburst charts. If you require other kinds of
+ violin plots, histograms, waterfall charts, heatmaps, treemaps, and sunburst charts. If you require other kinds of
selection, please [file an issue](https://github.com/marimo-team/marimo/issues).
::: marimo.ui.plotly
diff --git a/examples/third_party/plotly/violin_chart.py b/examples/third_party/plotly/violin_chart.py
new file mode 100644
index 0000000000..0171da653d
--- /dev/null
+++ b/examples/third_party/plotly/violin_chart.py
@@ -0,0 +1,309 @@
+# /// 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 Violin Plot Selection
+
+ This example demonstrates reactive violin plot selections with `mo.ui.plotly`.
+
+ Try:
+ - **Drag a box** over jittered sample points to select them
+ - **Click** a violin 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
+ ids = [
+ row["sample_id"]
+ for row in selection
+ if isinstance(row.get("sample_id"), str)
+ ]
+ 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 Violin Plot")
+
+ fig_single = go.Figure(
+ data=go.Violin(
+ x=df["team"],
+ y=df["score"],
+ customdata=df[["sample_id", "shift", "region", "passed"]],
+ points="all",
+ jitter=0.35,
+ pointpos=0,
+ box_visible=True,
+ meanline_visible=True,
+ marker=dict(size=8, opacity=0.8, color="#7B2D8B"),
+ line=dict(color="#7B2D8B"),
+ fillcolor="rgba(123,45,139,0.15)",
+ 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 violin",
+ xaxis_title="Team",
+ yaxis_title="Score",
+ dragmode="select",
+ )
+
+ violin_single = mo.ui.plotly(fig_single)
+ violin_single
+ return (violin_single,)
+
+
+def _(df, mo, selected_rows, violin_single):
+ _sel = selected_rows(violin_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:** {violin_single.indices}
+ """)
+ return
+
+
+def _(df, mo, selected_rows, violin_single):
+ mo.ui.table(selected_rows(violin_single.value, df))
+ return
+
+
+def _(df, mo, px):
+ mo.md("## Grouped Violin Plot")
+
+ fig_grouped = px.violin(
+ df,
+ x="team",
+ y="score",
+ color="shift",
+ points="all",
+ box=True,
+ 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,
+ meanline_visible=True,
+ 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")
+
+ violin_grouped = mo.ui.plotly(fig_grouped)
+ violin_grouped
+ return (violin_grouped,)
+
+
+def _(df, mo, selected_rows, violin_grouped):
+ _sel_g = selected_rows(violin_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:** {violin_grouped.indices}
+
+ **Range:** {violin_grouped.ranges}
+ """)
+ return
+
+
+def _(df, mo, selected_rows, violin_grouped):
+ mo.ui.table(selected_rows(violin_grouped.value, df))
+ return
+
+
+def _(df, go, mo):
+ mo.md("## Horizontal Violin Plot")
+
+ fig_horizontal = go.Figure(
+ data=go.Violin(
+ x=df["score"],
+ y=df["team"],
+ orientation="h",
+ customdata=df[["sample_id", "shift", "region", "passed"]],
+ points="all",
+ jitter=0.35,
+ pointpos=0,
+ box_visible=True,
+ meanline_visible=True,
+ marker=dict(size=8, opacity=0.8, color="#2a9d8f"),
+ line=dict(color="#2a9d8f"),
+ fillcolor="rgba(42,157,143,0.15)",
+ 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",
+ )
+
+ violin_horizontal = mo.ui.plotly(fig_horizontal)
+ violin_horizontal
+ return (violin_horizontal,)
+
+
+def _(df, mo, selected_rows, violin_horizontal):
+ _sel_h = selected_rows(violin_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:** {violin_horizontal.indices}
+ """)
+ return
+
+
+def _(df, mo, selected_rows, violin_horizontal):
+ mo.ui.table(selected_rows(violin_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 56a2e62d8e..21b9a62dbd 100644
--- a/frontend/src/plugins/impl/plotly/__tests__/PlotlyPlugin.test.tsx
+++ b/frontend/src/plugins/impl/plotly/__tests__/PlotlyPlugin.test.tsx
@@ -111,4 +111,54 @@ describe("PlotlyPlugin", () => {
range: undefined,
});
});
+
+ it("clicking a violin element triggers onClick", async () => {
+ const setValue = vi.fn<Setter<unknown>>();
+
+ render(
+ <Suspense fallback={null}>
+ <PlotlyComponent
+ figure={{
+ data: [{ type: "violin" }],
+ 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: "violin" },
+ 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,
+ });
+ });
});
diff --git a/frontend/src/plugins/impl/plotly/__tests__/selection.test.ts b/frontend/src/plugins/impl/plotly/__tests__/selection.test.ts
index b238d2d6a5..e4867b321f 100644
--- a/frontend/src/plugins/impl/plotly/__tests__/selection.test.ts
+++ b/frontend/src/plugins/impl/plotly/__tests__/selection.test.ts
@@ -101,6 +101,14 @@ describe("shouldHandleClickSelection", () => {
expect(shouldHandleClickSelection([heatmapPoint])).toBe(true);
});
+ it("accepts violin clicks", () => {
+ const violinPoint = createPlotDatum({
+ data: { type: "violin" },
+ });
+
+ expect(shouldHandleClickSelection([violinPoint])).toBe(true);
+ });
+
it("accepts histogram clicks", () => {
const histogramPoint = createPlotDatum({
data: { type: "histogram" },
diff --git a/frontend/src/plugins/impl/plotly/selection.ts b/frontend/src/plugins/impl/plotly/selection.ts
index b44a83dfa0..1757b31906 100644
--- a/frontend/src/plugins/impl/plotly/selection.ts
+++ b/frontend/src/plugins/impl/plotly/selection.ts
@@ -228,6 +228,7 @@ export function shouldHandleClickSelection(
type === "heatmap" ||
type === "histogram" ||
type === "waterfall" ||
+ type === "violin" ||
isLinePoint(point)
);
});
diff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.py
index a10ee0eb36..f3d3e0b052 100644
--- a/marimo/_plugins/ui/_impl/plotly.py
+++ b/marimo/_plugins/ui/_impl/plotly.py
@@ -205,7 +205,7 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):
cursor on the frontend, get them as a list of dicts in Python!
This function supports scatter plots, scattergl plots, line charts, area
- charts, bar charts, histograms, waterfall charts, treemap charts, sunburst
+ charts, bar charts, violin plots, histograms, waterfall charts, treemap charts, sunburst
charts, and heatmaps.
Examples:
@@ -328,6 +328,7 @@ 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 (
+ "violin",
"heatmap",
"bar",
"histogram",
@@ -501,6 +502,18 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):
self._figure, self._selection_data
)
+ has_violin = any(
+ getattr(trace, "type", None) == "violin"
+ 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(
+ self._figure, self._selection_data
+ )
+
# For line/scatter charts, extract points from box/lasso selections.
# Plotly may not send point data for pure line charts, so we extract manually.
if has_scatter and (value.get("range") or value.get("lasso")):
@@ -2259,6 +2272,317 @@ def _extract_waterfall_bars_fallback(
return selected
+def _append_violin_points_to_selection(
+ figure: go.Figure, selection_data: dict[str, Any]
+) -> None:
+ """Expand violin plot selections into individual underlying data points.
+
+ Handles three cases:
+ - Range/lasso with individual points already sent by Plotly (``points``
+ enabled): Plotly already delivered the right individual data points via
+ the ``onSelected`` event; pass them through unchanged.
+ - Range/lasso without individual points (``points`` 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 violin element; expand these into one dict per sample row so
+ Python callers get row-level data.
+ """
+ all_points = cast(list[dict[str, Any]], selection_data.get("points", []))
+ all_indices = cast(list[Any], selection_data.get("indices", []))
+
+ violin_curve_numbers = {
+ trace_idx
+ for trace_idx, trace in enumerate(figure.data)
+ if getattr(trace, "type", None) == "violin"
+ }
+ if not violin_curve_numbers:
+ return
+
+ range_value = selection_data.get("range")
+ lasso_value = selection_data.get("lasso")
+
+ # --- Range/lasso selection path (onSelected event) ---
+ if isinstance(range_value, dict) or isinstance(lasso_value, dict):
+ existing_violin = [
+ p
+ for p in all_points
+ if p and p.get("curveNumber") in violin_curve_numbers
+ ]
+ existing_non_violin = [
+ p
+ for p in all_points
+ if p and p.get("curveNumber") not in violin_curve_numbers
+ ]
+ existing_non_violin_indices = [
+ idx
+ for idx, p in zip(all_indices, all_points)
+ if p and p.get("curveNumber") not in violin_curve_numbers
+ ]
+
+ if existing_violin:
+ # Plotly already sent the individual selected data points because
+ # points 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 custom ids).
+ clean_points = existing_violin + existing_non_violin
+ # 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) 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
+
+ # No individual points from Plotly → points attribute 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
+ violin_points = _extract_violin_points_from_range(
+ figure, cast(dict[str, Any], range_value)
+ )
+
+ if violin_points or existing_non_violin:
+ seen: set[tuple[int, int]] = set()
+ merged_points: list[dict[str, Any]] = []
+ merged_indices: list[int] = []
+
+ for idx, point in zip(
+ existing_non_violin_indices, existing_non_violin
+ ):
+ 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)
+
+ for point in violin_points:
+ 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:
+ # Range didn't overlap any violin category and no non-violin points
+ # exist — clear any stale placeholder dicts the frontend may have sent.
+ selection_data["points"] = []
+ selection_data["indices"] = []
+ return
+
+ # --- Click event path ---
+ # Violin element clicks include pointNumbers (all raw-data indices in the
+ # group). Expand each such click-point into individual sample rows.
+ has_violin_click_with_numbers = any(
+ p.get("curveNumber") in violin_curve_numbers and "pointNumbers" in p
+ for p in all_points
+ if p
+ )
+ if not has_violin_click_with_numbers:
+ return
+
+ 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")
+
+ if curve_number not in violin_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_points.append(point)
+ # Use _get_selection_point_id to capture pointNumber as a fallback
+ # when pointIndex is absent (e.g. hovermode-'x' multi-trace clicks).
+ if point_id is not None:
+ expanded_indices.append(point_id[1])
+ elif isinstance(point.get("pointIndex"), int):
+ expanded_indices.append(cast(int, point["pointIndex"]))
+ continue
+
+ point_numbers = point.get("pointNumbers")
+ if not isinstance(point_numbers, list) or not (
+ 0 <= cast(int, curve_number) < len(figure.data)
+ ):
+ expanded_points.append(point)
+ if isinstance(point.get("pointIndex"), int):
+ expanded_indices.append(cast(int, point["pointIndex"]))
+ continue
+
+ trace = figure.data[cast(int, curve_number)]
+ for raw_idx in point_numbers:
+ if not isinstance(raw_idx, int):
+ continue
+ sample = _build_violin_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 _extract_violin_points_from_range(
+ figure: go.Figure, range_data: dict[str, Any]
+) -> list[dict[str, Any]]:
+ """Extract violin plot underlying data points that fall within a selection range.
+
+ For each violin trace, both the category axis (x for vertical, y for
+ horizontal) and the value axis are compared against the selection range.
+ Only sample rows whose category group overlaps the selection *and* whose
+ individual value falls within the value-axis bounds are returned. When the
+ value-axis range is absent from ``range_data`` (e.g. a selection spanning
+ the full y-axis) all rows in matching categories are included.
+ """
+ if DependencyManager.numpy.has():
+ return _extract_violin_points_numpy(figure, range_data)
+ return _extract_violin_points_fallback(figure, range_data)
+
+
+def _extract_violin_points_numpy(
+ figure: go.Figure, range_data: dict[str, Any]
+) -> list[dict[str, Any]]:
+ """Extract violin plot data points from a selection range using numpy.
+
+ 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). When ``points`` is disabled in the Plotly
+ figure, Plotly does not send individual point coordinates, so we derive
+ inclusion from the underlying trace arrays.
+ """
+ import numpy as np
+
+ 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
+
+ val_arr = np.asarray(val_data)
+ n = len(val_arr)
+ if n == 0:
+ continue
+
+ if cat_data is None:
+ 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:
+ 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()
+
+ 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:
+ seen_order: dict[Any, float] = {}
+ for v in cat_arr:
+ try:
+ if v not in seen_order:
+ seen_order[v] = float(len(seen_order))
+ except TypeError:
+ pass
+ positions = np.array(
+ [_safe_category_get(seen_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)
+
+ if val_range:
+ val_min_f = float(min(val_range))
+ val_max_f = float(max(val_range))
+ try:
+ val_numeric = val_arr.astype(float)
+ val_mask = (val_numeric >= val_min_f) & (
+ val_numeric <= val_max_f
+ )
+ cat_mask = cat_mask & val_mask
+ except (ValueError, TypeError):
+ pass # non-numeric values; skip value filtering
+
+ selected_indices = np.where(cat_mask)[0]
+ for i in selected_indices:
+ sample = _build_violin_sample_point(trace, trace_idx, int(i))
+ if sample is not None:
+ selected.append(sample)
+
+ return selected
+
+
def _build_waterfall_point(
trace: Any,
trace_idx: int,
@@ -2297,6 +2621,153 @@ 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).
+
+ 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
+) -> Optional[dict[str, Any]]:
+ """Build a row-level selection payload for a single violin 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,
+ "pointNumber": 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 _append_map_scatter_points_to_selection(
figure: go.Figure, selection_data: dict[str, Any]
) -> None:
diff --git a/tests/_plugins/ui/_impl/test_plotly.py b/tests/_plugins/ui/_impl/test_plotly.py
index 252619bab2..f552ac0595 100644
--- a/tests/_plugins/ui/_impl/test_plotly.py
+++ b/tests/_plugins/ui/_impl/test_plotly.py
@@ -25,6 +25,8 @@ from marimo._plugins.ui._impl.plotly import (
_extract_histogram_points_numpy,
_extract_scatter_points_fallback,
_extract_scatter_points_numpy,
+ _extract_violin_points_fallback,
+ _extract_violin_points_numpy,
_extract_waterfall_bars_fallback,
_extract_waterfall_bars_numpy,
_to_numeric_coord,
@@ -3332,3 +3334,291 @@ def test_waterfall_customdata_included() -> None:
}
result = plot._convert_value(selection)
assert all(p.get("customdata") is not None for p in result)
+
+
+# ============================================================================
+# 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]
+
+
+def test_violin_and_bar_range_selection_interaction() -> None:
+ """Mixed violin+bar figure: both trace types appear in the range result."""
+ fig = go.Figure()
+ fig.add_trace(go.Violin(x=["A", "A"], y=[1, 2]))
+ fig.add_trace(go.Bar(x=["A"], y=[10]))
+ plot = plotly(fig)
+
+ selection: dict[str, Any] = {
+ "range": {"x": [-0.4, 0.4], "y": [0, 15]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ curve_numbers = {r["curveNumber"] for r in result}
+ assert 0 in curve_numbers # violin trace
+ assert 1 in curve_numbers # bar trace
+
+
+def test_violin_lasso_without_range_skips_extraction() -> None:
+ """Lasso event without a range dict does not extract violin rows."""
+ fig = go.Figure()
+ fig.add_trace(go.Violin(x=["A", "A", "B"], y=[1, 2, 3]))
+ plot = plotly(fig)
+
+ selection: dict[str, Any] = {
+ "lasso": {"x": [0.5, 1.0, 0.5], "y": [0, 10, 10]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+ assert result == []
+
+
+def test_violin_click_with_empty_point_numbers_produces_no_rows() -> None:
+ """Click with empty pointNumbers list expands to zero points."""
+ fig = go.Figure()
+ fig.add_trace(go.Violin(x=["A", "A", "A"], y=[1, 2, 3]))
+ plot = plotly(fig)
+
+ selection: dict[str, Any] = {
+ "points": [
+ {
+ "x": "A",
+ "y": 1,
+ "pointIndex": 0,
+ "pointNumbers": [],
+ "curveNumber": 0,
+ }
+ ],
+ "indices": [0],
+ }
+
+ result = plot._convert_value(selection)
+ assert result == []