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
feat: add plotly scattermap/scattermapbox point selection support (#7975)
Myles Scolnick7b8c057beac6
diff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.pyindex eab2f43f0a..7dfbb36ffc 100644--- a/marimo/_plugins/ui/_impl/plotly.py+++ b/marimo/_plugins/ui/_impl/plotly.py@@ -392,6 +392,22 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):self._figure, self._selection_data)+ # Check for map-based scatter traces (scattermap, scattermapbox, scattergeo)+ # These use lat/lon instead of x/y+ map_scatter_types = ("scattermap", "scattermapbox", "scattergeo")+ has_map_scatter = any(+ getattr(trace, "type", None) in map_scatter_types+ for trace in self._figure.data+ )++ # For map scatter traces, extract points from the selection+ # Unlike regular scatter, map selections don't have a "range" - they have+ # direct point selection via lasso/box select on the map+ if has_map_scatter:+ _append_map_scatter_points_to_selection(+ self._figure, self._selection_data+ )+result = self.pointsreturn result@@ -1070,3 +1086,72 @@ def _extract_bars_fallback()return selected_bars+++def _append_map_scatter_points_to_selection(+ figure: go.Figure, selection_data: dict[str, Any]+) -> None:+ """Extract points from map scatter traces (scattermap, scattermapbox, scattergeo).++ These traces use lat/lon instead of x/y. If the frontend already sent+ points with lat/lon, we preserve them. Otherwise, we extract from trace data.+ """+ existing_points = [p for p in selection_data.get("points", []) if p]+ indices = selection_data.get("indices", [])++ # If frontend already sent lat/lon points, nothing to do+ if existing_points and any(+ "lat" in p or "lon" in p for p in existing_points+ ):+ return++ # Extract points from trace data using indices+ if not indices or existing_points:+ return++ map_types = ("scattermap", "scattermapbox", "scattergeo")+ extracted: list[dict[str, Any]] = []++ for trace_idx, trace in enumerate(figure.data):+ if getattr(trace, "type", None) not in map_types:+ continue++ lat_data = getattr(trace, "lat", None)+ lon_data = getattr(trace, "lon", None)+ if lat_data is None or lon_data is None:+ continue++ for idx in indices:+ if not (0 <= idx < len(lat_data)):+ continue++ point: dict[str, Any] = {+ "lat": lat_data[idx],+ "lon": lon_data[idx],+ "pointIndex": idx,+ "curveNumber": trace_idx,+ }++ # Add optional fields+ customdata = getattr(trace, "customdata", None)+ if customdata is not None and idx < len(customdata):+ point["customdata"] = customdata[idx]++ text = getattr(trace, "text", None)+ if text is not None:+ point["text"] = text if isinstance(text, str) else text[idx]++ hovertext = getattr(trace, "hovertext", None)+ if hovertext is not None:+ point["hovertext"] = (+ hovertext if isinstance(hovertext, str) else hovertext[idx]+ )++ name = getattr(trace, "name", None)+ if name:+ point["name"] = name++ extracted.append(point)++ if extracted:+ selection_data["points"] = extracteddiff --git a/marimo/_smoke_tests/plotly/scattermap_selection.py b/marimo/_smoke_tests/plotly/scattermap_selection.pynew file mode 100644index 0000000000..7387c58f26--- /dev/null+++ b/marimo/_smoke_tests/plotly/scattermap_selection.py@@ -0,0 +1,64 @@+import marimo++__generated_with = "0.19.5"+app = marimo.App(width="medium", auto_download=["html"])++with app.setup:+ import marimo as mo+ import pandas as pd+ import plotly.graph_objects as go+++def _():+ df_mock = pd.DataFrame(+ {+ "id": ["WC_0001", "WC_0002", "WC_0003", "WC_0004", "WC_0005"],+ "Region": ["WC", "WC", "WC", "WC", "WC"],+ "lon": [18.42, 18.46, 18.50, 18.54, 18.58],+ "lat": [-33.93, -33.95, -33.91, -33.97, -33.89],+ "cluster": [0, 1, 0, 2, 1],+ }+ )++ figg = go.Figure()++ figg.add_trace(+ go.Scattermap(+ lon=df_mock["lon"],+ lat=df_mock["lat"],+ mode="markers",+ marker=dict(size=12, color="red", opacity=0.9),+ customdata=df_mock[["id", "cluster"]].values,+ hovertemplate=(+ "<b>%{customdata[0]}</b><br>"+ "cluster: %{customdata[1]}<br>"+ "<extra></extra>"+ ),+ name="Mock sites",+ )+ )++ figg.update_layout(+ dragmode="lasso",+ map=dict(+ style="open-street-map",+ zoom=10,+ center=dict(lat=df_mock["lat"].mean(), lon=df_mock["lon"].mean()),+ ),+ margin=dict(l=0, r=0, t=0, b=0),+ )++ plot = mo.ui.plotly(figg)+ plot+ return (plot,)+++def _(plot):+ plot.value+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_plugins/ui/_impl/test_plotly.py b/tests/_plugins/ui/_impl/test_plotly.pyindex 79e4d67a2c..11062e6366 100644--- a/tests/_plugins/ui/_impl/test_plotly.py+++ b/tests/_plugins/ui/_impl/test_plotly.py@@ -2083,3 +2083,161 @@ def test_heatmap_numpy_and_fallback_numeric_axes() -> None:assert np_cell["y"] == fb_cell["y"]assert np_cell["z"] == fb_cell["z"]assert np_cell["curveNumber"] == fb_cell["curveNumber"]+++def test_scattermap_basic() -> None:+ """Test that scattermap plots can be created."""+ fig = go.Figure(+ data=go.Scattermap(+ lat=[37.7749, 34.0522],+ lon=[-122.4194, -118.2437],+ mode="markers",+ )+ )+ plot = plotly(fig)+ assert plot.value == []+++def test_scattermap_selection_with_indices() -> None:+ """Test scattermap selection extracts points by indices."""+ fig = go.Figure(+ data=go.Scattermap(+ lat=[37.7749, 34.0522, 40.7128],+ lon=[-122.4194, -118.2437, -74.0060],+ mode="markers",+ name="Cities",+ )+ )+ plot = plotly(fig)++ result = plot._convert_value({"points": [], "indices": [0, 2]})++ assert result == [+ {+ "lat": 37.7749,+ "lon": -122.4194,+ "pointIndex": 0,+ "curveNumber": 0,+ "name": "Cities",+ },+ {+ "lat": 40.7128,+ "lon": -74.0060,+ "pointIndex": 2,+ "curveNumber": 0,+ "name": "Cities",+ },+ ]+++def test_scattermap_selection_with_customdata() -> None:+ """Test scattermap selection includes customdata (issue #7970)."""+ import pandas as pd++ df = pd.DataFrame(+ {+ "id": ["WC_0001", "WC_0002", "WC_0003"],+ "lat": [-33.93, -33.95, -33.91],+ "lon": [18.42, 18.46, 18.50],+ "cluster": [0, 1, 0],+ }+ )++ fig = go.Figure(+ data=go.Scattermap(+ lat=df["lat"],+ lon=df["lon"],+ mode="markers",+ customdata=df[["id", "cluster"]].values,+ )+ )+ plot = plotly(fig)++ result = plot._convert_value({"points": [], "indices": [0]})++ assert len(result) == 1+ assert result[0]["customdata"][0] == "WC_0001"+ assert result[0]["customdata"][1] == 0+++def test_scattermapbox_selection() -> None:+ """Test scattermapbox (deprecated) selection works."""+ fig = go.Figure(+ data=go.Scattermapbox(+ lat=[37.7749, 34.0522],+ lon=[-122.4194, -118.2437],+ mode="markers",+ text=["SF", "LA"],+ )+ )+ plot = plotly(fig)++ result = plot._convert_value({"points": [], "indices": [1]})++ assert len(result) == 1+ assert result[0]["lat"] == 34.0522+ assert result[0]["text"] == "LA"+++def test_scattergeo_selection() -> None:+ """Test scattergeo selection works."""+ fig = go.Figure(+ data=go.Scattergeo(+ lat=[37.7749, 34.0522],+ lon=[-122.4194, -118.2437],+ mode="markers",+ hovertext=["SF", "LA"],+ )+ )+ plot = plotly(fig)++ result = plot._convert_value({"points": [], "indices": [0]})++ assert len(result) == 1+ assert result[0]["hovertext"] == "SF"+++def test_scattermap_preserves_frontend_points() -> None:+ """Test that existing points with lat/lon from frontend are preserved."""+ fig = go.Figure(+ data=go.Scattermap(+ lat=[37.7749],+ lon=[-122.4194],+ mode="markers",+ )+ )+ plot = plotly(fig)++ # Frontend already sent points with lat/lon+ selection = {+ "points": [{"lat": 37.7749, "lon": -122.4194, "pointIndex": 0}],+ "indices": [0],+ }++ result = plot._convert_value(selection)++ assert result == [{"lat": 37.7749, "lon": -122.4194, "pointIndex": 0}]+++def test_scattermap_empty_selection() -> None:+ """Test scattermap with empty selection."""+ fig = go.Figure(+ data=go.Scattermap(lat=[37.7749], lon=[-122.4194], mode="markers")+ )+ plot = plotly(fig)++ assert plot._convert_value({"points": [], "indices": []}) == []+++def test_scattermap_invalid_indices() -> None:+ """Test scattermap ignores invalid indices."""+ fig = go.Figure(+ data=go.Scattermap(lat=[37.7749], lon=[-122.4194], mode="markers")+ )+ plot = plotly(fig)++ # 100 and -1 are out of bounds+ result = plot._convert_value({"points": [], "indices": [0, 100, -1]})++ assert len(result) == 1+ assert result[0]["pointIndex"] == 0