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
Reactive Plotly heatmap (#7546)
Florian Verdonck88abd526ed49
diff --git a/examples/third_party/plotly/heatmap.py b/examples/third_party/plotly/heatmap.pynew file mode 100644index 0000000000..c170793860--- /dev/null+++ b/examples/third_party/plotly/heatmap.py@@ -0,0 +1,59 @@+import marimo++__generated_with = "0.18.4"+app = marimo.App(width="medium")+++def _():+ import marimo as mo+ import plotly.graph_objects as go+ import numpy as np++ # 1. Create your heatmap data+ z = np.random.rand(10, 10) * 100++ # 2. Create the plotly figure+ fig = go.Figure(+ data=go.Heatmap(+ z=z,+ x=["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"],+ y=[+ "Mon",+ "Tue",+ "Wed",+ "Thu",+ "Fri",+ "Sat",+ "Sun",+ "Mon2",+ "Tue2",+ "Wed2",+ ],+ colorscale="Viridis",+ )+ )++ # 3. Wrap it with mo.ui.plotly+ heatmap = mo.ui.plotly(fig)++ heatmap+ return heatmap, mo+++def _(heatmap, mo):+ # 4. Display it+ mo.md(f"""+ ## Sales Heatmap++ {heatmap}++ ### Selected Cells:+ {heatmap.value}+ """)+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.pyindex 028edb381c..511650ce53 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 currently only supports scatter plots, treemaps charts,- and sunbursts charts.+ This function currently only supports scatter plots, treemap charts,+ sunburst charts and heatmaps.Examples:```python@@ -112,6 +112,11 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):import plotly.io as pio # type:ignore+ # Store figure for later use in _convert_value+ self._figure: go.Figure = figure+ # Initialize selection data storage+ self._selection_data: PlotlySelection = {}+json_str = pio.to_json(figure)resolved_config: dict[str, Any] = {}@@ -160,15 +165,18 @@ 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":+ continuex_data = getattr(trace, "x", None)y_data = getattr(trace, "y", None)if x_data is None or y_data is None:continuefor point_idx, (x, y) in enumerate(zip(x_data, y_data)):- if (- selection.x0 <= x <= selection.x1- and selection.y0 <= y <= selection.y1- ):+ # Early exit if x is not in range+ if not (selection.x0 <= x <= selection.x1):+ continue+ if selection.y0 <= y <= selection.y1:selected_points.append({axis.title.text: val@@ -181,6 +189,14 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):initial_value["points"] = selected_pointsinitial_value["indices"] = selected_indices+ # For heatmaps with a range selection, extract all cells in range+ has_heatmap = any(+ getattr(trace, "type", None) == "heatmap"+ for trace in figure.data+ )+ if has_heatmap and initial_value.get("range"):+ _append_heatmap_cells_to_selection(figure, initial_value)+figure.for_each_selection(add_selection)super().__init__(@@ -240,5 +256,208 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):def _convert_value(self, value: PlotlySelection) -> Any:# Store the selection dataself._selection_data = value- # Default to returning the points- return self.points++ has_heatmap = any(+ getattr(trace, "type", None) == "heatmap"+ 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"):+ _append_heatmap_cells_to_selection(+ self._figure, self._selection_data+ )++ result = self.points+ return result+++def _append_heatmap_cells_to_selection(+ figure: go.Figure, selection_data: dict[str, Any]+) -> None:+ """Append heatmap cells within the selection range to the selection data.++ This modifies selection_data in place, appending any heatmap cells+ that fall within the range to the existing points and indices.+ """+ range_value = selection_data.get("range")+ if not isinstance(range_value, dict):+ return++ heatmap_cells = _extract_heatmap_cells_from_range(+ figure, cast(dict[str, Any], range_value)+ )+ if heatmap_cells:+ # Append heatmap cells to existing points (e.g., scatter)+ # instead of replacing them+ existing_points = selection_data.get("points", [])+ existing_indices = selection_data.get("indices", [])+ selection_data["points"] = existing_points + heatmap_cells+ selection_data["indices"] = existing_indices + list(+ range(+ len(existing_indices),+ len(existing_indices) + len(heatmap_cells),+ )+ )+++def _extract_heatmap_cells_from_range(+ figure: go.Figure, range_data: dict[str, Any]+) -> list[dict[str, Any]]:+ """Extract heatmap cells 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 heatmaps+ if DependencyManager.numpy.has():+ return _extract_heatmap_cells_numpy(figure, x_min, x_max, y_min, y_max)++ return _extract_heatmap_cells_fallback(figure, x_min, x_max, y_min, y_max)+++def _extract_heatmap_cells_numpy(+ figure: go.Figure,+ x_min: float,+ x_max: float,+ y_min: float,+ y_max: float,+) -> list[dict[str, Any]]:+ """Extract heatmap cells using numpy for O(selected) complexity."""+ import numpy as np++ selected_cells: list[dict[str, Any]] = []++ for trace_idx, trace in enumerate(figure.data):+ if getattr(trace, "type", None) != "heatmap":+ continue++ x_data = getattr(trace, "x", None)+ y_data = getattr(trace, "y", None)+ z_data = getattr(trace, "z", None)++ if x_data is None or y_data is None or z_data is None:+ continue++ # Convert to numpy arrays for vectorized operations+ x_arr = np.asarray(x_data)+ y_arr = np.asarray(y_data)+ z_arr = np.asarray(z_data)++ # Determine if axes are numeric+ x_is_numeric = np.issubdtype(x_arr.dtype, np.number)+ y_is_numeric = np.issubdtype(y_arr.dtype, np.number)++ # Compute masks for valid indices+ if x_is_numeric:+ x_mask = (x_arr >= x_min) & (x_arr <= x_max)+ else:+ # Categorical: cell spans (index - 0.5) to (index + 0.5)+ # Strict overlap: x_max > cell_x_min and x_min < cell_x_max+ x_indices = np.arange(len(x_arr))+ x_mask = (x_max > x_indices - 0.5) & (x_min < x_indices + 0.5)++ if y_is_numeric:+ y_mask = (y_arr >= y_min) & (y_arr <= y_max)+ else:+ # Categorical: cell spans (index - 0.5) to (index + 0.5)+ # Strict overlap: y_max > cell_y_min and y_min < cell_y_max+ y_indices = np.arange(len(y_arr))+ y_mask = (y_max > y_indices - 0.5) & (y_min < y_indices + 0.5)++ # Get indices where masks are True+ y_idx = np.where(y_mask)[0]+ x_idx = np.where(x_mask)[0]++ # Iterate only over selected indices (O(selected) instead of O(n*m))+ for i in y_idx:+ for j in x_idx:+ # Bounds check for z_data to handle malformed/ragged arrays+ if i >= len(z_arr) or j >= len(z_arr[i]):+ continue+ selected_cells.append(+ {+ "x": x_data[j],+ "y": y_data[i],+ "z": z_arr[i][j].item()+ if hasattr(z_arr[i][j], "item")+ else z_arr[i][j],+ "curveNumber": trace_idx,+ }+ )++ return selected_cells+++def _extract_heatmap_cells_fallback(+ figure: go.Figure,+ x_min: float,+ x_max: float,+ y_min: float,+ y_max: float,+) -> list[dict[str, Any]]:+ """Extract heatmap cells using pure Python (fallback when numpy unavailable)."""+ selected_cells: list[dict[str, Any]] = []++ # Iterate through traces to find heatmaps+ for trace_idx, trace in enumerate(figure.data):+ if getattr(trace, "type", None) != "heatmap":+ continue++ x_data = getattr(trace, "x", None)+ y_data = getattr(trace, "y", None)+ z_data = getattr(trace, "z", None)++ if x_data is None or y_data is None or z_data is None:+ continue++ # Iterate through the heatmap cells+ for i, y_val in enumerate(y_data):+ for j, x_val in enumerate(x_data):+ # Check if cell is within selection range+ # Handle both numeric and categorical data+ x_in_range = False+ y_in_range = False++ if isinstance(x_val, (int, float)):+ x_in_range = x_min <= x_val <= x_max+ else:+ # Categorical - each cell spans from (index - 0.5) to (index + 0.5)+ # Include cell if selection range strictly overlaps with cell bounds+ cell_x_min = j - 0.5+ cell_x_max = j + 0.5+ x_in_range = not (+ x_max <= cell_x_min or x_min >= cell_x_max+ )++ if isinstance(y_val, (int, float)):+ y_in_range = y_min <= y_val <= y_max+ else:+ # Categorical - each cell spans from (index - 0.5) to (index + 0.5)+ # Include cell if selection range strictly overlaps with cell bounds+ cell_y_min = i - 0.5+ cell_y_max = i + 0.5+ y_in_range = not (+ y_max <= cell_y_min or y_min >= cell_y_max+ )++ if x_in_range and y_in_range:+ # Bounds check for z_data to handle malformed/ragged arrays+ if i >= len(z_data) or j >= len(z_data[i]):+ continue+ selected_cells.append(+ {+ "x": x_val,+ "y": y_val,+ "z": z_data[i][j],+ "curveNumber": trace_idx,+ }+ )++ return selected_cellsdiff --git a/tests/_plugins/ui/_impl/test_plotly.py b/tests/_plugins/ui/_impl/test_plotly.pyindex 89b24bdafd..1c3ee6c1a2 100644--- a/tests/_plugins/ui/_impl/test_plotly.py+++ b/tests/_plugins/ui/_impl/test_plotly.py@@ -11,7 +11,11 @@ pytest.importorskip("plotly.graph_objects")import plotly.express as pximport plotly.graph_objects as go-from marimo._plugins.ui._impl.plotly import plotly+from marimo._plugins.ui._impl.plotly import (+ _extract_heatmap_cells_fallback,+ _extract_heatmap_cells_numpy,+ plotly,+)def test_basic_scatter_plot() -> None:@@ -351,3 +355,423 @@ def test_selection_boundary_conditions() -> None:initial_value = plot._args.initial_valueassert len(initial_value["indices"]) == 1assert 1 in initial_value["indices"]+++def test_heatmap_basic() -> None:+ """Test that heatmaps can be created (supported chart type)."""+ fig = go.Figure(+ data=go.Heatmap(+ z=[[1, 2, 3], [4, 5, 6], [7, 8, 9]],+ x=["A", "B", "C"],+ y=["X", "Y", "Z"],+ )+ )+ plot = plotly(fig)++ assert plot is not None+ assert plot.value == []+++def test_heatmap_selection_numeric() -> None:+ """Test heatmap selection with numeric axes."""+ fig = go.Figure(+ data=go.Heatmap(+ z=[[1, 2, 3], [4, 5, 6], [7, 8, 9]],+ x=[10, 20, 30],+ y=[100, 200, 300],+ )+ )+ plot = plotly(fig)++ # Simulate a selection from frontend+ selection = {+ "range": {"x": [15, 25], "y": [150, 250]},+ "points": [], # Frontend might send empty for heatmaps+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should extract cells at (20, 200) within the range+ assert len(result) > 0+ # Check that extracted cells have x, y, z values+ for cell in result:+ assert "x" in cell+ assert "y" in cell+ assert "z" in cell+++def test_heatmap_selection_categorical() -> None:+ """Test heatmap selection with categorical axes."""+ fig = go.Figure(+ data=go.Heatmap(+ z=[[1, 2, 3], [4, 5, 6], [7, 8, 9]],+ x=["A", "B", "C"],+ y=["X", "Y", "Z"],+ )+ )+ plot = plotly(fig)++ # For categorical axes, selection uses indices+ # Select cells around index 1 (0.5 to 1.5 covers index 1)+ selection = {+ "range": {"x": [0.5, 1.5], "y": [0.5, 1.5]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should extract the cell at index (1, 1) which is ("B", "Y")+ assert len(result) > 0+ assert any(cell["x"] == "B" and cell["y"] == "Y" for cell in result)+++def test_heatmap_selection_mixed_axes() -> None:+ """Test heatmap with one numeric and one categorical axis."""+ fig = go.Figure(+ data=go.Heatmap(+ z=[[1, 2, 3], [4, 5, 6]],+ x=[10, 20, 30], # Numeric+ y=["Row1", "Row2"], # Categorical+ )+ )+ plot = plotly(fig)++ selection = {+ "range": {"x": [15, 25], "y": [-0.5, 0.5]}, # Select first row+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should extract cell at (20, "Row1")+ assert len(result) > 0+ assert any(cell["x"] == 20 and cell["y"] == "Row1" for cell in result)+++def test_heatmap_selection_all_cells() -> None:+ """Test selecting all cells in a small heatmap."""+ fig = go.Figure(+ data=go.Heatmap(+ z=[[1, 2], [3, 4]],+ x=["A", "B"],+ y=["X", "Y"],+ )+ )+ plot = plotly(fig)++ # Select entire heatmap (categorical uses indices -0.5 to n-0.5)+ selection = {+ "range": {"x": [-0.5, 1.5], "y": [-0.5, 1.5]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should have all 4 cells+ assert len(result) == 4+ # Check we have all combinations+ expected_combinations = {("A", "X"), ("A", "Y"), ("B", "X"), ("B", "Y")}+ actual_combinations = {(cell["x"], cell["y"]) for cell in result}+ assert actual_combinations == expected_combinations+++def test_heatmap_selection_no_cells() -> None:+ """Test heatmap selection with range that includes no cells."""+ fig = go.Figure(+ data=go.Heatmap(+ z=[[1, 2, 3]],+ x=[10, 20, 30],+ y=[100],+ )+ )+ plot = plotly(fig)++ # Select a range with no cells+ selection = {+ "range": {"x": [50, 60], "y": [200, 300]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should be empty+ assert result == []+++def test_heatmap_selection_invalid_range_type() -> None:+ """Test heatmap with selection where range is not a dict."""+ fig = go.Figure(+ data=go.Heatmap(+ z=[[1, 2], [3, 4]],+ x=["A", "B"],+ y=["X", "Y"],+ )+ )+ plot = plotly(fig)++ # Selection with invalid range type (should be handled by isinstance check)+ selection = {"range": "invalid", "points": [], "indices": []}++ result = plot._convert_value(selection)++ # Should handle gracefully without crashing+ assert result == []+++def test_heatmap_selection_missing_x_or_y() -> None:+ """Test heatmap selection with incomplete range data."""+ fig = go.Figure(+ data=go.Heatmap(+ z=[[1, 2], [3, 4]],+ x=["A", "B"],+ y=["X", "Y"],+ )+ )+ plot = plotly(fig)++ # Selection with only x range+ selection = {"range": {"x": [0, 1]}, "points": [], "indices": []}++ result = plot._convert_value(selection)++ # Should return empty list (checked in _extract_heatmap_cells_from_range)+ assert result == []+++def test_heatmap_curve_number() -> None:+ """Test that heatmap 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.Heatmap(z=[[1, 2]], x=["A", "B"], y=["X"])) # trace 1++ plot = plotly(fig)++ selection = {+ "range": {"x": [-0.5, 1.5], "y": [-0.5, 0.5]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Heatmap cells should have curveNumber = 1+ assert len(result) > 0+ assert all(cell.get("curveNumber") == 1 for cell in result)+++def test_heatmap_initial_selection() -> None:+ """Test that initial selection works with heatmaps."""+ fig = go.Figure(+ data=go.Heatmap(+ z=[[1, 2, 3], [4, 5, 6], [7, 8, 9]],+ x=["A", "B", "C"],+ y=["X", "Y", "Z"],+ )+ )++ # Add an initial selection+ fig.add_selection(x0=0.5, x1=1.5, y0=0.5, y1=1.5, 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, 1.5]+ assert initial_value["range"]["y"] == [0.5, 1.5]++ # For heatmap, should extract cells, not scatter points+ assert "points" in initial_value+ assert len(initial_value["points"]) > 0++ # Should have x, y, z values (heatmap cells)+ for point in initial_value["points"]:+ assert "x" in point+ assert "y" in point+ assert "z" in point++ # Should extract cell at index (1, 1) which is ("B", "Y", 5)+ assert any(+ p["x"] == "B" and p["y"] == "Y" and p["z"] == 5+ for p in initial_value["points"]+ )+++def test_heatmap_empty() -> None:+ """Test heatmap with empty data."""+ fig = go.Figure(+ data=go.Heatmap(+ z=[],+ x=[],+ y=[],+ )+ )+ plot = plotly(fig)++ selection = {+ "range": {"x": [-0.5, 0.5], "y": [-0.5, 0.5]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should return empty list for empty heatmap+ assert result == []+++def test_heatmap_single_cell() -> None:+ """Test heatmap with a single cell."""+ fig = go.Figure(+ data=go.Heatmap(+ z=[[42]],+ x=["A"],+ y=["X"],+ )+ )+ plot = plotly(fig)++ # Selection that covers the single cell (categorical at index 0)+ selection = {+ "range": {"x": [-0.5, 0.5], "y": [-0.5, 0.5]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should extract the single cell+ assert len(result) == 1+ assert result[0]["x"] == "A"+ assert result[0]["y"] == "X"+ assert result[0]["z"] == 42+++def test_heatmap_single_cell_numeric() -> None:+ """Test heatmap with a single cell and numeric axes."""+ fig = go.Figure(+ data=go.Heatmap(+ z=[[99]],+ x=[5],+ y=[10],+ )+ )+ plot = plotly(fig)++ # Selection that covers the single numeric cell+ selection = {+ "range": {"x": [0, 10], "y": [5, 15]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should extract the single cell+ assert len(result) == 1+ assert result[0]["x"] == 5+ assert result[0]["y"] == 10+ assert result[0]["z"] == 99+++def test_heatmap_single_cell_outside_selection() -> None:+ """Test single-cell heatmap where selection doesn't cover the cell."""+ fig = go.Figure(+ data=go.Heatmap(+ z=[[42]],+ x=["A"],+ y=["X"],+ )+ )+ plot = plotly(fig)++ # Selection that doesn't cover the cell (categorical at index 0)+ selection = {+ "range": {"x": [1.5, 2.5], "y": [1.5, 2.5]},+ "points": [],+ "indices": [],+ }++ result = plot._convert_value(selection)++ # Should return empty list since selection doesn't cover the cell+ assert result == []+++def test_heatmap_numpy_and_fallback_produce_same_results() -> None:+ """Test that numpy and fallback implementations produce identical results."""+ fig = go.Figure(+ data=go.Heatmap(+ z=[[1, 2, 3], [4, 5, 6], [7, 8, 9]],+ x=["A", "B", "C"],+ y=["X", "Y", "Z"],+ )+ )++ x_min, x_max = 0.5, 2.5+ y_min, y_max = 0.5, 2.5++ # Get results from both implementations+ numpy_result = _extract_heatmap_cells_numpy(+ fig, x_min, x_max, y_min, y_max+ )+ fallback_result = _extract_heatmap_cells_fallback(+ fig, x_min, x_max, y_min, y_max+ )++ # Both should return the same number of cells+ assert len(numpy_result) == len(fallback_result)++ # Sort results for comparison (order might differ)+ def sort_key(cell: dict[str, Any]) -> tuple[Any, ...]:+ return (cell["x"], cell["y"], cell["z"])++ numpy_sorted = sorted(numpy_result, key=sort_key)+ fallback_sorted = sorted(fallback_result, key=sort_key)++ # Compare each cell+ for np_cell, fb_cell in zip(numpy_sorted, fallback_sorted):+ assert np_cell["x"] == fb_cell["x"]+ assert np_cell["y"] == fb_cell["y"]+ assert np_cell["z"] == fb_cell["z"]+ assert np_cell["curveNumber"] == fb_cell["curveNumber"]+++def test_heatmap_numpy_and_fallback_numeric_axes() -> None:+ """Test numpy and fallback with numeric axes produce identical results."""+ fig = go.Figure(+ data=go.Heatmap(+ z=[[1, 2, 3], [4, 5, 6], [7, 8, 9]],+ x=[10, 20, 30],+ y=[100, 200, 300],+ )+ )++ x_min, x_max = 15, 25+ y_min, y_max = 150, 250++ numpy_result = _extract_heatmap_cells_numpy(+ fig, x_min, x_max, y_min, y_max+ )+ fallback_result = _extract_heatmap_cells_fallback(+ fig, x_min, x_max, y_min, y_max+ )++ assert len(numpy_result) == len(fallback_result)++ def sort_key(cell: dict[str, Any]) -> tuple[Any, ...]:+ return (cell["x"], cell["y"], cell["z"])++ numpy_sorted = sorted(numpy_result, key=sort_key)+ fallback_sorted = sorted(fallback_result, key=sort_key)++ for np_cell, fb_cell in zip(numpy_sorted, fallback_sorted):+ assert np_cell["x"] == fb_cell["x"]+ assert np_cell["y"] == fb_cell["y"]+ assert np_cell["z"] == fb_cell["z"]+ assert np_cell["curveNumber"] == fb_cell["curveNumber"]