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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
Ensure Plotly area chart is reactive (#7761)
Florian Verdonck9c8181ee2ac9
diff --git a/examples/third_party/plotly/area_chart.py b/examples/third_party/plotly/area_chart.pynew file mode 100644index 0000000000..3b667471ae--- /dev/null+++ b/examples/third_party/plotly/area_chart.py@@ -0,0 +1,158 @@+# /// script+# requires-python = ">=3.9"+# dependencies = [+# "marimo",+# "pandas==2.3.3",+# "plotly==6.5.1",+# ]+# ///++import marimo++__generated_with = "0.19.0"+app = marimo.App(width="medium")+++def _():+ import marimo as mo+ return (mo,)+++def _(mo):+ mo.md("""+ # Reactive Plotly Area Charts++ Use `mo.ui.plotly` to make area charts reactive. Select data by dragging+ a box on the chart, and get the selected points in Python!++ Area charts are scatter traces with `fill='tozeroy'` or similar fill options.+ """)+ return+++def _():+ import plotly.graph_objects as go+ import pandas as pd+ return go, pd+++def _(pd):+ # Create sample data+ data = pd.DataFrame(+ {+ "month": list(range(1, 13)),+ "revenue": [45, 52, 48, 65, 72, 68, 80, 85, 78, 90, 95, 88],+ "costs": [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. Basic area chart with fill='tozeroy'+ fig1 = go.Figure()+ fig1.add_trace(+ go.Scatter(+ x=data["month"],+ y=data["revenue"],+ fill="tozeroy",+ mode="lines",+ name="Revenue",+ line=dict(color="#636EFA", width=2),+ )+ )+ fig1.update_layout(+ title="Monthly Revenue (Area Chart)",+ xaxis_title="Month",+ yaxis_title="Revenue ($1000s)",+ )++ area_chart = mo.ui.plotly(fig1)+ area_chart+ return (area_chart,)+++def _(area_chart, mo):+ mo.md(f"""+ ## Basic Area Chart (fill='tozeroy')++ **Instructions:** Use the box select tool (in the toolbar) to select a range.++ ### Selected Points:+ {area_chart.value}++ ### Selection Range:+ {area_chart.ranges}++ ### Indices:+ {area_chart.indices}+ """)+ return++[email protected](hide_code=True)+def _(data, go, mo):+ # 2. Stacked area chart+ fig2 = go.Figure()+ fig2.add_trace(+ go.Scatter(+ x=data["month"],+ y=data["costs"],+ fill="tozeroy",+ stackgroup="one",+ mode="lines",+ name="Costs",+ line=dict(color="#EF553B", width=2),+ )+ )+ fig2.add_trace(+ go.Scatter(+ x=data["month"],+ y=data["revenue"] - data["costs"],+ fill="tonexty",+ stackgroup="one",+ mode="lines",+ name="Profit",+ line=dict(color="#00CC96", width=2),+ )+ )+ fig2.update_layout(+ title="Costs vs Profit (Stacked Area)",+ xaxis_title="Month",+ yaxis_title="Amount ($1000s)",+ )++ stacked_area = mo.ui.plotly(fig2)+ stacked_area+ return (stacked_area,)+++def _(mo, stacked_area):+ mo.md(f"""+ ## Stacked Area Chart (stackgroup)++ **Instructions:** Use the box select tool to select a range.+ Points from both areas will be returned!++ ### Selected Points:+ {stacked_area.value}++ ### Number of selected points:+ {len(stacked_area.value)}++ ### Selection Range:+ {stacked_area.ranges}+ """)+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.pyindex 927b71154e..aadb22c76e 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 yourcursor on the frontend, get them as a list of dicts in Python!- This function supports scatter plots, line charts, bar charts, treemap charts,- sunburst charts, and heatmaps.+ This function supports scatter plots, line charts, area charts, bar charts,+ treemap charts, sunburst charts, and heatmaps.Examples:```pythondiff --git a/tests/_plugins/ui/_impl/test_plotly.py b/tests/_plugins/ui/_impl/test_plotly.pyindex 9332dcda01..cf326f52b3 100644--- a/tests/_plugins/ui/_impl/test_plotly.py+++ b/tests/_plugins/ui/_impl/test_plotly.py@@ -21,6 +21,10 @@ from marimo._plugins.ui._impl.plotly import (plotly,)+# ============================================================================+# General / Basic Tests+# ============================================================================+def test_basic_scatter_plot() -> None:"""Test creating a basic scatter plot."""@@ -366,6 +370,11 @@ def test_selection_boundary_conditions() -> None:assert 1 in initial_value["indices"]+# ============================================================================+# Heatmap Tests+# ============================================================================++def test_heatmap_basic() -> None:"""Test that heatmaps can be created (supported chart type)."""fig = go.Figure(@@ -762,26 +771,7 @@ def test_heatmap_numpy_and_fallback_produce_same_results() -> None:# ============================================================================-# Bar Chart Tests-# ============================================================================---def test_bar_chart_basic() -> None:- """Test that bar charts can be created (supported chart type)."""- fig = go.Figure(- data=go.Bar(- x=["A", "B", "C"],- y=[10, 20, 15],- )- )- plot = plotly(fig)-- assert plot is not None- assert plot.value == []---# ============================================================================-# Line Chart Tests+# Scatter / Line Chart Tests# ============================================================================@@ -800,31 +790,6 @@ def test_line_chart_basic() -> None:assert plot.value == []-def test_bar_chart_selection_vertical() -> None:- """Test bar chart selection with vertical bars (categorical x-axis)."""- fig = go.Figure(- data=go.Bar(- x=["A", "B", "C", "D"],- y=[10, 20, 15, 25],- )- )- plot = plotly(fig)-- # Simulate a selection from frontend (selecting bars B and C)- selection = {- "range": {"x": [0.5, 2.5], "y": [0, 30]},- "points": [],- "indices": [],- }-- result = plot._convert_value(selection)-- # Should extract bars at indices 1 and 2 (B and C)- assert len(result) == 2- assert any(bar["x"] == "B" and bar["y"] == 20 for bar in result)- 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(@@ -889,153 +854,6 @@ def test_line_markers_selection() -> None:assert result[1]["Value"] == 15-def test_bar_chart_selection_horizontal() -> None:- """Test bar chart selection with horizontal bars."""- fig = go.Figure(- data=go.Bar(- x=[10, 20, 15],- y=["A", "B", "C"],- orientation="h",- )- )- plot = plotly(fig)-- # Simulate a selection (selecting bars A and B)- selection = {- "range": {"x": [0, 30], "y": [-0.5, 1.5]},- "points": [],- "indices": [],- }-- result = plot._convert_value(selection)-- # Should extract bars at y-indices 0 and 1 (A and B)- assert len(result) == 2- assert any(bar["y"] == "A" and bar["x"] == 10 for bar in result)- assert any(bar["y"] == "B" and bar["x"] == 20 for bar in result)---def test_bar_chart_categorical_axis() -> None:- """Test bar chart with categorical x-axis (most common case)."""- fig = go.Figure(- data=go.Bar(- x=["Product A", "Product B", "Product C"],- y=[100, 200, 150],- )- )- plot = plotly(fig)-- # Select middle bar (Product B at index 1)- selection = {- "range": {"x": [0.7, 1.3], "y": [0, 250]},- "points": [],- "indices": [],- }-- result = plot._convert_value(selection)-- assert len(result) == 1- assert result[0]["x"] == "Product B"- assert result[0]["y"] == 200---def test_bar_chart_numeric_axis() -> None:- """Test bar chart with numeric x-axis (histogram-like)."""- fig = go.Figure(- data=go.Bar(- x=[10, 20, 30, 40],- y=[5, 12, 8, 15],- )- )- plot = plotly(fig)-- # Select bars at x=20 and x=30- selection = {- "range": {"x": [15, 35], "y": [0, 20]},- "points": [],- "indices": [],- }-- result = plot._convert_value(selection)-- assert len(result) == 2- assert any(bar["x"] == 20 and bar["y"] == 12 for bar in result)- assert any(bar["x"] == 30 and bar["y"] == 8 for bar in result)---def test_bar_chart_stacked() -> None:- """Test stacked bar chart - should return all segments at selected positions."""- fig = go.Figure()- # Two traces for stacked bars- fig.add_trace(go.Bar(x=["A", "B", "C"], y=[10, 15, 12], name="Series1"))- fig.add_trace(go.Bar(x=["A", "B", "C"], y=[5, 8, 6], name="Series2"))-- plot = plotly(fig)-- # Select bar at position A (index 0)- selection = {- "range": {"x": [-0.5, 0.5], "y": [0, 30]},- "points": [],- "indices": [],- }-- result = plot._convert_value(selection)-- # Should return both segments at position A (one from each trace)- assert len(result) == 2- assert any(bar["x"] == "A" and bar["y"] == 10 for bar in result)- assert any(bar["x"] == "A" and bar["y"] == 5 for bar in result)- # Check curveNumber to distinguish traces- assert result[0]["curveNumber"] != result[1]["curveNumber"]---def test_bar_chart_grouped() -> None:- """Test grouped bar chart - should return all bars at selected position."""- fig = go.Figure()- # Two traces for grouped bars- fig.add_trace(go.Bar(x=["A", "B", "C"], y=[20, 25, 18], name="Series1"))- fig.add_trace(go.Bar(x=["A", "B", "C"], y=[15, 22, 16], name="Series2"))-- plot = plotly(fig)-- # Select category B (index 1)- selection = {- "range": {"x": [0.5, 1.5], "y": [0, 30]},- "points": [],- "indices": [],- }-- result = plot._convert_value(selection)-- # Should return both bars at category B- assert len(result) == 2- assert any(bar["x"] == "B" and bar["y"] == 25 for bar in result)- assert any(bar["x"] == "B" and bar["y"] == 22 for bar in result)---def test_bar_chart_empty_selection() -> None:- """Test bar chart selection with range that includes no bars."""- fig = go.Figure(- data=go.Bar(- x=["A", "B", "C"],- y=[10, 20, 15],- )- )- plot = plotly(fig)-- # Select a range with no bars (far to the right)- selection = {- "range": {"x": [5, 10], "y": [0, 30]},- "points": [],- "indices": [],- }-- result = plot._convert_value(selection)-- # Should be empty- assert result == []--def test_line_chart_with_axis_titles() -> None:"""Test line chart selection with custom axis titles."""fig = go.Figure(@@ -1168,31 +986,6 @@ def test_line_chart_empty_selection() -> None:assert result == []-def test_bar_chart_single_bar() -> None:- """Test bar chart with a single bar."""- fig = go.Figure(- data=go.Bar(- x=["OnlyBar"],- y=[42],- )- )- plot = plotly(fig)-- # Select the single bar (categorical at index 0)- selection = {- "range": {"x": [-0.5, 0.5], "y": [0, 50]},- "points": [],- "indices": [],- }-- result = plot._convert_value(selection)-- # Should extract the single bar- assert len(result) == 1- assert result[0]["x"] == "OnlyBar"- 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(@@ -1220,31 +1013,687 @@ def test_line_chart_single_point_selection() -> None:assert result[0]["y"] == 15-def test_bar_chart_initial_selection() -> None:- """Test that initial selection works with bar charts."""- fig = go.Figure(- data=go.Bar(- x=["A", "B", "C", "D"],- y=[10, 20, 15, 25],- )+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"))-- # Add an initial selection- fig.add_selection(x0=0.5, x1=2.5, y0=0, y1=30, xref="x", yref="y")plot = plotly(fig)- # Check that initial value contains the selection- initial_value = plot._args.initial_value- assert "range" in initial_value- assert initial_value["range"]["x"] == [0.5, 2.5]- assert initial_value["range"]["y"] == [0, 30]+ selection = {+ "range": {"x": [1, 3], "y": [0, 30]},+ "points": [],+ "indices": [],+ }- # For bar charts, should extract bars at indices 1 and 2 (B and C)- assert "points" in initial_value- assert len(initial_value["points"]) == 2- assert any(- bar["x"] == "B" and bar["y"] == 20 for bar in initial_value["points"]+ 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}+++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_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_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+++# ============================================================================+# Area Chart Tests+# ============================================================================+++def test_area_chart_basic() -> None:+ """Test that area charts can be created (scatter with fill)."""+ fig = go.Figure(+ data=go.Scatter(+ x=[1, 2, 3, 4, 5],+ y=[10, 20, 15, 25, 30],+ fill="tozeroy",+ mode="lines",+ )+ )+ plot = plotly(fig)++ assert plot is not None+ assert plot.value == []+++def test_area_chart_selection() -> None:+ """Test box selection on area chart returns points in x-range."""+ fig = go.Figure(+ data=go.Scatter(+ x=[1, 2, 3, 4, 5],+ y=[10, 20, 15, 25, 30],+ fill="tozeroy",+ mode="lines",+ )+ )+ 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 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_area_chart_tozeroy() -> None:+ """Test area chart with fill='tozeroy' (fill down to x-axis)."""+ fig = go.Figure(+ data=go.Scatter(+ x=[1, 2, 3],+ y=[10, 20, 15],+ fill="tozeroy",+ mode="lines",+ name="Area",+ )+ )++ plot = plotly(fig)++ selection = {+ "range": {"x": [1, 3], "y": [0, 25]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should return all 3 points+ assert len(result) == 3+ assert all("name" in p and p["name"] == "Area" for p in result)+++def test_area_chart_tonexty() -> None:+ """Test stacked area chart with fill='tonexty'."""+ fig = go.Figure()+ # First trace fills to zero+ fig.add_trace(+ go.Scatter(+ x=[1, 2, 3],+ y=[10, 15, 12],+ fill="tozeroy",+ mode="lines",+ name="Bottom",+ )+ )+ # Second trace fills to previous trace+ fig.add_trace(+ go.Scatter(+ x=[1, 2, 3],+ y=[20, 25, 22],+ fill="tonexty",+ mode="lines",+ name="Top",+ )+ )++ plot = plotly(fig)++ selection = {+ "range": {"x": [1, 3], "y": [0, 30]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should return points from both traces (3 + 3 = 6)+ assert len(result) == 6++ # Check we have points from both traces+ bottom_points = [p for p in result if p.get("name") == "Bottom"]+ top_points = [p for p in result if p.get("name") == "Top"]+ assert len(bottom_points) == 3+ assert len(top_points) == 3+++def test_area_chart_stackgroup() -> None:+ """Test stacked area chart using stackgroup property."""+ fig = go.Figure()+ fig.add_trace(+ go.Scatter(+ x=[1, 2, 3, 4],+ y=[10, 20, 15, 25],+ stackgroup="one",+ mode="lines",+ name="Series A",+ )+ )+ fig.add_trace(+ go.Scatter(+ x=[1, 2, 3, 4],+ y=[5, 10, 8, 12],+ stackgroup="one",+ mode="lines",+ name="Series B",+ )+ )++ plot = plotly(fig)++ selection = {+ "range": {"x": [2, 3], "y": [0, 50]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should return 2 points from each trace (4 total)+ assert len(result) == 4++ series_a = [p for p in result if p.get("name") == "Series A"]+ series_b = [p for p in result if p.get("name") == "Series B"]+ assert len(series_a) == 2+ assert len(series_b) == 2+++def test_area_chart_mode_none() -> None:+ """Test area chart with mode='none' (fill only, no line)."""+ fig = go.Figure(+ data=go.Scatter(+ x=[1, 2, 3, 4],+ y=[10, 25, 15, 30],+ fill="tozeroy",+ mode="none", # No line, just fill+ name="Fill Only",+ )+ )++ plot = plotly(fig)++ selection = {+ "range": {"x": [1, 4], "y": [0, 35]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should still return all 4 points even with mode='none'+ assert len(result) == 4+++def test_area_chart_with_axis_titles() -> None:+ """Test area chart selection with custom axis titles."""+ fig = go.Figure(+ data=go.Scatter(+ x=[1, 2, 3, 4, 5],+ y=[100, 200, 150, 250, 300],+ fill="tozeroy",+ mode="lines",+ )+ )+ fig.update_xaxes(title_text="Time")+ fig.update_yaxes(title_text="Value")++ plot = plotly(fig)++ selection = {+ "range": {"x": [2, 4], "y": [0, 300]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should use custom axis titles as field names+ assert len(result) == 3+ assert result[0]["Time"] == 2+ assert result[0]["Value"] == 200+ assert result[1]["Time"] == 3+ assert result[1]["Value"] == 150+ assert result[2]["Time"] == 4+ assert result[2]["Value"] == 250+++def test_area_chart_empty_selection() -> None:+ """Test area chart with selection range containing no points."""+ fig = go.Figure(+ data=go.Scatter(+ x=[1, 2, 3],+ y=[10, 20, 30],+ fill="tozeroy",+ mode="lines",+ )+ )++ plot = plotly(fig)++ # Selection range outside data+ selection = {+ "range": {"x": [10, 20], "y": [0, 100]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should return empty list+ assert result == []+++def test_area_chart_single_point_selection() -> None:+ """Test area chart with selection covering only one point."""+ fig = go.Figure(+ data=go.Scatter(+ x=[1, 2, 3, 4, 5],+ y=[10, 20, 15, 25, 30],+ fill="tozeroy",+ 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 the point at x=3+ assert len(result) == 1+ assert result[0]["x"] == 3+ assert result[0]["y"] == 15+++def test_area_chart_curve_number() -> None:+ """Test that area chart points include curveNumber for multi-trace plots."""+ fig = go.Figure()+ fig.add_trace(+ go.Scatter(+ x=[1, 2, 3],+ y=[10, 20, 15],+ fill="tozeroy",+ mode="lines",+ name="Area A",+ )+ )+ fig.add_trace(+ go.Scatter(+ x=[1, 2, 3],+ y=[15, 10, 20],+ fill="tozeroy",+ mode="lines",+ name="Area B",+ )+ )++ plot = plotly(fig)++ selection = {+ "range": {"x": [1, 3], "y": [0, 25]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should have 6 points total (3 from each trace)+ assert len(result) == 6++ # Check curveNumbers are present and distinct+ assert all("curveNumber" in p for p in result)+ curve_numbers = {p["curveNumber"] for p in result}+ assert curve_numbers == {0, 1}+++# ============================================================================+# Bar Chart Tests+# ============================================================================+++def test_bar_chart_basic() -> None:+ """Test that bar charts can be created (supported chart type)."""+ fig = go.Figure(+ data=go.Bar(+ x=["A", "B", "C"],+ y=[10, 20, 15],+ )+ )+ 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(+ data=go.Bar(+ x=["A", "B", "C", "D"],+ y=[10, 20, 15, 25],+ )+ )+ plot = plotly(fig)++ # Simulate a selection from frontend (selecting bars B and C)+ selection = {+ "range": {"x": [0.5, 2.5], "y": [0, 30]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should extract bars at indices 1 and 2 (B and C)+ assert len(result) == 2+ assert any(bar["x"] == "B" and bar["y"] == 20 for bar in result)+ assert any(bar["x"] == "C" and bar["y"] == 15 for bar in result)+++def test_bar_chart_selection_horizontal() -> None:+ """Test bar chart selection with horizontal bars."""+ fig = go.Figure(+ data=go.Bar(+ x=[10, 20, 15],+ y=["A", "B", "C"],+ orientation="h",+ )+ )+ plot = plotly(fig)++ # Simulate a selection (selecting bars A and B)+ selection = {+ "range": {"x": [0, 30], "y": [-0.5, 1.5]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should extract bars at y-indices 0 and 1 (A and B)+ assert len(result) == 2+ assert any(bar["y"] == "A" and bar["x"] == 10 for bar in result)+ assert any(bar["y"] == "B" and bar["x"] == 20 for bar in result)+++def test_bar_chart_categorical_axis() -> None:+ """Test bar chart with categorical x-axis (most common case)."""+ fig = go.Figure(+ data=go.Bar(+ x=["Product A", "Product B", "Product C"],+ y=[100, 200, 150],+ )+ )+ plot = plotly(fig)++ # Select middle bar (Product B at index 1)+ selection = {+ "range": {"x": [0.7, 1.3], "y": [0, 250]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ assert len(result) == 1+ assert result[0]["x"] == "Product B"+ assert result[0]["y"] == 200+++def test_bar_chart_numeric_axis() -> None:+ """Test bar chart with numeric x-axis (histogram-like)."""+ fig = go.Figure(+ data=go.Bar(+ x=[10, 20, 30, 40],+ y=[5, 12, 8, 15],+ )+ )+ plot = plotly(fig)++ # Select bars at x=20 and x=30+ selection = {+ "range": {"x": [15, 35], "y": [0, 20]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ assert len(result) == 2+ assert any(bar["x"] == 20 and bar["y"] == 12 for bar in result)+ assert any(bar["x"] == 30 and bar["y"] == 8 for bar in result)+++def test_bar_chart_stacked() -> None:+ """Test stacked bar chart - should return all segments at selected positions."""+ fig = go.Figure()+ # Two traces for stacked bars+ fig.add_trace(go.Bar(x=["A", "B", "C"], y=[10, 15, 12], name="Series1"))+ fig.add_trace(go.Bar(x=["A", "B", "C"], y=[5, 8, 6], name="Series2"))++ plot = plotly(fig)++ # Select bar at position A (index 0)+ selection = {+ "range": {"x": [-0.5, 0.5], "y": [0, 30]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should return both segments at position A (one from each trace)+ assert len(result) == 2+ assert any(bar["x"] == "A" and bar["y"] == 10 for bar in result)+ assert any(bar["x"] == "A" and bar["y"] == 5 for bar in result)+ # Check curveNumber to distinguish traces+ assert result[0]["curveNumber"] != result[1]["curveNumber"]+++def test_bar_chart_grouped() -> None:+ """Test grouped bar chart - should return all bars at selected position."""+ fig = go.Figure()+ # Two traces for grouped bars+ fig.add_trace(go.Bar(x=["A", "B", "C"], y=[20, 25, 18], name="Series1"))+ fig.add_trace(go.Bar(x=["A", "B", "C"], y=[15, 22, 16], name="Series2"))++ plot = plotly(fig)++ # Select category B (index 1)+ selection = {+ "range": {"x": [0.5, 1.5], "y": [0, 30]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should return both bars at category B+ assert len(result) == 2+ assert any(bar["x"] == "B" and bar["y"] == 25 for bar in result)+ assert any(bar["x"] == "B" and bar["y"] == 22 for bar in result)+++def test_bar_chart_empty_selection() -> None:+ """Test bar chart selection with range that includes no bars."""+ fig = go.Figure(+ data=go.Bar(+ x=["A", "B", "C"],+ y=[10, 20, 15],+ )+ )+ plot = plotly(fig)++ # Select a range with no bars (far to the right)+ selection = {+ "range": {"x": [5, 10], "y": [0, 30]},+ "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(+ data=go.Bar(+ x=["OnlyBar"],+ y=[42],+ )+ )+ plot = plotly(fig)++ # Select the single bar (categorical at index 0)+ selection = {+ "range": {"x": [-0.5, 0.5], "y": [0, 50]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should extract the single bar+ assert len(result) == 1+ assert result[0]["x"] == "OnlyBar"+ assert result[0]["y"] == 42+++def test_bar_chart_initial_selection() -> None:+ """Test that initial selection works with bar charts."""+ fig = go.Figure(+ data=go.Bar(+ x=["A", "B", "C", "D"],+ y=[10, 20, 15, 25],+ )+ )++ # Add an initial selection+ fig.add_selection(x0=0.5, x1=2.5, y0=0, y1=30, xref="x", yref="y")++ plot = plotly(fig)++ # Check that initial value contains the selection+ initial_value = plot._args.initial_value+ assert "range" in initial_value+ assert initial_value["range"]["x"] == [0.5, 2.5]+ assert initial_value["range"]["y"] == [0, 30]++ # For bar charts, should extract bars at indices 1 and 2 (B and C)+ assert "points" in initial_value+ assert len(initial_value["points"]) == 2+ assert any(+ bar["x"] == "B" and bar["y"] == 20 for bar in initial_value["points"])assert any(bar["x"] == "C" and bar["y"] == 15 for bar in initial_value["points"]@@ -1299,34 +1748,6 @@ def test_bar_chart_mixed_with_scatter() -> None: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@@ -1422,98 +1843,6 @@ 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(