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.

Add support for reactive line charts for plotly (#7735)

Florian Verdonck8aff126bd97b
diff --git a/examples/third_party/plotly/line_chart.py b/examples/third_party/plotly/line_chart.py
new file mode 100644
index 0000000000..d677a872fa
--- /dev/null
+++ b/examples/third_party/plotly/line_chart.py
@@ -0,0 +1,181 @@
+# /// script
+# requires-python = ">=3.9"
+# dependencies = [
+# "marimo",
+# "pandas==2.3.3",
+# "plotly==6.5.1",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.18.4"
+app = marimo.App(width="medium")
+
+
+def _():
+ import marimo as mo
+ return (mo,)
+
+
+def _(mo):
+ mo.md("""
+ # Reactive Plotly Line Charts
+
+ Use `mo.ui.plotly` to make line charts reactive. Select data by dragging
+ a box on the chart, and get the selected points in Python!
+ """)
+ return
+
+
+def _():
+ import plotly.graph_objects as go
+ import pandas as pd
+ return go, pd
+
+
+def _(pd):
+ # Create sample time series data
+ data = pd.DataFrame(
+ {
+ "month": list(range(1, 13)),
+ "sales": [45, 52, 48, 65, 72, 68, 80, 85, 78, 90, 95, 88],
+ "expenses": [30, 35, 32, 40, 45, 42, 50, 48, 52, 55, 58, 54],
+ }
+ )
+ data
+ return (data,)
+
+
[email protected](hide_code=True)
+def _(data, go, mo):
+ # 1. Simple line chart
+ fig1 = go.Figure()
+ fig1.add_trace(
+ go.Scatter(
+ x=data["month"],
+ y=data["sales"],
+ mode="lines",
+ name="Sales",
+ line=dict(color="#636EFA", width=2),
+ )
+ )
+ fig1.update_layout(
+ title="Monthly Sales", xaxis_title="Month", yaxis_title="Sales ($1000s)"
+ )
+
+ line_chart = mo.ui.plotly(fig1)
+ line_chart
+ return (line_chart,)
+
+
+def _(line_chart, mo):
+ mo.md(f"""
+ ## Simple Line Chart
+
+ **Instructions:** Use the box select tool (in the toolbar) to select a range.
+
+ ### Selected Points:
+ {line_chart.value}
+
+ ### Selection Range:
+ {line_chart.ranges}
+ """)
+ return
+
+
[email protected](hide_code=True)
+def _(data, go, mo):
+ # 2. Line chart with markers
+ fig2 = go.Figure()
+ fig2.add_trace(
+ go.Scatter(
+ x=data["month"],
+ y=data["sales"],
+ mode="lines+markers",
+ name="Sales",
+ line=dict(color="#636EFA", width=2),
+ marker=dict(size=8),
+ )
+ )
+ fig2.update_layout(
+ title="Monthly Sales (with markers)",
+ xaxis_title="Month",
+ yaxis_title="Sales ($1000s)",
+ )
+
+ line_markers = mo.ui.plotly(fig2)
+ line_markers
+ return (line_markers,)
+
+
+def _(line_markers, mo):
+ mo.md(f"""
+ ## Line Chart with Markers
+
+ **Instructions:** Use the box select tool to select a range.
+
+ ### Selected Points:
+ {line_markers.value}
+ """)
+ return
+
+
[email protected](hide_code=True)
+def _(data, go, mo):
+ # 3. Multiple lines
+ fig3 = go.Figure()
+ fig3.add_trace(
+ go.Scatter(
+ x=data["month"],
+ y=data["sales"],
+ mode="lines",
+ name="Sales",
+ line=dict(color="#636EFA", width=2),
+ )
+ )
+ fig3.add_trace(
+ go.Scatter(
+ x=data["month"],
+ y=data["expenses"],
+ mode="lines",
+ name="Expenses",
+ line=dict(color="#EF553B", width=2),
+ )
+ )
+ fig3.update_layout(
+ title="Sales vs Expenses",
+ xaxis_title="Month",
+ yaxis_title="Amount ($1000s)",
+ )
+
+ multi_line = mo.ui.plotly(fig3)
+ multi_line
+ return (multi_line,)
+
+
+def _(mo, multi_line):
+ mo.md(f"""
+ ## Multiple Lines
+
+ **Instructions:** Use the box select tool to select a range.
+ Points from both lines will be returned!
+
+ ### Selected Points:
+ {multi_line.value}
+
+ ### Number of selected points:
+ {len(multi_line.value)}
+ """)
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.py
index 992907c650..927b71154e 100644
--- a/marimo/_plugins/ui/_impl/plotly.py
+++ b/marimo/_plugins/ui/_impl/plotly.py
@@ -44,8 +44,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 currently only supports scatter plots, treemap charts,
- sunburst charts, heatmaps, and bar charts.
+ This function supports scatter plots, line charts, bar charts, treemap charts,
+ sunburst charts, and heatmaps.
Examples:
```python
@@ -266,6 +266,11 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):
for trace in self._figure.data
)
+ has_scatter = any(
+ getattr(trace, "type", None) == "scatter"
+ for trace in self._figure.data
+ )
+
# For heatmaps with a range selection, always extract all cells in range
# (Plotly only sends corner/edge points, not all cells)
if has_heatmap and value.get("range"):
@@ -282,6 +287,14 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):
if has_bar and value.get("range"):
_append_bar_items_to_selection(self._figure, self._selection_data)
+ # For line/scatter charts with a range selection, extract all points in x-range
+ # This handles mode='lines', mode='lines+markers', and mode='markers'
+ # Plotly may not send point data for pure line charts, so we extract manually
+ if has_scatter and value.get("range"):
+ _append_scatter_points_to_selection(
+ self._figure, self._selection_data
+ )
+
result = self.points
return result
@@ -408,6 +421,233 @@ def _extract_heatmap_cells_numpy(
return selected_cells
+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.
+
+ This modifies selection_data in place, appending any scatter/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
+ (especially for mode='lines'). We manually extract all points where x is
+ within the selected range to match Altair's behavior.
+ """
+ range_value = selection_data.get("range")
+ if not isinstance(range_value, dict):
+ return
+
+ scatter_points = _extract_scatter_points_from_range(
+ figure, cast(dict[str, Any], range_value)
+ )
+ if scatter_points:
+ # Get existing points and indices
+ existing_points = selection_data.get("points", [])
+ existing_indices = selection_data.get("indices", [])
+
+ # Filter out empty dicts from existing points (these come from line charts)
+ # where Plotly sends the structure but no data
+ existing_points = [p for p in existing_points if p]
+
+ # Merge with scatter points, avoiding duplicates
+ # Use pointIndex and curveNumber to track uniqueness
+ # (can't use x/y values since field names vary: "x"/"y" vs "X"/"Y" etc.)
+ seen = set()
+ merged_points = []
+ merged_indices = []
+
+ # Add existing points first
+ for idx, point in enumerate(existing_points):
+ key = (
+ point.get("pointIndex"),
+ point.get("curveNumber"),
+ )
+ if key not in seen and key != (None, None):
+ seen.add(key)
+ merged_points.append(point)
+ if idx < len(existing_indices):
+ merged_indices.append(existing_indices[idx])
+
+ # Add new scatter points
+ for point in scatter_points:
+ key = (
+ point.get("pointIndex"),
+ point.get("curveNumber"),
+ )
+ if key not in seen:
+ seen.add(key)
+ merged_points.append(point)
+ # Indices for manually extracted points - use the point's original index
+ if "pointIndex" in point:
+ merged_indices.append(point["pointIndex"])
+
+ selection_data["points"] = merged_points
+ selection_data["indices"] = merged_indices
+
+
+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.
+
+ This follows Altair's behavior: returns all points where x is within
+ the x-range, regardless of y value.
+ """
+ if not range_data.get("x"):
+ return []
+
+ x_range = range_data["x"]
+ x_min, x_max = min(x_range), max(x_range)
+
+ # Use numpy fast path if available for better performance
+ if DependencyManager.numpy.has():
+ return _extract_scatter_points_numpy(figure, x_min, x_max)
+
+ return _extract_scatter_points_fallback(figure, x_min, x_max)
+
+
+def _extract_scatter_points_numpy(
+ figure: go.Figure,
+ x_min: float,
+ x_max: float,
+) -> list[dict[str, Any]]:
+ """Extract scatter/line points using numpy for better performance."""
+ import numpy as np
+
+ selected_points: list[dict[str, Any]] = []
+
+ # Get axis titles for field naming
+ x_axes: list[go.layout.XAxis] = []
+ figure.for_each_xaxis(x_axes.append)
+ x_axis = x_axes[0] if len(x_axes) == 1 else None
+
+ y_axes: list[go.layout.YAxis] = []
+ figure.for_each_yaxis(y_axes.append)
+ y_axis = y_axes[0] if len(y_axes) == 1 else None
+
+ x_field = x_axis.title.text if (x_axis and x_axis.title.text) else "x"
+ 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":
+ continue
+
+ x_data = getattr(trace, "x", None)
+ y_data = getattr(trace, "y", None)
+
+ if x_data is None or y_data is None:
+ continue
+
+ # Convert to numpy arrays for vectorized operations
+ x_arr = np.asarray(x_data)
+ y_arr = np.asarray(y_data)
+
+ # Check if x is numeric
+ x_is_numeric = np.issubdtype(x_arr.dtype, np.number)
+
+ # Filter by x-range (matching Altair behavior)
+ if x_is_numeric:
+ x_mask = (x_arr >= x_min) & (x_arr <= x_max)
+ else:
+ # Categorical: use index-based filtering
+ x_indices = np.arange(len(x_arr))
+ x_mask = (x_max > x_indices - 0.5) & (x_min < x_indices + 0.5)
+
+ # Get indices where mask is True
+ selected_indices = np.where(x_mask)[0]
+
+ # Build point dicts for selected indices
+ for idx in selected_indices:
+ # Use .item() to convert numpy types to Python types
+ x_val = (
+ x_arr[idx].item()
+ if hasattr(x_arr[idx], "item")
+ else x_arr[idx]
+ )
+ y_val = (
+ y_arr[idx].item()
+ if hasattr(y_arr[idx], "item")
+ else y_arr[idx]
+ )
+
+ point_dict = {
+ x_field: x_val,
+ y_field: y_val,
+ "curveNumber": trace_idx,
+ "pointIndex": int(idx),
+ }
+
+ # Add trace name if available
+ if hasattr(trace, "name") and trace.name:
+ point_dict["name"] = trace.name
+
+ selected_points.append(point_dict)
+
+ return selected_points
+
+
+def _extract_scatter_points_fallback(
+ figure: go.Figure,
+ x_min: float,
+ x_max: float,
+) -> list[dict[str, Any]]:
+ """Extract scatter/line points using pure Python (fallback when numpy unavailable)."""
+ selected_points: list[dict[str, Any]] = []
+
+ # Get axis titles for field naming
+ x_axes: list[go.layout.XAxis] = []
+ figure.for_each_xaxis(x_axes.append)
+ x_axis = x_axes[0] if len(x_axes) == 1 else None
+
+ y_axes: list[go.layout.YAxis] = []
+ figure.for_each_yaxis(y_axes.append)
+ y_axis = y_axes[0] if len(y_axes) == 1 else None
+
+ x_field = x_axis.title.text if (x_axis and x_axis.title.text) else "x"
+ 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":
+ continue
+
+ x_data = getattr(trace, "x", None)
+ y_data = getattr(trace, "y", None)
+
+ if x_data is None or y_data is None:
+ continue
+
+ # Iterate through points and filter by x-range
+ for point_idx, (x_val, y_val) in enumerate(zip(x_data, y_data)):
+ # Check if x is within range
+ x_in_range = False
+
+ if isinstance(x_val, (int, float)):
+ x_in_range = x_min <= x_val <= x_max
+ else:
+ # Categorical - use index-based filtering
+ cell_x_min = point_idx - 0.5
+ cell_x_max = point_idx + 0.5
+ x_in_range = not (x_max <= cell_x_min or x_min >= cell_x_max)
+
+ if x_in_range:
+ point_dict = {
+ x_field: x_val,
+ y_field: y_val,
+ "curveNumber": trace_idx,
+ "pointIndex": point_idx,
+ }
+
+ # Add trace name if available
+ if hasattr(trace, "name") and trace.name:
+ point_dict["name"] = trace.name
+
+ selected_points.append(point_dict)
+
+ return selected_points
+
+
def _extract_heatmap_cells_fallback(
figure: go.Figure,
x_min: float,
diff --git a/tests/_plugins/ui/_impl/test_plotly.py b/tests/_plugins/ui/_impl/test_plotly.py
index 14708a1494..9332dcda01 100644
--- a/tests/_plugins/ui/_impl/test_plotly.py
+++ b/tests/_plugins/ui/_impl/test_plotly.py
@@ -16,6 +16,8 @@ from marimo._plugins.ui._impl.plotly import (
_extract_bars_numpy,
_extract_heatmap_cells_fallback,
_extract_heatmap_cells_numpy,
+ _extract_scatter_points_fallback,
+ _extract_scatter_points_numpy,
plotly,
)
@@ -333,8 +335,13 @@ def test_value_returns_points() -> None:
}
# _convert_value returns the points
+ # With the new line chart support, it now extracts ALL points in the x-range
result = plot._convert_value(selection)
- assert result == [{"x": 1, "y": 4}]
+ assert len(result) == 2 # Points at x=1 and x=2
+ assert result[0]["x"] == 1
+ assert result[0]["y"] == 4
+ assert result[1]["x"] == 2
+ assert result[1]["y"] == 5
def test_plotly_name() -> None:
@@ -561,9 +568,19 @@ def test_heatmap_curve_number() -> None:
result = plot._convert_value(selection)
- # Heatmap cells should have curveNumber = 1
+ # Should include both scatter points (curveNumber=0) and heatmap cells (curveNumber=1)
assert len(result) > 0
- assert all(cell.get("curveNumber") == 1 for cell in result)
+
+ # Separate scatter and heatmap points
+ scatter_points = [p for p in result if p.get("curveNumber") == 0]
+ heatmap_cells = [p for p in result if p.get("curveNumber") == 1]
+
+ # Should have points from both traces
+ assert len(scatter_points) > 0, "Should have scatter points from trace 0"
+ assert len(heatmap_cells) > 0, "Should have heatmap cells from trace 1"
+
+ # Heatmap cells should have z values
+ assert all("z" in cell for cell in heatmap_cells)
def test_heatmap_initial_selection() -> None:
@@ -763,6 +780,26 @@ def test_bar_chart_basic() -> None:
assert plot.value == []
+# ============================================================================
+# Line Chart Tests
+# ============================================================================
+
+
+def test_line_chart_basic() -> None:
+ """Test that line charts can be created (supported chart type)."""
+ fig = go.Figure(
+ data=go.Scatter(
+ x=[1, 2, 3, 4, 5],
+ y=[10, 20, 15, 25, 30],
+ mode="lines",
+ )
+ )
+ plot = plotly(fig)
+
+ assert plot is not None
+ assert plot.value == []
+
+
def test_bar_chart_selection_vertical() -> None:
"""Test bar chart selection with vertical bars (categorical x-axis)."""
fig = go.Figure(
@@ -788,6 +825,70 @@ def test_bar_chart_selection_vertical() -> None:
assert any(bar["x"] == "C" and bar["y"] == 15 for bar in result)
+def test_line_chart_selection() -> None:
+ """Test box selection on pure line chart."""
+ fig = go.Figure(
+ data=go.Scatter(
+ 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)
+
+ # Simulate box selection from x=2 to x=4
+ 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_line_markers_selection() -> None:
+ """Test box selection on line chart with markers."""
+ fig = go.Figure(
+ data=go.Scatter(
+ x=[1, 2, 3, 4, 5],
+ y=[10, 20, 15, 25, 30],
+ mode="lines+markers",
+ )
+ )
+ fig.update_xaxes(title_text="Time")
+ fig.update_yaxes(title_text="Value")
+
+ plot = plotly(fig)
+
+ # Simulate box selection from x=1.5 to x=3.5
+ selection = {
+ "range": {"x": [1.5, 3.5], "y": [10, 25]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ # Should return points at x=2, 3
+ assert len(result) == 2
+ assert result[0]["Time"] == 2
+ assert result[0]["Value"] == 20
+ assert result[1]["Time"] == 3
+ assert result[1]["Value"] == 15
+
+
def test_bar_chart_selection_horizontal() -> None:
"""Test bar chart selection with horizontal bars."""
fig = go.Figure(
@@ -935,6 +1036,138 @@ def test_bar_chart_empty_selection() -> None:
assert result == []
+def test_line_chart_with_axis_titles() -> None:
+ """Test line chart selection with custom axis titles."""
+ fig = go.Figure(
+ data=go.Scatter(
+ x=[1, 2, 3, 4, 5],
+ y=[10, 20, 15, 25, 30],
+ mode="lines",
+ )
+ )
+ fig.update_xaxes(title_text="Time")
+ fig.update_yaxes(title_text="Value")
+
+ plot = plotly(fig)
+
+ selection = {
+ "range": {"x": [2, 3], "y": [0, 30]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ # Should return points at x=2, 3
+ assert len(result) == 2
+ assert result[0]["Time"] == 2
+ assert result[0]["Value"] == 20
+ assert result[1]["Time"] == 3
+ assert result[1]["Value"] == 15
+
+
+def test_multiple_line_traces_selection() -> None:
+ """Test box selection on multiple line traces."""
+ fig = go.Figure()
+ fig.add_trace(
+ go.Scatter(
+ x=[1, 2, 3, 4, 5],
+ y=[10, 20, 15, 25, 30],
+ mode="lines",
+ name="Series A",
+ )
+ )
+ fig.add_trace(
+ go.Scatter(
+ x=[1, 2, 3, 4, 5],
+ y=[15, 10, 20, 18, 25],
+ mode="lines",
+ name="Series B",
+ )
+ )
+ fig.update_xaxes(title_text="X")
+ fig.update_yaxes(title_text="Y")
+
+ plot = plotly(fig)
+
+ # Simulate box selection from x=2 to x=4
+ 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_chart_no_axis_titles() -> None:
+ """Test line chart selection without axis titles."""
+ fig = go.Figure(
+ data=go.Scatter(
+ x=[1, 2, 3, 4, 5],
+ y=[10, 20, 15, 25, 30],
+ mode="lines",
+ )
+ )
+
+ plot = plotly(fig)
+
+ selection = {
+ "range": {"x": [2, 4], "y": [10, 30]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ # Should use default field names 'x' and 'y'
+ assert len(result) == 3
+ assert result[0]["x"] == 2
+ assert result[0]["y"] == 20
+
+
+def test_line_chart_empty_selection() -> None:
+ """Test line chart with range that includes no points."""
+ fig = go.Figure(
+ data=go.Scatter(
+ x=[1, 2, 3],
+ y=[10, 20, 30],
+ mode="lines",
+ )
+ )
+
+ plot = plotly(fig)
+
+ # Select range outside data
+ selection = {
+ "range": {"x": [10, 20], "y": [0, 100]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ # Should be empty
+ assert result == []
+
+
def test_bar_chart_single_bar() -> None:
"""Test bar chart with a single bar."""
fig = go.Figure(
@@ -960,6 +1193,33 @@ def test_bar_chart_single_bar() -> None:
assert result[0]["y"] == 42
+def test_line_chart_single_point_selection() -> None:
+ """Test line chart with range that covers only one point."""
+ fig = go.Figure(
+ data=go.Scatter(
+ x=[1, 2, 3, 4, 5],
+ y=[10, 20, 15, 25, 30],
+ mode="lines",
+ )
+ )
+
+ plot = plotly(fig)
+
+ # Very narrow range around x=3
+ selection = {
+ "range": {"x": [2.9, 3.1], "y": [0, 30]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ # Should return only point at x=3
+ assert len(result) == 1
+ assert result[0]["x"] == 3
+ assert result[0]["y"] == 15
+
+
def test_bar_chart_initial_selection() -> None:
"""Test that initial selection works with bar charts."""
fig = go.Figure(
@@ -1021,19 +1281,53 @@ def test_bar_chart_mixed_with_scatter() -> None:
plot = plotly(fig)
- # Select range that includes both scatter point and bar
+ # Select range that includes scatter points and bars
selection = {
- "range": {"x": [-0.5, 1.5], "y": [5, 25]},
+ "range": {"x": [-0.5, 2.5], "y": [5, 25]},
"points": [],
"indices": [],
}
result = plot._convert_value(selection)
- # Should include bars A and B (indices 0 and 1)
+ # Should include both scatter points and bar(s)
+ # The exact count depends on the x-range mapping to categorical bar positions
assert len(result) >= 2
- assert any(r.get("x") == "A" and r.get("y") == 10 for r in result)
- assert any(r.get("x") == "B" and r.get("y") == 20 for r in result)
+ # Should have at least one bar
+ assert any(r.get("x") in ["A", "B", "C"] for r in result)
+ # Should have scatter points
+ assert any(isinstance(r.get("x"), int) for r in result)
+
+
+def test_line_chart_with_curve_number() -> None:
+ """Test that line chart points include curveNumber."""
+ fig = go.Figure()
+ fig.add_trace(
+ go.Scatter(x=[1, 2, 3], y=[10, 20, 15], mode="lines", name="A")
+ )
+ fig.add_trace(
+ go.Scatter(x=[1, 2, 3], y=[15, 10, 20], mode="lines", name="B")
+ )
+
+ plot = plotly(fig)
+
+ selection = {
+ "range": {"x": [1, 3], "y": [0, 30]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ # Check that all points have curveNumber
+ assert all("curveNumber" in point for point in result)
+
+ # Check we have points from both traces
+ curve_numbers = {point["curveNumber"] for point in result}
+ assert curve_numbers == {0, 1}
+
+
+# Test numpy vs fallback implementations
def test_bar_numpy_and_fallback_match_categorical() -> None:
@@ -1128,6 +1422,98 @@ def test_bar_numpy_and_fallback_match_horizontal() -> None:
assert np_bar["curveNumber"] == fb_bar["curveNumber"]
+def test_scatter_points_numpy_and_fallback() -> None:
+ """Test that numpy and fallback implementations produce identical results."""
+ fig = go.Figure(
+ data=go.Scatter(
+ x=[1, 2, 3, 4, 5],
+ y=[10, 20, 15, 25, 30],
+ mode="lines",
+ )
+ )
+
+ x_min, x_max = 2, 4
+
+ # Get results from both implementations
+ numpy_result = _extract_scatter_points_numpy(fig, x_min, x_max)
+ fallback_result = _extract_scatter_points_fallback(fig, x_min, x_max)
+
+ # Both should return the same number of points
+ assert len(numpy_result) == len(fallback_result)
+
+ # Sort results for comparison (order might differ)
+ 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)
+
+ # Compare each point
+ 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_line_chart_filters_by_x_range_only() -> None:
+ """Test that line chart selection filters by x-range, matching Altair behavior."""
+ fig = go.Figure(
+ data=go.Scatter(
+ x=[1, 2, 3, 4, 5],
+ y=[10, 50, 15, 60, 30], # Varying y values
+ mode="lines",
+ )
+ )
+
+ plot = plotly(fig)
+
+ # Select x range 2-4, with narrow y range that wouldn't include all points
+ selection = {
+ "range": {
+ "x": [2, 4],
+ "y": [10, 20],
+ }, # y range only covers some points
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ # Should return ALL points in x-range [2,4], regardless of y
+ # This matches Altair behavior
+ assert len(result) == 3
+ assert result[0]["x"] == 2
+ assert result[0]["y"] == 50 # y=50 is outside [10,20] but still included
+ assert result[1]["x"] == 3
+ assert result[1]["y"] == 15
+ assert result[2]["x"] == 4
+ assert result[2]["y"] == 60 # y=60 is outside [10,20] but still included
+
+
+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
+ fig = go.Figure()
+ fig.add_trace(
+ go.Scatter(x=[1, 2, 3], y=[10, 20, 15], mode="lines", name="Line")
+ )
+ # Note: Not adding heatmap since they typically don't mix,
+ # but test that scatter detection works correctly
+
+ plot = plotly(fig)
+
+ selection = {
+ "range": {"x": [1, 3], "y": [0, 30]},
+ "points": [],
+ "indices": [],
+ }
+
+ result = plot._convert_value(selection)
+
+ # Should extract line points
+ assert len(result) == 3
+
+
def test_heatmap_numpy_and_fallback_numeric_axes() -> None:
"""Test numpy and fallback with numeric axes produce identical results."""
fig = go.Figure(