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 histogram selection support (#8489)

axssel718496db9d4c
diff --git a/docs/guides/working_with_data/plotting.md b/docs/guides/working_with_data/plotting.md
index ee5f1e92ea..b59fdc3094 100644
--- a/docs/guides/working_with_data/plotting.md
+++ b/docs/guides/working_with_data/plotting.md
@@ -20,7 +20,7 @@ marimo automatically sends the selected data back to Python!
Reactive plots currently require matplotlib, Altair, or Plotly. Matplotlib
supports box and lasso selections (best suited for scatter plots);
selections in Plotly are limited to scatter/scattergl plots, bar charts,
- heatmaps, treemaps, and sunburst charts; Altair supports a larger class
+ histograms, heatmaps, treemaps, and sunburst charts; Altair supports a larger class
of plots for selections.
### matplotlib
@@ -305,7 +305,7 @@ conda install -c conda-forge "vegafusion-python-embed>=1.4.0" "vegafusion>=1.4.0
marimo can render any Plotly plot, but [`mo.ui.plotly`][marimo.ui.plotly] only
supports reactive selections for scatter/scattergl plots, bar charts,
- heatmaps, treemaps, and sunburst charts. If you require other kinds of
+ histograms, heatmaps, treemaps, and sunburst charts. If you require other kinds of
selection, please [file an issue](https://github.com/marimo-team/marimo/issues).
/// marimo-embed
diff --git a/examples/third_party/plotly/histogram.py b/examples/third_party/plotly/histogram.py
new file mode 100644
index 0000000000..7dd9746ff5
--- /dev/null
+++ b/examples/third_party/plotly/histogram.py
@@ -0,0 +1,190 @@
+# /// script
+# requires-python = ">=3.9"
+# dependencies = [
+# "marimo",
+# "plotly==6.5.1",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.20.2"
+app = marimo.App(width="medium")
+
+
+def _():
+ import random
+
+ import marimo as mo
+ import plotly.graph_objects as go
+
+ return go, mo, random
+
+
+def _(mo):
+ mo.md("""
+ # Reactive Plotly Histograms
+
+ This example demonstrates reactive histogram selections with `mo.ui.plotly`.
+
+ Select bins by dragging a box (or use lasso with Shift). Selections are
+ returned to Python as selected rows with `pointIndex` values.
+ """)
+ return
+
+
+def _(go, mo, random):
+ mo.md("## Numeric Histogram")
+
+ numeric_rng = random.Random(42)
+ values = [numeric_rng.gauss(0, 1.0) for _ in range(900)]
+
+ numeric_fig = go.Figure(
+ data=go.Histogram(
+ x=values,
+ nbinsx=28,
+ marker_color="#1f77b4",
+ opacity=0.85,
+ name="numeric",
+ )
+ )
+ numeric_fig.update_layout(
+ title="Numeric Histogram",
+ xaxis_title="value",
+ yaxis_title="count",
+ dragmode="select",
+ )
+
+ numeric_hist = mo.ui.plotly(numeric_fig)
+ numeric_hist
+ return numeric_hist, values
+
+
+def _(numeric_hist, values):
+ selected_rows = numeric_hist.value or []
+
+ # Show first selected original values by pointIndex.
+ mapped_original_values = [
+ values[row["pointIndex"]]
+ for row in selected_rows[:10]
+ if isinstance(row.get("pointIndex"), int)
+ ]
+
+ return mapped_original_values, selected_rows
+
+
+def _(mapped_original_values, mo, numeric_hist, selected_rows):
+ mo.md(f"""
+ ### Numeric Selection Output
+
+ **Selected rows:** {len(selected_rows)}
+
+ **Selected indices:** {len(numeric_hist.indices)}
+
+ **Selection range:** {numeric_hist.ranges}
+
+ **First mapped original values (using pointIndex):**
+ {mapped_original_values}
+ """)
+ return
+
+
+def _(go, mo, random):
+ mo.md("## Categorical Histogram")
+
+ categorical_rng = random.Random(7)
+ categories = [
+ categorical_rng.choice(["A", "B", "C", "D"]) for _ in range(500)
+ ]
+
+ categorical_fig = go.Figure(
+ data=go.Histogram(
+ x=categories,
+ marker_color="#2ca02c",
+ opacity=0.85,
+ name="categorical",
+ )
+ )
+ categorical_fig.update_layout(
+ title="Categorical Histogram",
+ xaxis_title="category",
+ yaxis_title="count",
+ dragmode="select",
+ )
+
+ categorical_hist = mo.ui.plotly(categorical_fig)
+ categorical_hist
+ return (categorical_hist,)
+
+
+def _(categorical_hist, mo):
+ mo.md(f"""
+ ### Categorical Selection Output
+
+ **Selected rows:** {len(categorical_hist.value)}
+
+ **Selected indices:** {len(categorical_hist.indices)}
+
+ **Selection range:** {categorical_hist.ranges}
+
+ **Preview:**
+ {categorical_hist.value[:10]}
+ """)
+ return
+
+
+def _(go, mo, random):
+ mo.md("## Horizontal Histogram")
+
+ horizontal_rng = random.Random(19)
+ y_values = [horizontal_rng.gauss(50, 12) for _ in range(800)]
+
+ horizontal_fig = go.Figure(
+ data=go.Histogram(
+ y=y_values,
+ orientation="h",
+ nbinsy=24,
+ marker_color="#ff7f0e",
+ opacity=0.85,
+ name="horizontal",
+ )
+ )
+ horizontal_fig.update_layout(
+ title="Horizontal Histogram",
+ xaxis_title="count",
+ yaxis_title="value",
+ dragmode="select",
+ )
+
+ horizontal_hist = mo.ui.plotly(horizontal_fig)
+ horizontal_hist
+ return (horizontal_hist,)
+
+
+def _(horizontal_hist, mo):
+ mo.md(f"""
+ ### Horizontal Selection Output
+
+ **Selected rows:** {len(horizontal_hist.value)}
+
+ **Selected indices:** {len(horizontal_hist.indices)}
+
+ **Selection range:** {horizontal_hist.ranges}
+
+ **Preview:**
+ {horizontal_hist.value[:10]}
+ """)
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx b/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx
index ed115223c8..fe90fac039 100644
--- a/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx
+++ b/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx
@@ -250,6 +250,7 @@ const STANDARD_POINT_KEYS: string[] = [
"lon",
"curveNumber",
"pointNumber",
+ "pointNumbers",
"pointIndex",
];
@@ -263,6 +264,8 @@ function extractPoints(
let parser: PlotlyTemplateParser | undefined;
return points.map((point) => {
+ const standardPointFields = pick(point, STANDARD_POINT_KEYS);
+
// Get the first hovertemplate
const hovertemplate = Array.isArray(point.data.hovertemplate)
? point.data.hovertemplate[0]
@@ -271,13 +274,16 @@ function extractPoints(
// For chart types with standard point keys (e.g. heatmaps),
// or when there's no hovertemplate, pick keys directly from the point.
if (!hovertemplate || point.data?.type === "heatmap") {
- return pick(point, STANDARD_POINT_KEYS);
+ return standardPointFields;
}
// Update or create a parser
parser = parser
? parser.update(hovertemplate)
: createParser(hovertemplate);
- return parser.parse(point);
+ return {
+ ...standardPointFields,
+ ...parser.parse(point),
+ };
});
}
diff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.py
index 1660e00b51..9af4a26ef7 100644
--- a/marimo/_plugins/ui/_impl/plotly.py
+++ b/marimo/_plugins/ui/_impl/plotly.py
@@ -136,7 +136,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, treemap charts, sunburst charts, and heatmaps.
+ charts, bar charts, histograms, treemap charts, sunburst charts, and heatmaps.
Examples:
```python
@@ -256,8 +256,12 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):
[y_axis] = y_axes if len(y_axes) == 1 else [None]
for trace in figure.data:
- # Skip heatmap and bar traces - they're handled separately below
- if getattr(trace, "type", None) in ("heatmap", "bar"):
+ # Skip trace types handled separately in _convert_value
+ if getattr(trace, "type", None) in (
+ "heatmap",
+ "bar",
+ "histogram",
+ ):
continue
x_data = getattr(trace, "x", None)
y_data = getattr(trace, "y", None)
@@ -393,6 +397,18 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):
self._figure, self._selection_data
)
+ has_histogram = any(
+ getattr(trace, "type", None) == "histogram"
+ for trace in self._figure.data
+ )
+
+ # For histograms, convert selected bins/ranges to underlying sample rows.
+ # This enables row-level reactive workflows from histogram selections.
+ if has_histogram:
+ _append_histogram_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")
@@ -861,6 +877,309 @@ def _extract_heatmap_cells_fallback(
return selected_cells
+def _append_histogram_points_to_selection(
+ figure: go.Figure, selection_data: dict[str, Any]
+) -> None:
+ """Append histogram sample rows to selection data.
+
+ Histogram selection events are bin-level on the frontend. This function
+ converts selected bins/ranges to underlying sample rows so .value behaves
+ like row-level selections from scatter plots.
+ """
+ all_points = cast(list[dict[str, Any]], selection_data.get("points", []))
+ all_indices = cast(list[Any], selection_data.get("indices", []))
+ range_value = selection_data.get("range")
+
+ histogram_points: list[dict[str, Any]] = []
+
+ if isinstance(range_value, dict):
+ histogram_points = _extract_histogram_points_from_range(
+ figure, cast(dict[str, Any], range_value)
+ )
+
+ # Lasso selections may not include a rectangular range. In that case, use
+ # the selected histogram bin payload (pointNumbers) to recover samples.
+ if not histogram_points:
+ histogram_points = _extract_histogram_points_from_bins(
+ figure, all_points
+ )
+
+ if not histogram_points:
+ return
+
+ histogram_curve_numbers = {
+ trace_idx
+ for trace_idx, trace in enumerate(figure.data)
+ if getattr(trace, "type", None) == "histogram"
+ }
+
+ # Drop existing histogram bin-level points, keep points from other traces.
+ filtered_points: list[dict[str, Any]] = []
+ filtered_indices: list[int] = []
+ seen = set()
+
+ for point_idx, point in enumerate(all_points):
+ if not point:
+ continue
+
+ curve_number = point.get("curveNumber")
+ if curve_number in histogram_curve_numbers:
+ continue
+
+ filtered_points.append(point)
+ if point_idx < len(all_indices) and isinstance(
+ all_indices[point_idx], int
+ ):
+ filtered_indices.append(all_indices[point_idx])
+ elif isinstance(point.get("pointIndex"), int):
+ filtered_indices.append(point["pointIndex"])
+
+ key = (point.get("pointIndex"), point.get("curveNumber"))
+ if key != (None, None):
+ seen.add(key)
+
+ # Merge histogram sample rows with deduplication by (curveNumber, pointIndex).
+ for point in histogram_points:
+ key = (point.get("pointIndex"), point.get("curveNumber"))
+ if key in seen:
+ continue
+ seen.add(key)
+ filtered_points.append(point)
+ if "pointIndex" in point:
+ filtered_indices.append(cast(int, point["pointIndex"]))
+
+ selection_data["points"] = filtered_points
+ selection_data["indices"] = filtered_indices
+
+
+def _extract_histogram_points_from_range(
+ figure: go.Figure, range_data: dict[str, Any]
+) -> list[dict[str, Any]]:
+ """Extract histogram sample rows that fall in a selection range."""
+ if DependencyManager.numpy.has():
+ return _extract_histogram_points_numpy(figure, range_data)
+ return _extract_histogram_points_fallback(figure, range_data)
+
+
+def _extract_histogram_points_numpy(
+ figure: go.Figure, range_data: dict[str, Any]
+) -> list[dict[str, Any]]:
+ """Extract histogram sample rows using numpy for better performance."""
+ import numpy as np
+
+ selected_points: list[dict[str, Any]] = []
+
+ for trace_idx, trace in enumerate(figure.data):
+ if getattr(trace, "type", None) != "histogram":
+ continue
+
+ orientation = getattr(trace, "orientation", "v")
+ if orientation is None:
+ orientation = "v"
+
+ axis_key = "y" if orientation == "h" else "x"
+ axis_range = range_data.get(axis_key)
+ axis_data = getattr(trace, axis_key, None)
+
+ if axis_data is None or not axis_range:
+ continue
+
+ axis_min, axis_max = min(axis_range), max(axis_range)
+ axis_arr = np.asarray(axis_data)
+
+ if axis_arr.size == 0:
+ continue
+
+ axis_is_orderable = _is_orderable_axis(axis_arr, axis_min)
+ axis_min_parsed = (
+ _parse_datetime_bound(axis_min) if axis_is_orderable else axis_min
+ )
+ axis_max_parsed = (
+ _parse_datetime_bound(axis_max) if axis_is_orderable else axis_max
+ )
+
+ if axis_is_orderable:
+ axis_mask = (axis_arr >= axis_min_parsed) & (
+ axis_arr <= axis_max_parsed
+ )
+ else:
+ category_positions = {
+ value: idx
+ for idx, value in enumerate(dict.fromkeys(axis_data))
+ }
+ position_arr = np.asarray(
+ [category_positions[value] for value in axis_data]
+ )
+ axis_mask = (axis_max > position_arr - 0.5) & (
+ axis_min < position_arr + 0.5
+ )
+
+ selected_indices = np.where(axis_mask)[0]
+ for point_idx in selected_indices:
+ point = _build_histogram_sample_point(
+ trace, trace_idx, int(point_idx)
+ )
+ if point is not None:
+ selected_points.append(point)
+
+ return selected_points
+
+
+def _extract_histogram_points_fallback(
+ figure: go.Figure, range_data: dict[str, Any]
+) -> list[dict[str, Any]]:
+ """Extract histogram sample rows using pure Python."""
+ selected_points: list[dict[str, Any]] = []
+
+ for trace_idx, trace in enumerate(figure.data):
+ if getattr(trace, "type", None) != "histogram":
+ continue
+
+ orientation = getattr(trace, "orientation", "v")
+ if orientation is None:
+ orientation = "v"
+
+ axis_key = "y" if orientation == "h" else "x"
+ axis_range = range_data.get(axis_key)
+ axis_data = getattr(trace, axis_key, None)
+
+ if axis_data is None or not axis_range:
+ continue
+
+ axis_min, axis_max = min(axis_range), max(axis_range)
+ category_positions = {
+ value: idx for idx, value in enumerate(dict.fromkeys(axis_data))
+ }
+
+ for point_idx, axis_value in enumerate(axis_data):
+ axis_in_range = False
+
+ if _is_orderable_value(axis_value) and _is_orderable_value(
+ axis_min
+ ):
+ axis_min_p = _parse_datetime_bound(axis_min)
+ axis_max_p = _parse_datetime_bound(axis_max)
+ axis_in_range = axis_min_p <= axis_value <= axis_max_p
+ else:
+ position = category_positions[axis_value]
+ bin_min = position - 0.5
+ bin_max = position + 0.5
+ axis_in_range = not (
+ axis_max <= bin_min or axis_min >= bin_max
+ )
+
+ if axis_in_range:
+ point = _build_histogram_sample_point(
+ trace, trace_idx, point_idx
+ )
+ if point is not None:
+ selected_points.append(point)
+
+ return selected_points
+
+
+def _extract_histogram_points_from_bins(
+ figure: go.Figure, points: list[dict[str, Any]]
+) -> list[dict[str, Any]]:
+ """Extract histogram sample rows from selected bin payloads."""
+ selected_points: list[dict[str, Any]] = []
+
+ for point in points:
+ curve_number = point.get("curveNumber")
+ if not isinstance(curve_number, int):
+ continue
+ if not (0 <= curve_number < len(figure.data)):
+ continue
+
+ trace = figure.data[curve_number]
+ if getattr(trace, "type", None) != "histogram":
+ continue
+
+ point_numbers = point.get("pointNumbers")
+ if not isinstance(point_numbers, list):
+ continue
+
+ for point_number in point_numbers:
+ if not isinstance(point_number, int):
+ continue
+ sample_point = _build_histogram_sample_point(
+ trace, curve_number, point_number
+ )
+ if sample_point is not None:
+ selected_points.append(sample_point)
+
+ return selected_points
+
+
+def _build_histogram_sample_point(
+ trace: Any, trace_idx: int, point_idx: int
+) -> Optional[dict[str, Any]]:
+ """Build a row-level selection payload point from a histogram trace."""
+ orientation = getattr(trace, "orientation", "v")
+ if orientation is None:
+ orientation = "v"
+
+ axis_key = "y" if orientation == "h" else "x"
+ paired_axis_key = "x" if orientation == "h" else "y"
+
+ axis_value = _get_indexed_value(getattr(trace, axis_key, None), point_idx)
+ if axis_value is None:
+ return None
+
+ point: dict[str, Any] = {
+ axis_key: axis_value,
+ "pointIndex": point_idx,
+ "curveNumber": trace_idx,
+ }
+
+ paired_axis_value = _get_indexed_value(
+ getattr(trace, paired_axis_key, None), point_idx
+ )
+ if paired_axis_value is not None:
+ point[paired_axis_key] = paired_axis_value
+
+ name = getattr(trace, "name", None)
+ if name:
+ point["name"] = name
+
+ customdata = _get_indexed_value(
+ getattr(trace, "customdata", None), point_idx
+ )
+ if customdata is not None:
+ point["customdata"] = customdata
+
+ text = _get_indexed_value(getattr(trace, "text", None), point_idx)
+ if text is not None:
+ point["text"] = text
+
+ hovertext = _get_indexed_value(
+ getattr(trace, "hovertext", None), point_idx
+ )
+ if hovertext is not None:
+ point["hovertext"] = hovertext
+
+ return point
+
+
+def _get_indexed_value(data: Any, index: int) -> Any:
+ """Safely extract an indexed value from array-like or scalar data."""
+ if data is None:
+ return None
+
+ if isinstance(data, str):
+ return data
+
+ try:
+ if not (0 <= index < len(data)):
+ return None
+ except TypeError:
+ # Scalar value
+ return data
+
+ value = data[index]
+ return value.item() if hasattr(value, "item") else value
+
+
def _append_bar_items_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 b24aff5982..bb13d8f5b5 100644
--- a/tests/_plugins/ui/_impl/test_plotly.py
+++ b/tests/_plugins/ui/_impl/test_plotly.py
@@ -17,6 +17,8 @@ from marimo._plugins.ui._impl.plotly import (
_extract_bars_numpy,
_extract_heatmap_cells_fallback,
_extract_heatmap_cells_numpy,
+ _extract_histogram_points_fallback,
+ _extract_histogram_points_numpy,
_extract_scatter_points_fallback,
_extract_scatter_points_numpy,
plotly,
@@ -2123,6 +2125,197 @@ def test_bar_chart_mixed_with_scatter() -> None:
assert any(isinstance(r.get("x"), int) for r in result)
+# ============================================================================
+# Histogram Tests
+# ============================================================================
+
+
+def test_histogram_basic() -> None:
+ """Test that histograms can be created (supported chart type)."""
+ fig = go.Figure(data=go.Histogram(x=[0.1, 0.2, 0.3, 0.4]))
+ plot = plotly(fig)
+
+ assert plot is not None
+ assert plot.value == []
+
+
+def test_histogram_selection_vertical_row_level() -> None:
+ """Test histogram vertical selection returns underlying sample rows."""
+ x_values = [-1.2, -0.4, 0.1, 0.6, 1.4]
+ fig = go.Figure(data=go.Histogram(x=x_values))
+ plot = plotly(fig)
+
+ selection = {
+ "range": {"x": [-0.5, 0.7], "y": [0, 50]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 3
+ assert [point["x"] for point in result] == [-0.4, 0.1, 0.6]
+ assert [point["pointIndex"] for point in result] == [1, 2, 3]
+ assert all(point["curveNumber"] == 0 for point in result)
+
+
+def test_histogram_selection_horizontal_row_level() -> None:
+ """Test horizontal histogram selection uses y-range for row extraction."""
+ y_values = [5, 10, 15, 20]
+ fig = go.Figure(data=go.Histogram(y=y_values, orientation="h"))
+ plot = plotly(fig)
+
+ selection = {
+ "range": {"x": [0, 50], "y": [9, 18]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 2
+ assert [point["y"] for point in result] == [10, 15]
+ assert [point["pointIndex"] for point in result] == [1, 2]
+
+
+def test_histogram_selection_preserves_optional_fields() -> None:
+ """Test histogram row extraction includes y/customdata/text when present."""
+ fig = go.Figure(
+ data=go.Histogram(
+ x=[0, 1, 2, 3],
+ y=[10, 20, 30, 40],
+ text=["a", "b", "c", "d"],
+ customdata=[["id0"], ["id1"], ["id2"], ["id3"]],
+ histfunc="sum",
+ )
+ )
+ plot = plotly(fig)
+
+ selection = {
+ "range": {"x": [0.5, 2.5], "y": [0, 100]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 2
+ assert result[0] == {
+ "x": 1,
+ "y": 20,
+ "pointIndex": 1,
+ "curveNumber": 0,
+ "customdata": ["id1"],
+ "text": "b",
+ }
+ assert result[1] == {
+ "x": 2,
+ "y": 30,
+ "pointIndex": 2,
+ "curveNumber": 0,
+ "customdata": ["id2"],
+ "text": "c",
+ }
+
+
+def test_histogram_selection_from_point_numbers() -> None:
+ """Test histogram extraction from pointNumbers (lasso/no-range events)."""
+ fig = go.Figure(data=go.Histogram(x=[0.1, 0.2, 0.3, 0.4, 0.5]))
+ plot = plotly(fig)
+
+ selection = {
+ "points": [
+ {
+ "curveNumber": 0,
+ "pointNumber": 0,
+ "pointNumbers": [1, 3],
+ }
+ ],
+ "indices": [0],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert result == [
+ {"x": 0.2, "pointIndex": 1, "curveNumber": 0},
+ {"x": 0.4, "pointIndex": 3, "curveNumber": 0},
+ ]
+ assert plot.indices == [1, 3]
+
+
+def test_histogram_initial_selection() -> None:
+ """Test that initial selection works with histograms."""
+ fig = go.Figure(data=go.Histogram(x=[0.1, 0.9, 1.1, 2.0]))
+ fig.add_selection(x0=0, x1=1, y0=0, y1=100, xref="x", yref="y")
+
+ plot = plotly(fig)
+ initial_value = plot._args.initial_value
+
+ assert initial_value["range"]["x"] == [0, 1]
+ assert initial_value["range"]["y"] == [0, 100]
+ assert initial_value["points"] == [
+ {"x": 0.1, "pointIndex": 0, "curveNumber": 0},
+ {"x": 0.9, "pointIndex": 1, "curveNumber": 0},
+ ]
+ assert initial_value["indices"] == [0, 1]
+
+
+def test_histogram_mixed_with_scatter_drops_bin_payload() -> None:
+ """Test histogram bins are replaced with row-level points in mixed charts."""
+ fig = go.Figure()
+ fig.add_trace(go.Scatter(x=[0.1, 0.4], y=[10, 20], mode="markers"))
+ fig.add_trace(go.Histogram(x=[0.1, 0.2, 0.7]))
+ plot = plotly(fig)
+
+ selection = {
+ "range": {"x": [0.0, 0.3], "y": [0, 50]},
+ "points": [
+ {"x": 0.1, "y": 10, "curveNumber": 0, "pointIndex": 0},
+ {"x": 0.2, "y": 2, "curveNumber": 1, "pointNumber": 0},
+ ],
+ "indices": [0, 0],
+ }
+
+ result = plot._convert_value(selection)
+
+ scatter_points = [p for p in result if p.get("curveNumber") == 0]
+ histogram_points = [p for p in result if p.get("curveNumber") == 1]
+
+ assert scatter_points == [
+ {"x": 0.1, "y": 10, "curveNumber": 0, "pointIndex": 0}
+ ]
+ assert histogram_points == [
+ {"x": 0.1, "pointIndex": 0, "curveNumber": 1},
+ {"x": 0.2, "pointIndex": 1, "curveNumber": 1},
+ ]
+
+
+def test_histogram_preserves_indices_when_empty_points_exist() -> None:
+ """Test index alignment when frontend emits empty point dicts."""
+ fig = go.Figure()
+ fig.add_trace(go.Scatter(x=[0.1, 0.4], y=[10, 20], mode="markers"))
+ fig.add_trace(go.Histogram(x=[0.1, 0.2, 0.7]))
+ plot = plotly(fig)
+
+ # The first empty dict simulates frontend payload entries with dropped fields.
+ selection = {
+ "points": [
+ {},
+ {"x": 0.1, "y": 10, "curveNumber": 0, "pointIndex": 0},
+ {"curveNumber": 1, "pointNumbers": [1]},
+ ],
+ "indices": [999, 0, 0],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert result == [
+ {"x": 0.1, "y": 10, "curveNumber": 0, "pointIndex": 0},
+ {"x": 0.2, "pointIndex": 1, "curveNumber": 1},
+ ]
+ assert plot.indices == [0, 1]
+
+
# Test numpy vs fallback implementations
@@ -2218,6 +2411,46 @@ def test_bar_numpy_and_fallback_match_horizontal() -> None:
assert np_bar["curveNumber"] == fb_bar["curveNumber"]
+def test_histogram_numpy_and_fallback_match_numeric() -> None:
+ """Test histogram numpy and fallback extraction match on numeric data."""
+ fig = go.Figure(data=go.Histogram(x=[-1.0, -0.5, 0.0, 0.5, 1.0]))
+ range_data = {"x": [-0.5, 0.6], "y": [0, 50]}
+
+ numpy_result = _extract_histogram_points_numpy(fig, range_data)
+ fallback_result = _extract_histogram_points_fallback(fig, range_data)
+
+ assert len(numpy_result) == len(fallback_result)
+
+ def sort_key(point: dict[str, Any]) -> tuple[Any, ...]:
+ return (point["pointIndex"], point["curveNumber"])
+
+ numpy_sorted = sorted(numpy_result, key=sort_key)
+ fallback_sorted = sorted(fallback_result, key=sort_key)
+
+ for np_point, fb_point in zip(numpy_sorted, fallback_sorted):
+ assert np_point == fb_point
+
+
+def test_histogram_numpy_and_fallback_match_categorical() -> None:
+ """Test histogram numpy and fallback extraction match on categories."""
+ fig = go.Figure(data=go.Histogram(x=["A", "B", "A", "C", "B"]))
+ range_data = {"x": [0.5, 1.5], "y": [0, 50]}
+
+ numpy_result = _extract_histogram_points_numpy(fig, range_data)
+ fallback_result = _extract_histogram_points_fallback(fig, range_data)
+
+ assert len(numpy_result) == len(fallback_result)
+
+ def sort_key(point: dict[str, Any]) -> tuple[Any, ...]:
+ return (point["pointIndex"], point["curveNumber"])
+
+ numpy_sorted = sorted(numpy_result, key=sort_key)
+ fallback_sorted = sorted(fallback_result, key=sort_key)
+
+ for np_point, fb_point in zip(numpy_sorted, fallback_sorted):
+ assert np_point == fb_point
+
+
def test_heatmap_numpy_and_fallback_numeric_axes() -> None:
"""Test numpy and fallback with numeric axes produce identical results."""
fig = go.Figure(