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
fix: support altair map selection when vconcat or hconcat (#3590)
Myles Scolnickb3d83d958c73
diff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.pyindex d7955519e6..7e5e3e01b6 100644--- a/marimo/_plugins/ui/_impl/altair_chart.py+++ b/marimo/_plugins/ui/_impl/altair_chart.py@@ -67,6 +67,13 @@ def _has_geoshape(spec: altair.TopLevelMixin) -> bool:"""Return True if the spec has geoshape."""try:if not hasattr(spec, "mark"):+ # Check for nested layers, vconcat, hconcat+ if hasattr(spec, "layer"):+ return any(_has_geoshape(layer) for layer in spec.layer)+ if hasattr(spec, "vconcat"):+ return any(_has_geoshape(layer) for layer in spec.vconcat)+ if hasattr(spec, "hconcat"):+ return any(_has_geoshape(layer) for layer in spec.hconcat)return Falsemark = spec.mark # type: ignorereturn mark == "geoshape" or mark.type == "geoshape" # type: ignore@@ -95,13 +102,16 @@ def _filter_dataframe(# and instead passes an individual selected point.if len(fields) == 2 and "vlPoint" in fields and "_vgsid_" in fields:# Vega is 1-indexed, so subtract 1+ vgsid = fields.get("_vgsid_", [])try:- indexes = [int(i) - 1 for i in fields["_vgsid_"]]+ indexes = [int(i) - 1 for i in vgsid]df = cast(nw.DataFrame[Any], df)[indexes]- except (ValueError, IndexError) as e:- raise ValueError(- f"Invalid index in selection: {fields['_vgsid_']}"- ) from e+ except IndexError:+ # Out of bounds index, return empty dataframe if it's the+ df = cast(nw.DataFrame[Any], df)[[]]+ LOGGER.error(f"Invalid index in selection: {vgsid}")+ except ValueError:+ LOGGER.error(f"Invalid index in selection: {vgsid}")continue# If vlPoint is in the selection,diff --git a/marimo/_smoke_tests/altair/map_selection.py b/marimo/_smoke_tests/altair/map_selection.pynew file mode 100644index 0000000000..8d41dd6e29--- /dev/null+++ b/marimo/_smoke_tests/altair/map_selection.py@@ -0,0 +1,267 @@+import marimo++__generated_with = "0.10.17"+app = marimo.App(width="columns")++[email protected](column=0, hide_code=True)+def _(mo):+ mo.md(r"""# Selections with altair maps""")+ return++[email protected](hide_code=True)+def _():+ import altair as alt+ from vega_datasets import data+ import geopandas as gpd+ return alt, data, gpd++[email protected](hide_code=True)+def _(mo):+ mo.md("""## Load the data""")+ return++[email protected](hide_code=True)+def _(data, gpd):+ # load the data+ us_states = gpd.read_file(data.us_10m.url, driver="TopoJSON", layer="states")+ us_population = data.population_engineers_hurricanes()[+ ["state", "id", "population"]+ ]++ gdf_quakies = gpd.read_file(data.earthquakes.url, driver="GeoJSON")+ gdf_world = gpd.read_file(data.world_110m.url, driver="TopoJSON")+ return gdf_quakies, gdf_world, us_population, us_states++[email protected](column=1, hide_code=True)+def _(mo):+ mo.md(+ r"""+ ## Example 1: Population map++ https://altair-viz.github.io/user_guide/marks/geoshape.html#interactions+ """+ )+ return++[email protected](hide_code=True)+def _(alt, us_population, us_states):+ def population_map():+ # define a pointer selection+ click_state = alt.selection_point(fields=["state"])+ # define a condition on the opacity encoding depending on the selection+ opacity = alt.when(click_state).then(alt.value(1)).otherwise(alt.value(0.2))++ # create a choropleth map using a lookup transform+ choropleth = (+ alt.Chart(us_states)+ .mark_geoshape()+ .transform_lookup(+ lookup="id",+ from_=alt.LookupData(us_population, "id", ["population", "state"]),+ )+ .encode(+ color="population:Q",+ opacity=opacity,+ tooltip=["state:N", "population:Q"],+ )+ .project(type="albersUsa")+ )++ # create a bar chart with the same conditional ``opacity`` encoding.+ bars = (+ alt.Chart(+ us_population.nlargest(15, "population"),+ title="Top 15 states by population",+ )+ .mark_bar()+ .encode(+ x="population",+ opacity=opacity,+ color="population",+ y=alt.Y("state").sort("-x"),+ )+ )++ return (choropleth & bars).add_params(click_state)+ return (population_map,)++[email protected](hide_code=True)+def _(mo):+ mo.md("""### Without `mo.ui.altair_chart`""")+ return+++def _(population_map):+ population_map()+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""### With `mo.ui.altair_chart`""")+ return+++def _(mo, population_map):+ chart = mo.ui.altair_chart(population_map())+ chart+ return (chart,)++[email protected](hide_code=True)+def _(mo):+ mo.md("""Selecting the bar chart or map should filter the table below""")+ return+++def _(chart, mo, us_population):+ mo.hstack([chart.selections, chart.apply_selection(us_population)])+ return+++def _():+ return+++def _():+ import marimo as mo+ return (mo,)+++def _():+ return++[email protected](column=2)+def _(mo):+ mo.md("""## Example 2: """)+ return++[email protected](hide_code=True)+def _(alt, gdf_quakies, gdf_world):+ def world_map():+ # define parameters+ range0 = alt.binding_range(+ min=-180, max=180, step=5, name="rotate longitude "+ )+ rotate0 = alt.param(value=120, bind=range0)+ hover = alt.selection_point(on="pointerover", clear="pointerout")++ # world disk+ sphere = alt.Chart(alt.sphere()).mark_geoshape(+ fill="aliceblue", stroke="black", strokeWidth=1.5+ )++ # countries as shapes+ world = alt.Chart(gdf_world).mark_geoshape(+ fill="mintcream", stroke="black", strokeWidth=0.35+ )++ # earthquakes as circles with fill for depth and size for magnitude+ # the hover param is added on the mar_circle only+ quakes = (+ alt.Chart(gdf_quakies)+ .mark_circle(opacity=0.35, tooltip=True, stroke="black")+ .transform_calculate(+ lon="datum.geometry.coordinates[0]",+ lat="datum.geometry.coordinates[1]",+ depth="datum.geometry.coordinates[2]",+ )+ .transform_filter(+ (+ (rotate0 * -1 - 90 < alt.datum.lon)+ & (alt.datum.lon < rotate0 * -1 + 90)+ ).expr+ )+ .encode(+ longitude="lon:Q",+ latitude="lat:Q",+ strokeWidth=alt.when(hover, empty=False)+ .then(alt.value(1))+ .otherwise(alt.value(0)),+ size=alt.Size(+ "mag:Q",+ scale=alt.Scale(+ type="pow", range=[1, 1000], domain=[0, 6], exponent=4+ ),+ ),+ fill=alt.Fill(+ "depth:Q",+ scale=alt.Scale(scheme="lightorange", domain=[0, 400]),+ ),+ )+ .add_params(hover, rotate0)+ )++ # define projection and add the rotation param for all layers+ comb = alt.layer(sphere, world, quakes).project(+ type="orthographic", rotate=alt.expr(f"[{rotate0.name}, 0, 0]")+ )+ return comb+ return (world_map,)++[email protected](hide_code=True)+def _(mo):+ mo.md("""### Without `mo.ui.altair_chart`""")+ return+++def _(world_map):+ world_map()+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""### With `mo.ui.altair_chart`""")+ return+++def _(mo, world_map):+ world = mo.ui.altair_chart(world_map())+ world+ return (world,)++[email protected](hide_code=True)+def _(mo):+ mo.md("""Hovering over an element on the map should filter the table below.""")+ return+++def _(world):+ str(world.selections)+ return+++def _(gdf_quakies, gdf_world, mo, world):+ mo.hstack(+ [+ world.apply_selection(gdf_quakies)["title"],+ world.apply_selection(gdf_world)["id"],+ ]+ )+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_plugins/ui/_impl/test_altair_chart.py b/tests/_plugins/ui/_impl/test_altair_chart.pyindex d3161dd890..f0ae21eed8 100644--- a/tests/_plugins/ui/_impl/test_altair_chart.py+++ b/tests/_plugins/ui/_impl/test_altair_chart.py@@ -705,6 +705,27 @@ def test_has_geoshape() -> None:chart_without_geoshape = alt.Chart().mark_bar()assert _has_geoshape(chart_without_geoshape) is False+ # Test nested charts+ nested_layer = alt.layer(+ alt.Chart().mark_bar(), alt.Chart().mark_geoshape()+ )+ assert _has_geoshape(nested_layer) is True++ nested_vconcat = alt.vconcat(+ alt.Chart().mark_bar(), alt.Chart().mark_geoshape()+ )+ assert _has_geoshape(nested_vconcat) is True++ nested_hconcat = alt.hconcat(+ alt.Chart().mark_bar(), alt.Chart().mark_geoshape()+ )+ assert _has_geoshape(nested_hconcat) is True++ all_non_geoshape = alt.layer(+ alt.Chart().mark_bar(), alt.Chart().mark_line()+ )+ assert _has_geoshape(all_non_geoshape) is False+@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")def test_no_selection_pandas() -> None: