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
Add support for reactive Plotly bar chart. (#7733)
Florian Verdonckf038d407b2ab
diff --git a/examples/third_party/plotly/bar_chart.py b/examples/third_party/plotly/bar_chart.pynew file mode 100644index 0000000000..b0d120c759--- /dev/null+++ b/examples/third_party/plotly/bar_chart.py@@ -0,0 +1,239 @@+# /// script+# requires-python = ">=3.9"+# dependencies = [+# "marimo",+# "plotly==6.5.1",+# ]+# ///+import marimo++__generated_with = "0.18.4"+app = marimo.App(width="medium")+++def _():+ import marimo as mo+ import plotly.graph_objects as go+ return go, mo+++def _(go, mo):+ mo.md("""+ # Plotly Bar Chart Selection++ This example demonstrates reactive bar chart selections with `mo.ui.plotly`.+ Select bars by clicking or dragging a box to see the selected data.+ """)+ return+++def _(go, mo):+ mo.md("## Simple Vertical Bar Chart")++ # Create a simple bar chart with categorical data+ fig_simple = go.Figure(+ data=go.Bar(+ x=["Product A", "Product B", "Product C", "Product D", "Product E"],+ y=[20, 35, 30, 25, 40],+ marker_color="steelblue",+ )+ )++ fig_simple.update_layout(+ title="Sales by Product",+ xaxis_title="Product",+ yaxis_title="Sales ($k)",+ )++ # Wrap with mo.ui.plotly to make it reactive+ bar_chart = mo.ui.plotly(fig_simple)++ return bar_chart, fig_simple+++def _(bar_chart, mo):+ mo.md(f"""+ ### Interactive Chart++ {bar_chart}++ ### Selected Bars++ Select bars by dragging a box over them:++ ```python+ {bar_chart.value}+ ```+ """)+ return+++def _(go, mo):+ mo.md("## Stacked Bar Chart")++ # Create a stacked bar chart+ fig_stacked = go.Figure()+ fig_stacked.add_trace(+ go.Bar(+ x=["Q1", "Q2", "Q3", "Q4"],+ y=[15, 20, 18, 22],+ name="Product A",+ marker_color="steelblue",+ )+ )+ fig_stacked.add_trace(+ go.Bar(+ x=["Q1", "Q2", "Q3", "Q4"],+ y=[10, 15, 12, 18],+ name="Product B",+ marker_color="lightcoral",+ )+ )++ fig_stacked.update_layout(+ title="Quarterly Sales by Product",+ xaxis_title="Quarter",+ yaxis_title="Sales ($k)",+ barmode="stack",+ )++ stacked_chart = mo.ui.plotly(fig_stacked)++ return fig_stacked, stacked_chart+++def _(stacked_chart, mo):+ mo.md(f"""+ ### Stacked Bar Chart++ {stacked_chart}++ **Note:** When you select a stacked bar, all segments at that position are returned!++ ### Selected Data++ ```python+ {stacked_chart.value}+ ```+ """)+ return+++def _(go, mo):+ mo.md("## Grouped Bar Chart")++ # Create a grouped bar chart+ fig_grouped = go.Figure()+ fig_grouped.add_trace(+ go.Bar(+ x=["Jan", "Feb", "Mar", "Apr"],+ y=[20, 25, 22, 28],+ name="2024",+ marker_color="steelblue",+ )+ )+ fig_grouped.add_trace(+ go.Bar(+ x=["Jan", "Feb", "Mar", "Apr"],+ y=[18, 23, 20, 25],+ name="2025",+ marker_color="lightcoral",+ )+ )++ fig_grouped.update_layout(+ title="Monthly Sales Comparison",+ xaxis_title="Month",+ yaxis_title="Sales ($k)",+ barmode="group",+ )++ grouped_chart = mo.ui.plotly(fig_grouped)++ return fig_grouped, grouped_chart+++def _(grouped_chart, mo):+ mo.md(f"""+ ### Grouped Bar Chart++ {grouped_chart}++ **Note:** When you select a category, all bars in that group are returned!++ ### Selected Data++ ```python+ {grouped_chart.value}+ ```+ """)+ return+++def _(go, mo):+ mo.md("## Horizontal Bar Chart")++ # Create a horizontal bar chart+ fig_horizontal = go.Figure(+ data=go.Bar(+ x=[30, 45, 35, 50, 40],+ y=["Team A", "Team B", "Team C", "Team D", "Team E"],+ orientation="h",+ marker_color="mediumseagreen",+ )+ )++ fig_horizontal.update_layout(+ title="Team Performance",+ xaxis_title="Score",+ yaxis_title="Team",+ )++ horizontal_chart = mo.ui.plotly(fig_horizontal)++ return fig_horizontal, horizontal_chart+++def _(horizontal_chart, mo):+ mo.md(f"""+ ### Horizontal Bar Chart++ {horizontal_chart}++ ### Selected Data++ ```python+ {horizontal_chart.value}+ ```+ """)+ return+++def _(mo):+ mo.md("""+ ## How It Works++ - **Selection**: Drag a box over bars to select them+ - **Categorical axes**: Each bar spans from (index - 0.5) to (index + 0.5)+ - **Stacked/Grouped**: All bars at a position are returned when that position is selected+ - **Data format**: Returns a list of `{"x": value, "y": value, "curveNumber": trace_index}`++ This allows you to build reactive dashboards where selecting bars filters other+ visualizations or displays detailed information about the selected data.+ """)+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.pyindex 511650ce53..992907c650 100644--- a/marimo/_plugins/ui/_impl/plotly.py+++ b/marimo/_plugins/ui/_impl/plotly.py@@ -45,7 +45,7 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):cursor on the frontend, get them as a list of dicts in Python!This function currently only supports scatter plots, treemap charts,- sunburst charts and heatmaps.+ sunburst charts, heatmaps, and bar charts.Examples:```python@@ -165,8 +165,8 @@ 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 traces - they're handled separately below- if getattr(trace, "type", None) == "heatmap":+ # Skip heatmap and bar traces - they're handled separately below+ if getattr(trace, "type", None) in ("heatmap", "bar"):continuex_data = getattr(trace, "x", None)y_data = getattr(trace, "y", None)@@ -197,6 +197,10 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):if has_heatmap and initial_value.get("range"):_append_heatmap_cells_to_selection(figure, initial_value)+ # 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+figure.for_each_selection(add_selection)super().__init__(@@ -269,6 +273,15 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):self._figure, self._selection_data)+ has_bar = any(+ getattr(trace, "type", None) == "bar"+ for trace in self._figure.data+ )++ # For bar charts with a range selection, extract all bars in range+ if has_bar and value.get("range"):+ _append_bar_items_to_selection(self._figure, self._selection_data)+result = self.pointsreturn result@@ -290,8 +303,8 @@ def _append_heatmap_cells_to_selection()if heatmap_cells:# Append heatmap cells to existing points (e.g., scatter)- # instead of replacing them- existing_points = selection_data.get("points", [])+ # Filter out empty dicts that may come from frontend+ existing_points = [p for p in selection_data.get("points", []) if p]existing_indices = selection_data.get("indices", [])selection_data["points"] = existing_points + heatmap_cellsselection_data["indices"] = existing_indices + list(@@ -461,3 +474,218 @@ def _extract_heatmap_cells_fallback()return selected_cells+++def _append_bar_items_to_selection(+ figure: go.Figure, selection_data: dict[str, Any]+) -> None:+ """Append bars within the selection range to the selection data.++ This modifies selection_data in place, appending any bars+ that fall within the range to the existing points and indices.+ """+ range_value = selection_data.get("range")+ if not isinstance(range_value, dict):+ return++ bar_items = _extract_bars_from_range(+ figure, cast(dict[str, Any], range_value)+ )+ if bar_items:+ # Append bar items to existing points (e.g., scatter)+ # Filter out empty dicts that may come from frontend+ existing_points = [p for p in selection_data.get("points", []) if p]+ existing_indices = selection_data.get("indices", [])+ selection_data["points"] = existing_points + bar_items+ selection_data["indices"] = existing_indices + list(+ range(+ len(existing_indices),+ len(existing_indices) + len(bar_items),+ )+ )+++def _extract_bars_from_range(+ figure: go.Figure, range_data: dict[str, Any]+) -> list[dict[str, Any]]:+ """Extract bars that fall within a selection range."""++ if not range_data.get("x") or not range_data.get("y"):+ return []++ x_range = range_data["x"]+ y_range = range_data["y"]+ x_min, x_max = min(x_range), max(x_range)+ y_min, y_max = min(y_range), max(y_range)++ # Use numpy fast path if available for better performance on large datasets+ if DependencyManager.numpy.has():+ return _extract_bars_numpy(figure, x_min, x_max, y_min, y_max)++ return _extract_bars_fallback(figure, x_min, x_max, y_min, y_max)+++def _extract_bars_numpy(+ figure: go.Figure,+ x_min: float,+ x_max: float,+ y_min: float,+ y_max: float,+) -> list[dict[str, Any]]:+ """Extract bars using numpy for O(selected) complexity."""+ import numpy as np++ selected_bars: list[dict[str, Any]] = []++ for trace_idx, trace in enumerate(figure.data):+ if getattr(trace, "type", None) != "bar":+ continue++ x_data = getattr(trace, "x", None)+ y_data = getattr(trace, "y", None)++ if x_data is None or y_data is None:+ continue++ # Determine bar orientation (default is 'v' for vertical)+ orientation = getattr(trace, "orientation", "v")+ if orientation is None:+ orientation = "v"++ # Convert to numpy arrays for vectorized operations+ x_arr = np.asarray(x_data)+ y_arr = np.asarray(y_data)++ # For vertical bars: filter by x-axis position+ # For horizontal bars: filter by y-axis position (swap roles)+ if orientation == "v":+ # Vertical bars: x-axis determines which bars are selected+ # y-axis is the value (we don't filter by it, similar to Altair)+ position_data = x_arr+ value_data = y_arr+ pos_min, pos_max = x_min, x_max+ else: # orientation == "h"+ # Horizontal bars: y-axis determines which bars are selected+ # x-axis is the value+ position_data = y_arr+ value_data = x_arr+ pos_min, pos_max = y_min, y_max++ # Determine if position axis is numeric or categorical+ pos_is_numeric = np.issubdtype(position_data.dtype, np.number)++ # Compute mask for valid indices+ if pos_is_numeric:+ # Numeric axis: direct range comparison+ # TODO: Consider bar width in future implementations+ # Currently treating bars as points at their position value+ pos_mask = (position_data >= pos_min) & (position_data <= pos_max)+ else:+ # Categorical axis: each bar spans (index - 0.5) to (index + 0.5)+ # Selection overlaps if: pos_max > bar_min AND pos_min < bar_max+ pos_indices = np.arange(len(position_data))+ pos_mask = (pos_max > pos_indices - 0.5) & (+ pos_min < pos_indices + 0.5+ )++ # Get indices where mask is True+ selected_indices = np.where(pos_mask)[0]++ # Iterate only over selected indices+ for i in selected_indices:+ if orientation == "v":+ selected_bars.append(+ {+ "x": x_data[i],+ "y": value_data[i].item()+ if hasattr(value_data[i], "item")+ else value_data[i],+ "curveNumber": trace_idx,+ }+ )+ else: # horizontal+ selected_bars.append(+ {+ "x": value_data[i].item()+ if hasattr(value_data[i], "item")+ else value_data[i],+ "y": y_data[i],+ "curveNumber": trace_idx,+ }+ )++ return selected_bars+++def _extract_bars_fallback(+ figure: go.Figure,+ x_min: float,+ x_max: float,+ y_min: float,+ y_max: float,+) -> list[dict[str, Any]]:+ """Extract bars using pure Python (fallback when numpy unavailable)."""+ selected_bars: list[dict[str, Any]] = []++ for trace_idx, trace in enumerate(figure.data):+ if getattr(trace, "type", None) != "bar":+ continue++ x_data = getattr(trace, "x", None)+ y_data = getattr(trace, "y", None)++ if x_data is None or y_data is None:+ continue++ # Determine bar orientation (default is 'v' for vertical)+ orientation = getattr(trace, "orientation", "v")+ if orientation is None:+ orientation = "v"++ # For vertical bars: filter by x-axis position+ # For horizontal bars: filter by y-axis position+ if orientation == "v":+ position_data = x_data+ value_data = y_data+ pos_min, pos_max = x_min, x_max+ else: # orientation == "h"+ position_data = y_data+ value_data = x_data+ pos_min, pos_max = y_min, y_max++ # Iterate through bars+ for i, pos_val in enumerate(position_data):+ # Check if bar position is within selection range+ pos_in_range = False++ if isinstance(pos_val, (int, float)):+ # Numeric axis: direct comparison+ # TODO: Consider bar width in future implementations+ # Currently treating bars as points at their position value+ pos_in_range = pos_min <= pos_val <= pos_max+ else:+ # Categorical axis: each bar spans (index - 0.5) to (index + 0.5)+ # Include bar if selection range strictly overlaps with bar bounds+ bar_min = i - 0.5+ bar_max = i + 0.5+ pos_in_range = not (pos_max <= bar_min or pos_min >= bar_max)++ if pos_in_range:+ if orientation == "v":+ selected_bars.append(+ {+ "x": x_data[i],+ "y": value_data[i],+ "curveNumber": trace_idx,+ }+ )+ else: # horizontal+ selected_bars.append(+ {+ "x": value_data[i],+ "y": y_data[i],+ "curveNumber": trace_idx,+ }+ )++ return selected_barsdiff --git a/tests/_plugins/ui/_impl/test_plotly.py b/tests/_plugins/ui/_impl/test_plotly.pyindex 1c3ee6c1a2..14708a1494 100644--- a/tests/_plugins/ui/_impl/test_plotly.py+++ b/tests/_plugins/ui/_impl/test_plotly.py@@ -12,6 +12,8 @@ import plotly.express as pximport plotly.graph_objects as gofrom marimo._plugins.ui._impl.plotly import (+ _extract_bars_fallback,+ _extract_bars_numpy,_extract_heatmap_cells_fallback,_extract_heatmap_cells_numpy,plotly,@@ -742,6 +744,390 @@ def test_heatmap_numpy_and_fallback_produce_same_results() -> None:assert np_cell["curveNumber"] == fb_cell["curveNumber"]+# ============================================================================+# 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"]+ )+++def test_bar_chart_curve_number() -> None:+ """Test that bar chart cells include curveNumber for multi-trace plots."""+ fig = go.Figure()+ fig.add_trace(go.Scatter(x=[1, 2], y=[1, 2])) # trace 0+ fig.add_trace(go.Bar(x=["A", "B"], y=[10, 20])) # trace 1++ plot = plotly(fig)++ selection = {+ "range": {"x": [-0.5, 0.5], "y": [0, 30]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Bar should have curveNumber = 1+ bar_items = [r for r in result if "x" in r and r["x"] == "A"]+ assert len(bar_items) > 0+ assert bar_items[0]["curveNumber"] == 1+++def test_bar_chart_mixed_with_scatter() -> None:+ """Test figure with both scatter and bar traces."""+ fig = go.Figure()+ fig.add_trace(go.Scatter(x=[0, 1, 2], y=[5, 10, 15], mode="markers"))+ fig.add_trace(go.Bar(x=["A", "B", "C"], y=[10, 20, 15]))++ plot = plotly(fig)++ # Select range that includes both scatter point and bar+ selection = {+ "range": {"x": [-0.5, 1.5], "y": [5, 25]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should include bars A and B (indices 0 and 1)+ 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)+++def test_bar_numpy_and_fallback_match_categorical() -> None:+ """Test that numpy and fallback produce identical results for categorical bars."""+ fig = go.Figure(+ data=go.Bar(+ x=["A", "B", "C", "D"],+ y=[10, 20, 15, 25],+ )+ )++ x_min, x_max = 0.5, 2.5+ y_min, y_max = 0, 30++ # Get results from both implementations+ numpy_result = _extract_bars_numpy(fig, x_min, x_max, y_min, y_max)+ fallback_result = _extract_bars_fallback(fig, x_min, x_max, y_min, y_max)++ # Both should return the same number of bars+ assert len(numpy_result) == len(fallback_result)++ # Sort results for comparison+ def sort_key(bar: dict[str, Any]) -> tuple[Any, ...]:+ return (bar["x"], bar["y"], bar["curveNumber"])++ numpy_sorted = sorted(numpy_result, key=sort_key)+ fallback_sorted = sorted(fallback_result, key=sort_key)++ # Compare each bar+ for np_bar, fb_bar in zip(numpy_sorted, fallback_sorted):+ assert np_bar["x"] == fb_bar["x"]+ assert np_bar["y"] == fb_bar["y"]+ assert np_bar["curveNumber"] == fb_bar["curveNumber"]+++def test_bar_numpy_and_fallback_match_numeric() -> None:+ """Test that numpy and fallback produce identical results for numeric bars."""+ fig = go.Figure(+ data=go.Bar(+ x=[10, 20, 30, 40],+ y=[5, 12, 8, 15],+ )+ )++ x_min, x_max = 15, 35+ y_min, y_max = 0, 20++ numpy_result = _extract_bars_numpy(fig, x_min, x_max, y_min, y_max)+ fallback_result = _extract_bars_fallback(fig, x_min, x_max, y_min, y_max)++ assert len(numpy_result) == len(fallback_result)++ def sort_key(bar: dict[str, Any]) -> tuple[Any, ...]:+ return (bar["x"], bar["y"], bar["curveNumber"])++ numpy_sorted = sorted(numpy_result, key=sort_key)+ fallback_sorted = sorted(fallback_result, key=sort_key)++ for np_bar, fb_bar in zip(numpy_sorted, fallback_sorted):+ assert np_bar["x"] == fb_bar["x"]+ assert np_bar["y"] == fb_bar["y"]+ assert np_bar["curveNumber"] == fb_bar["curveNumber"]+++def test_bar_numpy_and_fallback_match_horizontal() -> None:+ """Test that numpy and fallback produce identical results for horizontal bars."""+ fig = go.Figure(+ data=go.Bar(+ x=[10, 20, 15],+ y=["A", "B", "C"],+ orientation="h",+ )+ )++ x_min, x_max = 0, 30+ y_min, y_max = -0.5, 1.5++ numpy_result = _extract_bars_numpy(fig, x_min, x_max, y_min, y_max)+ fallback_result = _extract_bars_fallback(fig, x_min, x_max, y_min, y_max)++ assert len(numpy_result) == len(fallback_result)++ def sort_key(bar: dict[str, Any]) -> tuple[Any, ...]:+ return (str(bar["y"]), bar["x"], bar["curveNumber"])++ numpy_sorted = sorted(numpy_result, key=sort_key)+ fallback_sorted = sorted(fallback_result, key=sort_key)++ for np_bar, fb_bar in zip(numpy_sorted, fallback_sorted):+ assert np_bar["x"] == fb_bar["x"]+ assert np_bar["y"] == fb_bar["y"]+ assert np_bar["curveNumber"] == fb_bar["curveNumber"]++def test_heatmap_numpy_and_fallback_numeric_axes() -> None:"""Test numpy and fallback with numeric axes produce identical results."""fig = go.Figure(