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 scattergl selection support (#8490)

axssel944b8f7bb8b8
diff --git a/docs/api/plotting.md b/docs/api/plotting.md
index 301a3f6245..fa9f546701 100644
--- a/docs/api/plotting.md
+++ b/docs/api/plotting.md
@@ -105,9 +105,9 @@ alt.data_transformers.enable('marimo_csv')
!!! warning "Supported charts"
marimo can render any Plotly plot, but [`mo.ui.plotly`][marimo.ui.plotly] only
- supports reactive selections for scatter plots, bar charts, heatmaps,
- treemaps, and sunburst charts. If you require other kinds of selection,
- please [file an issue](https://github.com/marimo-team/marimo/issues).
+ supports reactive selections for scatter/scattergl plots, bar 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/docs/guides/working_with_data/plotting.md b/docs/guides/working_with_data/plotting.md
index d2735e0c98..ee5f1e92ea 100644
--- a/docs/guides/working_with_data/plotting.md
+++ b/docs/guides/working_with_data/plotting.md
@@ -19,9 +19,9 @@ 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 plots, bar charts, heatmaps,
- treemaps, and sunburst charts; Altair supports a larger class of plots
- for selections.
+ selections in Plotly are limited to scatter/scattergl plots, bar charts,
+ heatmaps, treemaps, and sunburst charts; Altair supports a larger class
+ of plots for selections.
### matplotlib
@@ -304,9 +304,9 @@ conda install -c conda-forge "vegafusion-python-embed>=1.4.0" "vegafusion>=1.4.0
!!! warning "Supported charts"
marimo can render any Plotly plot, but [`mo.ui.plotly`][marimo.ui.plotly] only
- supports reactive selections for scatter plots, bar charts, heatmaps,
- treemaps, and sunburst charts. If you require other kinds of selection,
- please [file an issue](https://github.com/marimo-team/marimo/issues).
+ supports reactive selections for scatter/scattergl plots, bar 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-embed
size: large
diff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.py
index 7dfbb36ffc..1660e00b51 100644
--- a/marimo/_plugins/ui/_impl/plotly.py
+++ b/marimo/_plugins/ui/_impl/plotly.py
@@ -135,8 +135,8 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):
Use `mo.ui.plotly` to make plotly plots reactive: select data with your
cursor on the frontend, get them as a list of dicts in Python!
- This function supports scatter plots, line charts, area charts, bar charts,
- treemap charts, sunburst charts, and heatmaps.
+ This function supports scatter plots, scattergl plots, line charts, area
+ charts, bar charts, treemap charts, sunburst charts, and heatmaps.
Examples:
```python
@@ -363,8 +363,9 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):
for trace in self._figure.data
)
+ scatter_trace_types = {"scatter", "scattergl"}
has_scatter = any(
- getattr(trace, "type", None) == "scatter"
+ getattr(trace, "type", None) in scatter_trace_types
for trace in self._figure.data
)
@@ -551,9 +552,9 @@ def _extract_heatmap_cells_numpy(
def _append_scatter_points_to_selection(
figure: go.Figure, selection_data: dict[str, Any]
) -> None:
- """Append scatter/line points within the selection range to the selection data.
+ """Append scatter/scattergl/line points within range to selection data.
- This modifies selection_data in place, appending any scatter/line points
+ This modifies selection_data in place, appending any scatter/scattergl/line points
that fall within the x-range to the existing points and indices.
For line charts, Plotly may not send point-level data in the selection event
@@ -615,7 +616,7 @@ def _append_scatter_points_to_selection(
def _extract_scatter_points_from_range(
figure: go.Figure, range_data: dict[str, Any]
) -> list[dict[str, Any]]:
- """Extract scatter/line points that fall within a selection range.
+ """Extract scatter/scattergl/line points in a selection range.
This follows Altair's behavior: returns all points where x is within
the x-range, regardless of y value.
@@ -638,7 +639,7 @@ def _extract_scatter_points_numpy(
x_min: float,
x_max: float,
) -> list[dict[str, Any]]:
- """Extract scatter/line points using numpy for better performance."""
+ """Extract scatter/scattergl/line points using numpy."""
import numpy as np
selected_points: list[dict[str, Any]] = []
@@ -656,8 +657,8 @@ def _extract_scatter_points_numpy(
y_field = y_axis.title.text if (y_axis and y_axis.title.text) else "y"
for trace_idx, trace in enumerate(figure.data):
- # Only process scatter traces (which includes lines, markers, lines+markers)
- if getattr(trace, "type", None) != "scatter":
+ # Process scatter-like traces (includes lines, markers, lines+markers)
+ if getattr(trace, "type", None) not in {"scatter", "scattergl"}:
continue
x_data = getattr(trace, "x", None)
@@ -727,7 +728,7 @@ def _extract_scatter_points_fallback(
x_min: float,
x_max: float,
) -> list[dict[str, Any]]:
- """Extract scatter/line points using pure Python (fallback when numpy unavailable)."""
+ """Extract scatter/scattergl/line points with pure Python."""
selected_points: list[dict[str, Any]] = []
# Get axis titles for field naming
@@ -743,8 +744,8 @@ def _extract_scatter_points_fallback(
y_field = y_axis.title.text if (y_axis and y_axis.title.text) else "y"
for trace_idx, trace in enumerate(figure.data):
- # Only process scatter traces (which includes lines, markers, lines+markers)
- if getattr(trace, "type", None) != "scatter":
+ # Process scatter-like traces (includes lines, markers, lines+markers)
+ if getattr(trace, "type", None) not in {"scatter", "scattergl"}:
continue
x_data = getattr(trace, "x", None)
diff --git a/tests/_plugins/ui/_impl/test_plotly.py b/tests/_plugins/ui/_impl/test_plotly.py
index ca770bb382..b24aff5982 100644
--- a/tests/_plugins/ui/_impl/test_plotly.py
+++ b/tests/_plugins/ui/_impl/test_plotly.py
@@ -1030,6 +1030,146 @@ def test_line_chart_selection() -> None:
assert result[2]["Y"] == 25
+def test_scattergl_line_selection() -> None:
+ """Test box selection on pure scattergl line chart."""
+ fig = go.Figure(
+ data=go.Scattergl(
+ x=[1, 2, 3, 4, 5],
+ y=[10, 20, 15, 25, 30],
+ mode="lines",
+ )
+ )
+ fig.update_xaxes(title_text="X")
+ fig.update_yaxes(title_text="Y")
+
+ plot = plotly(fig)
+
+ selection = {
+ "range": {"x": [2, 4], "y": [10, 30]},
+ "points": [], # Empty for pure lines
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ # Should return points at x=2, 3, 4
+ assert len(result) == 3
+ assert result[0]["X"] == 2
+ assert result[0]["Y"] == 20
+ assert result[1]["X"] == 3
+ assert result[1]["Y"] == 15
+ assert result[2]["X"] == 4
+ assert result[2]["Y"] == 25
+
+
+def test_scattergl_line_filters_by_x_range_only() -> None:
+ """Test scattergl line selection uses x-range only."""
+ fig = go.Figure(
+ data=go.Scattergl(
+ x=[1, 2, 3, 4, 5],
+ y=[10, 50, 15, 60, 30], # y values outside narrow selection
+ mode="lines",
+ )
+ )
+ plot = plotly(fig)
+
+ selection = {
+ "range": {"x": [2, 4], "y": [10, 20]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ # Should include all points with x in [2, 4], regardless of y.
+ assert len(result) == 3
+ assert result[0]["x"] == 2
+ assert result[0]["y"] == 50
+ assert result[1]["x"] == 3
+ assert result[1]["y"] == 15
+ assert result[2]["x"] == 4
+ assert result[2]["y"] == 60
+
+
+def test_scattergl_selection_datetime_x_axis() -> None:
+ """Test scattergl line selection with datetime x-axis from frontend ISO strings."""
+ base_date = datetime(2024, 1, 1)
+ dates = [base_date + timedelta(days=i) for i in range(5)]
+ values = [10, 20, 15, 25, 30]
+
+ fig = go.Figure(data=go.Scattergl(x=dates, y=values, mode="lines"))
+ plot = plotly(fig)
+
+ selection = {
+ "range": {
+ "x": [dates[1].isoformat(), dates[3].isoformat()],
+ "y": [0, 50],
+ },
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ assert len(result) == 3
+ assert result[0]["x"] == dates[1]
+ assert result[0]["y"] == 20
+ assert result[1]["x"] == dates[2]
+ assert result[1]["y"] == 15
+ assert result[2]["x"] == dates[3]
+ assert result[2]["y"] == 25
+
+
+def test_scattergl_multiple_line_traces_selection() -> None:
+ """Test box selection on multiple scattergl line traces."""
+ fig = go.Figure()
+ fig.add_trace(
+ go.Scattergl(
+ x=[1, 2, 3, 4],
+ y=[10, 20, 15, 25],
+ mode="lines",
+ name="Series A",
+ )
+ )
+ fig.add_trace(
+ go.Scattergl(
+ x=[1, 2, 3, 4],
+ y=[15, 10, 20, 18],
+ mode="lines",
+ name="Series B",
+ )
+ )
+ fig.update_xaxes(title_text="X")
+ fig.update_yaxes(title_text="Y")
+
+ plot = plotly(fig)
+
+ selection = {
+ "range": {"x": [2, 4], "y": [0, 30]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ # Should return 6 points total: 3 from each trace
+ assert len(result) == 6
+
+ # Check Series A points
+ series_a_points = [p for p in result if p.get("name") == "Series A"]
+ assert len(series_a_points) == 3
+ assert series_a_points[0]["X"] == 2
+ assert series_a_points[1]["X"] == 3
+ assert series_a_points[2]["X"] == 4
+
+ # Check Series B points
+ series_b_points = [p for p in result if p.get("name") == "Series B"]
+ assert len(series_b_points) == 3
+ assert series_b_points[0]["X"] == 2
+ assert series_b_points[1]["X"] == 3
+ assert series_b_points[2]["X"] == 4
+
+
def test_line_markers_selection() -> None:
"""Test box selection on line chart with markers."""
fig = go.Figure(
@@ -1316,6 +1456,34 @@ def test_scatter_points_numpy_and_fallback() -> None:
assert np_point["curveNumber"] == fb_point["curveNumber"]
+def test_scattergl_points_numpy_and_fallback() -> None:
+ """Test numpy/fallback parity for scattergl extraction."""
+ fig = go.Figure(
+ data=go.Scattergl(
+ x=[1, 2, 3, 4, 5],
+ y=[10, 20, 15, 25, 30],
+ mode="lines",
+ )
+ )
+
+ x_min, x_max = 2, 4
+ numpy_result = _extract_scatter_points_numpy(fig, x_min, x_max)
+ fallback_result = _extract_scatter_points_fallback(fig, x_min, x_max)
+
+ assert len(numpy_result) == len(fallback_result)
+
+ def sort_key(point: dict[str, Any]) -> tuple[Any, ...]:
+ return (point["x"], point["y"])
+
+ 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["x"] == fb_point["x"]
+ assert np_point["y"] == fb_point["y"]
+ assert np_point["curveNumber"] == fb_point["curveNumber"]
+
+
def test_mixed_heatmap_and_line_selection() -> None:
"""Test that heatmap and line selections don't interfere with each other."""
# Create figure with both heatmap and line