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.

enable single-click selection for reactive Plotly charts (#8782)

axssel750fb859be41
diff --git a/docs/api/plotting.md b/docs/api/plotting.md
index fa9f546701..d5c9915583 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, 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.ui.plotly
diff --git a/frontend/src/plugins/impl/__tests__/SliderPlugin.test.tsx b/frontend/src/plugins/impl/__tests__/SliderPlugin.test.tsx
index 34b4bfae68..9ded85e333 100644
--- a/frontend/src/plugins/impl/__tests__/SliderPlugin.test.tsx
+++ b/frontend/src/plugins/impl/__tests__/SliderPlugin.test.tsx
@@ -9,6 +9,35 @@ import { store } from "@/core/state/jotai";
import type { IPluginProps } from "../../types";
import { SliderPlugin } from "../SliderPlugin";
+vi.mock("@/components/ui/slider", () => ({
+ Slider: ({
+ disabled,
+ onValueChange,
+ onValueCommit,
+ value,
+ }: {
+ disabled?: boolean;
+ onValueChange?: (value: number[]) => void;
+ onValueCommit?: (value: number[]) => void;
+ value: number[];
+ }) => (
+ <div>
+ <button
+ aria-label="Slider change"
+ disabled={disabled}
+ onClick={() => onValueChange?.([value[0] + 1])}
+ type="button"
+ />
+ <button
+ aria-label="Slider commit"
+ disabled={disabled}
+ onClick={() => onValueCommit?.(value)}
+ type="button"
+ />
+ </div>
+ ),
+}));
+
SetupMocks.resizeObserver();
describe("SliderPlugin", () => {
@@ -51,46 +80,45 @@ describe("SliderPlugin", () => {
const plugin = new SliderPlugin();
const setValue = vi.fn();
const props = createProps(false, false, setValue);
- const { container } = render(plugin.render(props));
+ const { getByRole } = render(plugin.render(props));
act(() => {
vi.advanceTimersByTime(0);
});
- const thumb = container.querySelector('[role="slider"]');
- expect(thumb).toBeTruthy();
+ const changeButton = getByRole("button", { name: "Slider change" });
- // Radix UI Slider updates on keyboard ArrowRight/ArrowLeft
act(() => {
- (thumb as HTMLElement)?.focus();
- fireEvent.keyDown(thumb!, { key: "ArrowRight" });
+ fireEvent.click(changeButton);
});
expect(setValue).toHaveBeenCalledWith(6);
});
- it("slider does not trigger setValue immediately when debounce is true", () => {
+ it("slider waits until commit before calling setValue when debounce is true", () => {
const plugin = new SliderPlugin();
const setValue = vi.fn();
const props = createProps(true, false, setValue);
- const { container } = render(plugin.render(props));
+ const { getByRole } = render(plugin.render(props));
act(() => {
vi.advanceTimersByTime(0);
});
- const thumb = container.querySelector('[role="slider"]');
+ const changeButton = getByRole("button", { name: "Slider change" });
+ const commitButton = getByRole("button", { name: "Slider commit" });
act(() => {
- (thumb as HTMLElement)?.focus();
- // Simulate just a programmatic change that Radix would trigger via pointer move
- // which fires onValueChange but not onValueCommit yet
- // Because we can't easily separated Radix's internal pointer events in jsdom, we
- // test the main issue: editable input. We can trust Radix's onValueChange vs onValueCommit.
+ fireEvent.click(changeButton);
});
- // We verified above that NumberField works when debounce=true
expect(setValue).not.toHaveBeenCalled();
+
+ act(() => {
+ fireEvent.click(commitButton);
+ });
+
+ expect(setValue).toHaveBeenCalledWith(6);
});
it("editable input triggers setValue immediately even when slider debounce is true", () => {
diff --git a/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx b/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx
index c20f375683..cfd3e333fb 100644
--- a/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx
+++ b/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx
@@ -15,7 +15,11 @@ import { useDeepCompareMemoize } from "@/hooks/useDeepCompareMemoize";
import { useScript } from "@/hooks/useScript";
import { Arrays } from "@/utils/arrays";
import { Objects } from "@/utils/objects";
-import { createParser, type PlotlyTemplateParser } from "./parse-from-template";
+import {
+ extractClickSelection,
+ extractIndices,
+ extractPoints,
+} from "./selection";
import { usePlotlyLayout } from "./usePlotlyLayout";
interface Data {
@@ -23,12 +27,9 @@ interface Data {
config: Partial<Plotly.Config>;
}
-type AxisName = string;
-type AxisDatum = unknown;
-
type T =
| {
- points?: Record<AxisName, AxisDatum>[] | Plotly.PlotDatum[];
+ points?: Record<string, unknown>[] | Plotly.PlotDatum[];
indices?: number[];
range?: {
x?: number[];
@@ -202,19 +203,13 @@ export const PlotlyComponent = memo(
if (!evt) {
return;
}
- // Only handle clicks for chart types where box/lasso selection
- // (onSelected) doesn't work, such as heatmaps.
- const isHeatmap = evt.points.some(
- (point) => point.data?.type === "heatmap",
- );
- if (!isHeatmap) {
+
+ const clickSelection = extractClickSelection(evt);
+ if (!clickSelection) {
return;
}
- setValue((prev) => ({
- ...prev,
- points: extractPoints(evt.points),
- indices: evt.points.map((point) => point.pointIndex),
- }));
+
+ setValue((prev) => ({ ...prev, ...clickSelection }));
})}
onSelected={useEvent((evt: Readonly<Plotly.PlotSelectionEvent>) => {
if (!evt) {
@@ -226,7 +221,7 @@ export const PlotlyComponent = memo(
selections:
"selections" in evt ? (evt.selections as unknown[]) : [],
points: extractPoints(evt.points),
- indices: evt.points.map((point) => point.pointIndex),
+ indices: extractIndices(evt.points),
range: evt.range,
}));
})}
@@ -241,54 +236,3 @@ export const PlotlyComponent = memo(
},
);
PlotlyComponent.displayName = "PlotlyComponent";
-
-/**
- * This is a hack to extract the points with their original keys,
- * instead of the ones that Plotly uses internally,
- * by using the hovertemplate.
- */
-const STANDARD_POINT_KEYS: string[] = [
- "x",
- "y",
- "z",
- "lat",
- "lon",
- "curveNumber",
- "pointNumber",
- "pointNumbers",
- "pointIndex",
-];
-
-function extractPoints(
- points: Plotly.PlotDatum[],
-): Record<AxisName, AxisDatum>[] {
- if (!points) {
- return [];
- }
-
- let parser: PlotlyTemplateParser | undefined;
-
- return points.map((point) => {
- const standardPointFields = Objects.pick(point, STANDARD_POINT_KEYS);
-
- // Get the first hovertemplate
- const hovertemplate = Array.isArray(point.data.hovertemplate)
- ? point.data.hovertemplate[0]
- : point.data.hovertemplate;
-
- // 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 standardPointFields;
- }
-
- // Update or create a parser
- parser = parser
- ? parser.update(hovertemplate)
- : createParser(hovertemplate);
- return {
- ...standardPointFields,
- ...parser.parse(point),
- };
- });
-}
diff --git a/frontend/src/plugins/impl/plotly/__tests__/selection.test.ts b/frontend/src/plugins/impl/plotly/__tests__/selection.test.ts
new file mode 100644
index 0000000000..f6436651f6
--- /dev/null
+++ b/frontend/src/plugins/impl/plotly/__tests__/selection.test.ts
@@ -0,0 +1,237 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type * as Plotly from "plotly.js";
+import { describe, expect, it } from "vitest";
+import {
+ extractClickSelection,
+ extractIndices,
+ extractPoints,
+} from "../selection";
+
+interface PlotlyPointInput {
+ data: {
+ type: string;
+ hovertemplate?: string | string[];
+ };
+ [key: string]: unknown;
+}
+
+function makePoint(point: PlotlyPointInput): Plotly.PlotDatum {
+ return point as unknown as Plotly.PlotDatum;
+}
+
+function makeClickEvent(
+ points: Plotly.PlotDatum[],
+): Readonly<Plotly.PlotMouseEvent> {
+ return { points } as unknown as Readonly<Plotly.PlotMouseEvent>;
+}
+
+describe("extractIndices", () => {
+ it("prefers pointIndex and falls back to pointNumber", () => {
+ const points = [
+ makePoint({
+ pointIndex: 2,
+ pointNumber: 99,
+ data: { type: "scatter" },
+ }),
+ makePoint({
+ pointNumber: 4,
+ data: { type: "scattergl" },
+ }),
+ makePoint({
+ data: { type: "heatmap" },
+ }),
+ ];
+
+ expect(extractIndices(points)).toEqual([2, 4]);
+ });
+});
+
+describe("extractPoints", () => {
+ it("extracts parsed scatter payload fields from the hovertemplate", () => {
+ const points = [
+ makePoint({
+ x: 3,
+ y: 7,
+ curveNumber: 0,
+ pointIndex: 1,
+ customdata: ["B"],
+ data: {
+ type: "scatter",
+ hovertemplate:
+ "label=%{customdata[0]}<br>x=%{x}<br>y=%{y}<extra></extra>",
+ },
+ }),
+ ];
+
+ expect(extractPoints(points)).toEqual([
+ {
+ x: 3,
+ y: 7,
+ curveNumber: 0,
+ pointIndex: 1,
+ label: "B",
+ },
+ ]);
+ });
+
+ it("keeps standard heatmap keys without hovertemplate parsing", () => {
+ const points = [
+ makePoint({
+ x: "B",
+ y: "Row 2",
+ z: 6,
+ curveNumber: 0,
+ pointIndex: 5,
+ data: { type: "heatmap", hovertemplate: "ignored=%{z}" },
+ }),
+ ];
+
+ expect(extractPoints(points)).toEqual([
+ {
+ x: "B",
+ y: "Row 2",
+ z: 6,
+ curveNumber: 0,
+ pointIndex: 5,
+ },
+ ]);
+ });
+});
+
+describe("extractClickSelection", () => {
+ it("returns undefined for unsupported trace types", () => {
+ const event = makeClickEvent([
+ makePoint({
+ x: "A",
+ y: 10,
+ pointIndex: 0,
+ data: { type: "bar" },
+ }),
+ ]);
+
+ expect(extractClickSelection(event)).toBeUndefined();
+ });
+
+ it("returns undefined when all points are non-click-selectable trace types", () => {
+ // scatter and scattergl use onSelected (box/lasso) for selection, not onClick.
+ // Clicks on these traces fire both plotly_click and plotly_selected; the
+ // latter provides a range and must be the authoritative source.
+ const event = makeClickEvent([
+ makePoint({
+ x: "ignore",
+ y: 1,
+ pointIndex: 0,
+ data: { type: "bar" },
+ }),
+ makePoint({
+ x: 2,
+ y: 5,
+ curveNumber: 1,
+ pointIndex: 3,
+ data: { type: "scatter" },
+ }),
+ makePoint({
+ x: 4,
+ y: 12,
+ curveNumber: 2,
+ pointNumber: 5,
+ data: { type: "scattergl" },
+ }),
+ ]);
+
+ expect(extractClickSelection(event)).toBeUndefined();
+ });
+
+ it("filters unsupported points and preserves supported click payloads", () => {
+ // bar is unsupported; histogram is supported and its pointNumbers must be
+ // forwarded so the backend can recover the exact sample rows.
+ const event = makeClickEvent([
+ makePoint({
+ x: "ignore",
+ y: 1,
+ pointIndex: 0,
+ data: { type: "bar" },
+ }),
+ makePoint({
+ x: 8,
+ y: 3,
+ curveNumber: 1,
+ pointNumber: 2,
+ pointNumbers: [4, 5, 6],
+ data: { type: "histogram" },
+ }),
+ ]);
+
+ expect(extractClickSelection(event)).toEqual({
+ selections: [],
+ range: undefined,
+ indices: [2],
+ points: [
+ {
+ x: 8,
+ y: 3,
+ curveNumber: 1,
+ pointNumber: 2,
+ pointNumbers: [4, 5, 6],
+ },
+ ],
+ });
+ });
+
+ it("preserves histogram pointNumbers for backend row extraction", () => {
+ const event = makeClickEvent([
+ makePoint({
+ x: 8,
+ y: 2,
+ curveNumber: 0,
+ pointNumber: 3,
+ pointNumbers: [6, 7],
+ data: { type: "histogram" },
+ }),
+ ]);
+
+ expect(extractClickSelection(event)).toEqual({
+ selections: [],
+ range: undefined,
+ indices: [3],
+ points: [
+ {
+ x: 8,
+ y: 2,
+ curveNumber: 0,
+ pointNumber: 3,
+ pointNumbers: [6, 7],
+ },
+ ],
+ });
+ });
+
+ it("preserves standard heatmap click payloads", () => {
+ const event = makeClickEvent([
+ makePoint({
+ x: "C",
+ y: "Row 3",
+ z: 11,
+ curveNumber: 0,
+ pointIndex: 10,
+ data: { type: "heatmap" },
+ }),
+ ]);
+
+ expect(extractClickSelection(event)).toEqual({
+ selections: [],
+ range: undefined,
+ indices: [10],
+ points: [
+ {
+ x: "C",
+ y: "Row 3",
+ z: 11,
+ curveNumber: 0,
+ pointIndex: 10,
+ },
+ ],
+ });
+ });
+});
diff --git a/frontend/src/plugins/impl/plotly/selection.ts b/frontend/src/plugins/impl/plotly/selection.ts
new file mode 100644
index 0000000000..db12b9c3d4
--- /dev/null
+++ b/frontend/src/plugins/impl/plotly/selection.ts
@@ -0,0 +1,118 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { pick } from "lodash-es";
+import type * as Plotly from "plotly.js";
+import { Arrays } from "@/utils/arrays";
+import { createParser, type PlotlyTemplateParser } from "./parse-from-template";
+
+type AxisName = string;
+type AxisDatum = unknown;
+
+export interface PlotlyClickSelection {
+ points: Record<AxisName, AxisDatum>[] | Plotly.PlotDatum[];
+ indices: number[];
+ range: undefined;
+ selections: unknown[];
+}
+
+const CLICK_SELECTABLE_TRACE_TYPES = new Set([
+ "heatmap",
+ "histogram",
+]);
+
+const STANDARD_POINT_KEYS: string[] = [
+ "x",
+ "y",
+ "z",
+ "lat",
+ "lon",
+ "curveNumber",
+ "pointNumber",
+ "pointNumbers",
+ "pointIndex",
+] as const;
+
+function getPointIndex(point: Plotly.PlotDatum): number | undefined {
+ if (typeof point.pointIndex === "number") {
+ return point.pointIndex;
+ }
+
+ if (typeof point.pointNumber === "number") {
+ return point.pointNumber;
+ }
+
+ return undefined;
+}
+
+function isClickSelectablePoint(point: Plotly.PlotDatum): boolean {
+ const traceType = point.data?.type;
+ return typeof traceType === "string"
+ ? CLICK_SELECTABLE_TRACE_TYPES.has(traceType)
+ : false;
+}
+
+export function extractIndices(points: Plotly.PlotDatum[]): number[] {
+ return points.flatMap((point) => {
+ const index = getPointIndex(point);
+ return typeof index === "number" ? [index] : [];
+ });
+}
+
+/**
+ * This is a hack to extract the points with their original keys,
+ * instead of the ones that Plotly uses internally,
+ * by using the hovertemplate.
+ */
+export function extractPoints(
+ points: Plotly.PlotDatum[],
+): Record<AxisName, AxisDatum>[] {
+ if (!points) {
+ return [];
+ }
+
+ 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]
+ : point.data.hovertemplate;
+
+ // 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 standardPointFields;
+ }
+
+ // Update or create a parser
+ parser = parser
+ ? parser.update(hovertemplate)
+ : createParser(hovertemplate);
+ return {
+ ...standardPointFields,
+ ...parser.parse(point),
+ };
+ });
+}
+
+export function extractClickSelection(
+ evt: Readonly<Plotly.PlotMouseEvent>,
+): PlotlyClickSelection | undefined {
+ if (!evt.points?.length) {
+ return undefined;
+ }
+
+ const points = evt.points.filter(isClickSelectablePoint);
+ if (points.length === 0) {
+ return undefined;
+ }
+
+ return {
+ selections: Arrays.EMPTY,
+ points: extractPoints(points),
+ indices: extractIndices(points),
+ range: undefined,
+ };
+}
diff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.py
index 9df2ad5a40..aa308c7954 100644
--- a/marimo/_plugins/ui/_impl/plotly.py
+++ b/marimo/_plugins/ui/_impl/plotly.py
@@ -292,6 +292,34 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):
if has_heatmap and initial_value.get("range"):
_append_heatmap_cells_to_selection(figure, initial_value)
+ # For histograms, pre-compute sample rows using the selection range.
+ # Interactive events use bin payloads (pointNumbers) for extraction;
+ # programmatic initial selections via add_selection only have a range,
+ # so we resolve sample rows here before _convert_value is called.
+ has_histogram = any(
+ getattr(trace, "type", None) == "histogram"
+ for trace in figure.data
+ )
+ if has_histogram and initial_value.get("range"):
+ histogram_points = _extract_histogram_points_from_range(
+ figure, cast(dict[str, Any], initial_value["range"])
+ )
+ seen = {
+ (p.get("pointIndex"), p.get("curveNumber"))
+ for p in selected_points
+ }
+ for point in histogram_points:
+ key = (point.get("pointIndex"), point.get("curveNumber"))
+ if key not in seen:
+ seen.add(key)
+ selected_points.append(point)
+ if isinstance(point.get("pointIndex"), int):
+ selected_indices.append(
+ cast(int, point["pointIndex"])
+ )
+ initial_value["points"] = selected_points
+ initial_value["indices"] = selected_indices
+
# Note: Bar chart extraction is handled in _convert_value, not here
# This avoids duplicate extraction since _convert_value is called
# during super().__init__() with the initial_value
@@ -936,37 +964,30 @@ def _append_histogram_points_to_selection(
"""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.
+ converts selected bin payloads (pointNumbers) to underlying sample rows so
+ .value behaves like row-level selections from scatter plots.
+
+ Pre-computed sample rows from fig.add_selection() have no pointNumbers and
+ are passed through the filter unchanged — they do not need re-expansion.
"""
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"
}
+ if not histogram_curve_numbers:
+ return
+
+ # Expand bin payloads (those with pointNumbers) into sample rows.
+ # Points without pointNumbers are pre-computed sample rows (e.g. from
+ # add_selection) and are preserved through the filter step below.
+ histogram_points = _extract_histogram_points_from_bins(figure, all_points)
- # Drop existing histogram bin-level points, keep points from other traces.
+ # Drop only bin-level payloads (those with pointNumbers); keep sample rows
+ # from other traces and pre-computed histogram rows (e.g. add_selection).
filtered_points: list[dict[str, Any]] = []
filtered_indices: list[int] = []
seen = set()
@@ -976,7 +997,7 @@ def _append_histogram_points_to_selection(
continue
curve_number = point.get("curveNumber")
- if curve_number in histogram_curve_numbers:
+ if curve_number in histogram_curve_numbers and "pointNumbers" in point:
continue
filtered_points.append(point)
@@ -991,7 +1012,7 @@ def _append_histogram_points_to_selection(
if key != (None, None):
seen.add(key)
- # Merge histogram sample rows with deduplication by (curveNumber, pointIndex).
+ # Merge bin-expanded sample rows with deduplication by (curveNumber, pointIndex).
for point in histogram_points:
key = (point.get("pointIndex"), point.get("curveNumber"))
if key in seen:
diff --git a/tests/_plugins/ui/_impl/test_plotly.py b/tests/_plugins/ui/_impl/test_plotly.py
index c6b84b9e1a..8f035eb864 100644
--- a/tests/_plugins/ui/_impl/test_plotly.py
+++ b/tests/_plugins/ui/_impl/test_plotly.py
@@ -2226,10 +2226,13 @@ def test_histogram_selection_vertical_row_level() -> None:
fig = go.Figure(data=go.Histogram(x=x_values))
plot = plotly(fig)
+ # Simulate Plotly bin payloads covering indices 1, 2, 3 (-0.4, 0.1, 0.6)
selection = {
- "range": {"x": [-0.5, 0.7], "y": [0, 50]},
- "points": [],
- "indices": [],
+ "points": [
+ {"curveNumber": 0, "pointNumber": 0, "pointNumbers": [1, 2]},
+ {"curveNumber": 0, "pointNumber": 1, "pointNumbers": [3]},
+ ],
+ "indices": [0, 1],
}
result = plot._convert_value(selection)
@@ -2241,15 +2244,17 @@ def test_histogram_selection_vertical_row_level() -> None:
def test_histogram_selection_horizontal_row_level() -> None:
- """Test horizontal histogram selection uses y-range for row extraction."""
+ """Test horizontal histogram selection returns underlying sample rows."""
y_values = [5, 10, 15, 20]
fig = go.Figure(data=go.Histogram(y=y_values, orientation="h"))
plot = plotly(fig)
+ # Simulate Plotly bin payload covering indices 1, 2 (y=10, 15)
selection = {
- "range": {"x": [0, 50], "y": [9, 18]},
- "points": [],
- "indices": [],
+ "points": [
+ {"curveNumber": 0, "pointNumber": 0, "pointNumbers": [1, 2]},
+ ],
+ "indices": [0],
}
result = plot._convert_value(selection)
@@ -2272,10 +2277,12 @@ def test_histogram_selection_preserves_optional_fields() -> None:
)
plot = plotly(fig)
+ # Simulate Plotly bin payload for indices 1, 2 (x=1, x=2)
selection = {
- "range": {"x": [0.5, 2.5], "y": [0, 100]},
- "points": [],
- "indices": [],
+ "points": [
+ {"curveNumber": 0, "pointNumber": 0, "pointNumbers": [1, 2]},
+ ],
+ "indices": [0],
}
result = plot._convert_value(selection)
@@ -2348,11 +2355,12 @@ def test_histogram_mixed_with_scatter_drops_bin_payload() -> None:
fig.add_trace(go.Histogram(x=[0.1, 0.2, 0.7]))
plot = plotly(fig)
+ # Scatter provides per-point payload; histogram provides a bin payload
+ # with pointNumbers covering samples at indices 0 (x=0.1) and 1 (x=0.2).
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},
+ {"curveNumber": 1, "pointNumber": 0, "pointNumbers": [0, 1]},
],
"indices": [0, 0],
}
@@ -2512,6 +2520,69 @@ def test_histogram_numpy_and_fallback_match_numeric() -> None:
assert np_point == fb_point
+def test_histogram_click_uses_bin_pointnumbers_not_range() -> None:
+ """When a click sends both pointNumbers and a range, bin membership wins.
+
+ In Plotly "select" dragmode, clicking a histogram bar fires both
+ plotly_click and plotly_selected. The latter sets range to the click
+ coordinates. The backend must prioritise the exact bin pointNumbers over
+ raw x-range filtering so that only samples belonging to the clicked bin
+ are returned — not all samples whose x-value happens to fall inside the
+ click range.
+ """
+ x_values = [1.0, 1.5, 2.5, 3.0, 4.0]
+ fig = go.Figure(data=go.Histogram(x=x_values))
+ plot = plotly(fig)
+
+ # Simulates the double-fire scenario: the frontend sends both a range
+ # (from onSelected) and a bin point with pointNumbers (from onClick).
+ # The bin covers samples at indices 0 and 1 (x=1.0, x=1.5).
+ # Raw range filtering on [1.0, 2.0] would also pick up x=1.5 and
+ # potentially x=2.5 depending on bin boundaries — using pointNumbers
+ # ensures only indices 0 and 1 are returned.
+ selection = {
+ "range": {"x": [1.0, 2.0], "y": [0, 10]},
+ "points": [
+ {
+ "x": 1.25,
+ "y": 2,
+ "curveNumber": 0,
+ "pointNumber": 0,
+ "pointNumbers": [0, 1],
+ }
+ ],
+ "indices": [0],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 2
+ assert {p["pointIndex"] for p in result} == {0, 1}
+ assert all(p["x"] in (1.0, 1.5) for p in result)
+
+
+def test_histogram_empty_box_selection_returns_empty() -> None:
+ """Selecting an empty region on a histogram must return no data.
+
+ When the user draws a box/lasso over an area with no histogram bars,
+ Plotly sends points=[] and range={x:[a,b]}. The backend must not use the
+ range to find nearby samples — an empty selection must produce empty output.
+ """
+ x_values = [1.0, 2.0, 3.0, 4.0, 5.0]
+ fig = go.Figure(data=go.Histogram(x=x_values))
+ plot = plotly(fig)
+
+ # Plotly sends empty points when the drawn box covers no bars.
+ selection = {
+ "points": [],
+ "indices": [],
+ "range": {"x": [10.0, 20.0], "y": [0, 10]},
+ }
+
+ result = plot._convert_value(selection)
+ assert result == []
+
+
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"]))