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: mo.ui.altair_chart when give by the user (#2924)
Myles Scolnick6a7f8f4d5126
diff --git a/frontend/src/plugins/impl/vega/__tests__/__snapshots__/make-selectable.test.ts.snap b/frontend/src/plugins/impl/vega/__tests__/__snapshots__/make-selectable.test.ts.snapindex d0cd3fb415..91d30e16a8 100644--- a/frontend/src/plugins/impl/vega/__tests__/__snapshots__/make-selectable.test.ts.snap+++ b/frontend/src/plugins/impl/vega/__tests__/__snapshots__/make-selectable.test.ts.snap@@ -25,9 +25,6 @@ exports[`makeSelectable > should return correctly if existing legend selection 1{"param": "param_1",},- {- "param": "legend_selection_series",- },{"param": "select_point",},@@ -71,16 +68,6 @@ exports[`makeSelectable > should return correctly if existing legend selection 1"type": "point",},},- {- "bind": "legend",- "name": "legend_selection_series",- "select": {- "fields": [- "series",- ],- "type": "point",- },- },{"name": "select_point","select": {@@ -558,6 +545,401 @@ exports[`makeSelectable > should work for geoshape 1`] = `}`;+exports[`makeSelectable > should work for layered charts 1`] = `+{+ "data": {+ "name": "data-34c3e7380bd529c27667c64406db8bb8",+ },+ "datasets": {+ "data-34c3e7380bd529c27667c64406db8bb8": [+ {+ "Level1": "a",+ "count": 1,+ "stage": "france",+ },+ {+ "Level1": "b",+ "count": 2,+ "stage": "france",+ },+ {+ "Level1": "c",+ "count": 3,+ "stage": "england",+ },+ ],+ },+ "layer": [+ {+ "encoding": {+ "color": {+ "condition": {+ "field": "stage",+ "param": "param_22",+ },+ "value": "lightgray",+ },+ "x": {+ "field": "Level1",+ "sort": {+ "order": "descending",+ },+ "title": "Subpillar",+ "type": "nominal",+ },+ "y": {+ "field": "count",+ "title": "Number of Companies",+ "type": "quantitative",+ },+ },+ "mark": {+ "type": "bar",+ },+ "name": "view_21",+ "params": [+ {+ "bind": "scales",+ "name": "pan_zoom",+ "select": {+ "on": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",+ "translate": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",+ "type": "interval",+ "zoom": "wheel![event.metaKey]",+ },+ },+ ],+ },+ {+ "encoding": {+ "color": {+ "datum": "england",+ },+ "y": {+ "datum": 2,+ },+ },+ "mark": {+ "strokeDash": [+ 2,+ 2,+ ],+ "type": "rule",+ },+ },+ ],+ "params": [+ {+ "name": "param_22",+ "select": {+ "encodings": [+ "x",+ ],+ "type": "point",+ },+ "views": [+ "view_21",+ ],+ },+ ],+}+`;++exports[`makeSelectable > should work for layered charts, with existing legend selection 1`] = `+{+ "data": {+ "name": "data-34c3e7380bd529c27667c64406db8bb8",+ },+ "datasets": {+ "data-34c3e7380bd529c27667c64406db8bb8": [+ {+ "Level1": "a",+ "count": 1,+ "stage": "france",+ },+ {+ "Level1": "b",+ "count": 2,+ "stage": "france",+ },+ {+ "Level1": "c",+ "count": 3,+ "stage": "england",+ },+ ],+ },+ "layer": [+ {+ "encoding": {+ "color": {+ "condition": {+ "field": "stage",+ "param": "param_22",+ },+ "value": "lightgray",+ },+ "opacity": {+ "condition": {+ "test": {+ "and": [+ {+ "param": "select_point_0",+ },+ {+ "param": "select_interval_0",+ },+ ],+ },+ "value": 1,+ },+ "value": 0.2,+ },+ "x": {+ "field": "Level1",+ "sort": {+ "order": "descending",+ },+ "title": "Subpillar",+ "type": "nominal",+ },+ "y": {+ "field": "count",+ "title": "Number of Companies",+ "type": "quantitative",+ },+ },+ "mark": {+ "cursor": "pointer",+ "tooltip": true,+ "type": "bar",+ },+ "name": "view_21",+ "params": [+ {+ "name": "select_point_0",+ "select": {+ "encodings": [+ "x",+ ],+ "on": "click[!event.metaKey]",+ "type": "point",+ },+ },+ {+ "name": "select_interval_0",+ "select": {+ "encodings": [+ "x",+ ],+ "mark": {+ "fill": "#669EFF",+ "fillOpacity": 0.07,+ "stroke": "#669EFF",+ "strokeOpacity": 0.4,+ },+ "on": "[mousedown[!event.metaKey], mouseup] > mousemove[!event.metaKey]",+ "translate": "[mousedown[!event.metaKey], mouseup] > mousemove[!event.metaKey]",+ "type": "interval",+ },+ },+ {+ "bind": "scales",+ "name": "pan_zoom",+ "select": {+ "on": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",+ "translate": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",+ "type": "interval",+ "zoom": "wheel![event.metaKey]",+ },+ },+ ],+ },+ {+ "encoding": {+ "color": {+ "datum": "england",+ },+ "opacity": {+ "condition": {+ "test": {+ "and": [+ {+ "param": "select_point_1",+ },+ {+ "param": "select_interval_1",+ },+ ],+ },+ "value": 1,+ },+ "value": 0.2,+ },+ "y": {+ "datum": 2,+ },+ },+ "mark": {+ "cursor": "pointer",+ "strokeDash": [+ 2,+ 2,+ ],+ "tooltip": true,+ "type": "rule",+ },+ "params": [+ {+ "name": "select_point_1",+ "select": {+ "encodings": [+ "x",+ "y",+ ],+ "on": "click[!event.metaKey]",+ "type": "point",+ },+ },+ {+ "name": "select_interval_1",+ "select": {+ "encodings": [+ "x",+ "y",+ ],+ "mark": {+ "fill": "#669EFF",+ "fillOpacity": 0.07,+ "stroke": "#669EFF",+ "strokeOpacity": 0.4,+ },+ "on": "[mousedown[!event.metaKey], mouseup] > mousemove[!event.metaKey]",+ "translate": "[mousedown[!event.metaKey], mouseup] > mousemove[!event.metaKey]",+ "type": "interval",+ },+ },+ ],+ },+ ],+ "params": [+ {+ "bind": "legend",+ "name": "param_22",+ "select": {+ "fields": [+ "x",+ ],+ "type": "point",+ },+ "views": [+ "view_21",+ ],+ },+ ],+}+`;++exports[`makeSelectable > should work for layered charts, with existing selection 1`] = `+{+ "data": {+ "name": "data-34c3e7380bd529c27667c64406db8bb8",+ },+ "datasets": {+ "data-34c3e7380bd529c27667c64406db8bb8": [+ {+ "Level1": "a",+ "count": 1,+ "stage": "france",+ },+ {+ "Level1": "b",+ "count": 2,+ "stage": "france",+ },+ {+ "Level1": "c",+ "count": 3,+ "stage": "england",+ },+ ],+ },+ "layer": [+ {+ "encoding": {+ "color": {+ "condition": {+ "field": "stage",+ "param": "param_22",+ },+ "value": "lightgray",+ },+ "x": {+ "field": "Level1",+ "sort": {+ "order": "descending",+ },+ "title": "Subpillar",+ "type": "nominal",+ },+ "y": {+ "field": "count",+ "title": "Number of Companies",+ "type": "quantitative",+ },+ },+ "mark": {+ "type": "bar",+ },+ "name": "view_21",+ "params": [+ {+ "bind": "scales",+ "name": "pan_zoom",+ "select": {+ "on": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",+ "translate": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",+ "type": "interval",+ "zoom": "wheel![event.metaKey]",+ },+ },+ ],+ },+ {+ "encoding": {+ "color": {+ "datum": "england",+ },+ "y": {+ "datum": 2,+ },+ },+ "mark": {+ "strokeDash": [+ 2,+ 2,+ ],+ "type": "rule",+ },+ },+ ],+ "params": [+ {+ "name": "param_22",+ "select": {+ "encodings": [+ "x",+ ],+ "type": "point",+ },+ "views": [+ "view_21",+ ],+ },+ ],+}+`;+exports[`makeSelectable > should work for multi-layered charts 1`] = `{"data": {diff --git a/frontend/src/plugins/impl/vega/__tests__/make-selectable.test.ts b/frontend/src/plugins/impl/vega/__tests__/make-selectable.test.tsindex fc263187d1..09154de417 100644--- a/frontend/src/plugins/impl/vega/__tests__/make-selectable.test.ts+++ b/frontend/src/plugins/impl/vega/__tests__/make-selectable.test.ts@@ -215,7 +215,6 @@ describe("makeSelectable", () => {expect(newSpec).toMatchSnapshot();expect(getSelectionParamNames(newSpec)).toEqual(["param_1",- "legend_selection_series","select_point","pan_zoom",]);@@ -380,4 +379,181 @@ describe("makeSelectable", () => {expect(newSpec).toMatchSnapshot();expect(getSelectionParamNames(newSpec)).toEqual([]);});++ it("should work for layered charts, with existing selection", () => {+ const spec = {+ data: {+ name: "data-34c3e7380bd529c27667c64406db8bb8",+ },+ datasets: {+ "data-34c3e7380bd529c27667c64406db8bb8": [+ {+ Level1: "a",+ count: 1,+ stage: "france",+ },+ {+ Level1: "b",+ count: 2,+ stage: "france",+ },+ {+ Level1: "c",+ count: 3,+ stage: "england",+ },+ ],+ },+ layer: [+ {+ encoding: {+ color: {+ condition: {+ field: "stage",+ param: "param_22",+ },+ value: "lightgray",+ },+ x: {+ field: "Level1",+ sort: {+ order: "descending",+ },+ title: "Subpillar",+ type: "nominal",+ },+ y: {+ field: "count",+ title: "Number of Companies",+ type: "quantitative",+ },+ },+ mark: {+ type: "bar",+ },+ name: "view_21",+ },+ {+ encoding: {+ color: {+ datum: "england",+ },+ y: {+ datum: 2,+ },+ },+ mark: {+ strokeDash: [2, 2],+ type: "rule",+ },+ },+ ],+ params: [+ {+ name: "param_22",+ select: {+ encodings: ["x"],+ type: "point",+ },+ views: ["view_21"],+ },+ ],+ } as VegaLiteSpec;+ const newSpec = makeSelectable(spec, {});+ expect(newSpec).toMatchSnapshot();+ expect(getSelectionParamNames(newSpec)).toMatchInlineSnapshot(`+ [+ "param_22",+ ]+ `);+ });++ it("should work for layered charts, with existing legend selection", () => {+ const spec = {+ data: {+ name: "data-34c3e7380bd529c27667c64406db8bb8",+ },+ datasets: {+ "data-34c3e7380bd529c27667c64406db8bb8": [+ {+ Level1: "a",+ count: 1,+ stage: "france",+ },+ {+ Level1: "b",+ count: 2,+ stage: "france",+ },+ {+ Level1: "c",+ count: 3,+ stage: "england",+ },+ ],+ },+ layer: [+ {+ encoding: {+ color: {+ condition: {+ field: "stage",+ param: "param_22",+ },+ value: "lightgray",+ },+ x: {+ field: "Level1",+ sort: {+ order: "descending",+ },+ title: "Subpillar",+ type: "nominal",+ },+ y: {+ field: "count",+ title: "Number of Companies",+ type: "quantitative",+ },+ },+ mark: {+ type: "bar",+ },+ name: "view_21",+ },+ {+ encoding: {+ color: {+ datum: "england",+ },+ y: {+ datum: 2,+ },+ },+ mark: {+ strokeDash: [2, 2],+ type: "rule",+ },+ },+ ],+ params: [+ {+ name: "param_22",+ bind: "legend",+ select: {+ fields: ["x"],+ type: "point",+ },+ views: ["view_21"],+ },+ ],+ } as VegaLiteSpec;+ const newSpec = makeSelectable(spec, {});+ expect(newSpec).toMatchSnapshot();+ expect(getSelectionParamNames(newSpec)).toMatchInlineSnapshot(`+ [+ "param_22",+ ]+ `);+ });});diff --git a/frontend/src/plugins/impl/vega/make-selectable.ts b/frontend/src/plugins/impl/vega/make-selectable.tsindex 919d9eb465..2bec778241 100644--- a/frontend/src/plugins/impl/vega/make-selectable.ts+++ b/frontend/src/plugins/impl/vega/make-selectable.ts@@ -18,13 +18,23 @@ export function makeSelectable<T extends VegaLiteSpec>(},): T {// Both default to true- const { chartSelection = true, fieldSelection = true } = opts;+ let { chartSelection = true, fieldSelection = true } = opts;// Disable selection if both are falseif (!chartSelection && !fieldSelection) {return spec;}+ // If params already exist, we don't add any more+ const hasLegendParam = spec.params?.some((param) => param.bind === "legend");+ if (hasLegendParam) {+ fieldSelection = false;+ }+ const hasChartParam = spec.params?.some((param) => !param.bind);+ if (hasChartParam) {+ chartSelection = false;+ }+if ("vconcat" in spec) {const subSpecs = spec.vconcat.map((subSpec) =>"mark" in subSpec ? makeChartInteractive(subSpec) : subSpec,diff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.pyindex 2e2bec0741..523caddb2d 100644--- a/marimo/_plugins/ui/_impl/altair_chart.py+++ b/marimo/_plugins/ui/_impl/altair_chart.py@@ -242,10 +242,12 @@ class altair_chart(UIElement[ChartSelection, ChartDataType]):- `chart`: An `altair.Chart`- `chart_selection`: optional selection type,`"point"`, `"interval"`, or a bool; defaults to `True` which will- automatically detect the best selection type+ automatically detect the best selection type.+ This is ignored if the chart already has a point/interval selection param.- `legend_selection`: optional list of legend fields (columns) for which toenable selection, `True` to enable selection for all fields, or- `False` to disable selection entirely+ `False` to disable selection entirely.+ This is ignored if the chart already has a legend selection param.- `label`: optional markdown label for the element- `on_change`: optional callback to run when this element's value changes"""@@ -299,6 +301,30 @@ class altair_chart(UIElement[ChartSelection, ChartDataType]):if legend_selection is None: # type: ignorelegend_selection = False+ # If the chart already has a selection param,+ # we don't add any more+ if _has_selection_param(chart):+ # Log a warning if the user has set chart_selection+ # but the chart already has a selection param+ if isinstance(chart_selection, str):+ sys.stderr.write(+ f"Warning: chart already has a selection param. "+ f"Ignoring chart_selection={chart_selection}"+ )+ chart_selection = False+ if _has_legend_param(chart):+ # Log a warning if the user has set legend_selection+ # but the chart already has a legend param+ if (+ isinstance(legend_selection, list)+ and len(legend_selection) > 0+ ):+ sys.stderr.write(+ f"Warning: chart already has a legend param. "+ f"Ignoring legend_selection={legend_selection}"+ )+ legend_selection = False+# Selection for binned charts is not yet implementedhas_chart_selection = chart_selection is not Falsehas_legend_selection = legend_selection is not False@@ -523,3 +549,41 @@ def maybe_make_full_width(chart: altair.Chart) -> altair.Chart:"This is likely due to a missing dependency or an invalid chart.")return chart+++def _has_selection_param(chart: altair.Chart) -> bool:+ import altair as alt++ try:+ for param in chart.params:+ try:+ if isinstance(+ param,+ (alt.SelectionParameter, alt.TopLevelSelectionParameter),+ ):+ if param.bind is alt.Undefined:+ return True+ except Exception:+ pass+ except Exception:+ pass+ return False+++def _has_legend_param(chart: altair.Chart) -> bool:+ import altair as alt++ try:+ for param in chart.params:+ try:+ if isinstance(+ param,+ (alt.SelectionParameter, alt.TopLevelSelectionParameter),+ ):+ if param.bind == "legend":+ return True+ except Exception:+ pass+ except Exception:+ pass+ return Falsediff --git a/marimo/_smoke_tests/altair/layered_charts.py b/marimo/_smoke_tests/altair/layered_charts.pynew file mode 100644index 0000000000..2744d336d4--- /dev/null+++ b/marimo/_smoke_tests/altair/layered_charts.py@@ -0,0 +1,81 @@+import marimo++__generated_with = "0.9.21"+app = marimo.App(width="medium")+++def __():+ import marimo as mo+ import altair as alt+ import pandas as pd++ # data+ test_counts = pd.DataFrame(+ [+ {"Level1": "a", "count": 1, "stage": "france"},+ {"Level1": "b", "count": 2, "stage": "france"},+ {"Level1": "c", "count": 3, "stage": "england"},+ ]+ )+ return alt, mo, pd, test_counts+++def __(mo):+ mo.md(r"""## Layered""")+ return+++def __(alt, mo, test_counts):+ # Base+ _base = alt.Chart(test_counts)++ # Params+ _point = alt.selection_point(encodings=["x"])+ _brush = alt.selection_interval(encodings=["x"])++ # Chart 1+ chart = (+ _base.mark_bar()+ .encode(+ x=alt.X("Level1").sort(order="descending").title("Subpillar"),+ y=alt.Y("count").title("Number of Companies"),+ color=alt.condition(_point, "stage", alt.value("lightgray")),+ )+ .add_params(_point, _brush)+ )++ # Chart 2+ rule = _base.mark_rule(strokeDash=[2, 2]).encode(+ y=alt.datum(2), color=alt.datum("england")+ )++ # Layered+ layered_chart = mo.ui.altair_chart(alt.layer(chart, rule))+ layered_chart+ return chart, layered_chart, rule+++def __(layered_chart):+ layered_chart.value+ return+++def __(mo):+ mo.md(r"""## Warnings""")+ return+++def __(alt, chart, mo, rule):+ mo.ui.altair_chart(alt.layer(chart, rule), chart_selection="point")+ None+ 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 e75400c322..135747c289 100644--- a/tests/_plugins/ui/_impl/test_altair_chart.py+++ b/tests/_plugins/ui/_impl/test_altair_chart.py@@ -11,14 +11,16 @@ import narwhals.stable.v1 as nwimport pytestfrom marimo._dependencies.dependencies import DependencyManager-from marimo._plugins.ui._impl import altair_chartfrom marimo._plugins.ui._impl.altair_chart import (ChartDataType,ChartSelection,_filter_dataframe,_has_binning,_has_geoshape,+ _has_legend_param,+ _has_selection_param,_parse_spec,+ altair_chart,)from marimo._runtime.runtime import Kernelfrom tests._data.mocks import create_dataframes@@ -202,9 +204,7 @@ class TestAltairChart:# smoke test; this shouldn't error, even though it's larger than# altair's default of 5000 data points.df = pd.DataFrame({"a": [10000], "b": [10000]})- altair_chart.altair_chart(- alt.Chart(df).mark_circle().encode(x="a", y="b")- )+ altair_chart(alt.Chart(df).mark_circle().encode(x="a", y="b"))@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")@@ -215,10 +215,8 @@ def test_can_add_altair_chart() -> None:unwrapped = (alt.Chart(data).mark_point().encode(x="values:Q").properties(width=200))- chart1 = altair_chart.altair_chart(unwrapped)- chart2 = altair_chart.altair_chart(- alt.Chart(data).mark_bar().encode(x="values:Q")- )+ chart1 = altair_chart(unwrapped)+ chart2 = altair_chart(alt.Chart(data).mark_bar().encode(x="values:Q"))assert chart1 + chart2 is not Noneassert chart2 + chart1 is not None@@ -235,10 +233,8 @@ def test_can_or_altair_chart() -> None:unwrapped = (alt.Chart(data).mark_point().encode(x="values:Q").properties(width=200))- chart1 = altair_chart.altair_chart(unwrapped)- chart2 = altair_chart.altair_chart(- alt.Chart(data).mark_bar().encode(x="values:Q")- )+ chart1 = altair_chart(unwrapped)+ chart2 = altair_chart(alt.Chart(data).mark_bar().encode(x="values:Q"))assert chart1 | chart2 is not Noneassert chart2 | chart1 is not None@@ -255,10 +251,8 @@ def test_can_and_altair_chart() -> None:unwrapped = (alt.Chart(data).mark_point().encode(x="values:Q").properties(width=200))- chart1 = altair_chart.altair_chart(unwrapped)- chart2 = altair_chart.altair_chart(- alt.Chart(data).mark_bar().encode(x="values:Q")- )+ chart1 = altair_chart(unwrapped)+ chart2 = altair_chart(alt.Chart(data).mark_bar().encode(x="values:Q"))assert chart1 & chart2 is not Noneassert chart2 & chart1 is not None@@ -277,9 +271,7 @@ def test_does_not_modify_original() -> None:)alt2 = alt.Chart(data).mark_bar().encode(x="values:Q").properties()combined1 = alt1 | alt2- combined2 = altair_chart.altair_chart(alt1) | altair_chart.altair_chart(- alt2- )+ combined2 = altair_chart(alt1) | altair_chart(alt2)assert combined1 == combined2._chart@@ -289,9 +281,7 @@ def test_get_dataframe() -> None:import altair as altdata = {"values": [1, 2, 3]}- chart = altair_chart.altair_chart(- alt.Chart(data).mark_point().encode(x="values:Q")- )+ chart = altair_chart(alt.Chart(data).mark_point().encode(x="values:Q"))assert chart.dataframe == data@@ -302,9 +292,7 @@ def test_get_dataframe_csv() -> None:import polars as pldata = "https://cdn.jsdelivr.net/npm/[email protected]/data/stocks.csv"- chart = altair_chart.altair_chart(- alt.Chart(data).mark_point().encode(x="values:Q")- )+ chart = altair_chart(alt.Chart(data).mark_point().encode(x="values:Q"))assert isinstance(chart.dataframe, (pd.DataFrame, pl.DataFrame))@@ -317,9 +305,7 @@ def test_get_dataframe_json() -> None:data = ("https://cdn.jsdelivr.net/npm/[email protected]/data/barley.json")- chart = altair_chart.altair_chart(- alt.Chart(data).mark_point().encode(x="values:Q")- )+ chart = altair_chart(alt.Chart(data).mark_point().encode(x="values:Q"))assert isinstance(chart.dataframe, (pd.DataFrame, pl.DataFrame))@@ -394,9 +380,7 @@ def test_no_selection_pandas() -> None:import pandas as pddata = pd.DataFrame({"values": [1, 2, 3]})- chart = altair_chart.altair_chart(- alt.Chart(data).mark_point().encode(x="values:Q")- )+ chart = altair_chart(alt.Chart(data).mark_point().encode(x="values:Q"))assert isinstance(chart._value, pd.DataFrame)assert len(chart._value) == 0selected_value = chart._convert_value({})@@ -411,9 +395,7 @@ def test_no_selection_polars() -> None:import polars as pldata = pl.DataFrame({"values": [1, 2, 3]})- chart = altair_chart.altair_chart(- alt.Chart(data).mark_point().encode(x="values:Q")- )+ chart = altair_chart(alt.Chart(data).mark_point().encode(x="values:Q"))assert isinstance(chart._value, pl.DataFrame)assert len(chart._value) == 0selected_value = chart._convert_value({})@@ -437,7 +419,7 @@ def test_layered_chart(df: IntoDataFrame):chart2 = base.mark_line().encode(y="y2")layered = alt.layer(chart1, chart2)- marimo_chart = altair_chart.altair_chart(layered)+ marimo_chart = altair_chart(layered)assert isinstance(marimo_chart._chart, alt.LayerChart)assert marimo_chart.dataframe is not None@@ -456,7 +438,7 @@ def test_chart_with_binning(df: IntoDataFrame):.encode(x=alt.X("values", bin=True), y="count()"))- marimo_chart = altair_chart.altair_chart(chart)+ marimo_chart = altair_chart(chart)assert _has_binning(marimo_chart._spec)# Test that selection is disabled for binned chartsassert marimo_chart._component_args["chart-selection"] is False@@ -479,7 +461,7 @@ def test_apply_selection(df: IntoDataFrame):chart = alt.Chart(df).mark_point().encode(x="x", y="y", color="category")- marimo_chart = altair_chart.altair_chart(chart)+ marimo_chart = altair_chart(chart)marimo_chart._chart_selection = {"signal_channel": {"category": ["A"]}}filtered_data = marimo_chart.apply_selection(df)@@ -499,7 +481,7 @@ def test_chart_with_url_data():.encode(x="Horsepower:Q", y="Miles_per_Gallon:Q"))- marimo_chart = altair_chart.altair_chart(chart)+ marimo_chart = altair_chart(chart)assert isinstance(marimo_chart.dataframe, pl.DataFrame)assert len(marimo_chart.dataframe) > 0@@ -515,17 +497,89 @@ def test_chart_operations(df: IntoDataFrame):chart1 = alt.Chart(df).mark_point().encode(x="x", y="y")chart2 = alt.Chart(df).mark_line().encode(x="x", y="y")- marimo_chart1 = altair_chart.altair_chart(chart1)- marimo_chart2 = altair_chart.altair_chart(chart2)+ marimo_chart1 = altair_chart(chart1)+ marimo_chart2 = altair_chart(chart2)combined_chart = marimo_chart1 + marimo_chart2- assert isinstance(combined_chart, altair_chart.altair_chart)+ assert isinstance(combined_chart, altair_chart)assert isinstance(combined_chart._chart, alt.LayerChart)concat_chart = marimo_chart1 | marimo_chart2- assert isinstance(concat_chart, altair_chart.altair_chart)+ assert isinstance(concat_chart, altair_chart)assert isinstance(concat_chart._chart, alt.HConcatChart)facet_chart = marimo_chart1 & marimo_chart2- assert isinstance(facet_chart, altair_chart.altair_chart)+ assert isinstance(facet_chart, altair_chart)assert isinstance(facet_chart._chart, alt.VConcatChart)++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+def test_has_selection_param() -> None:+ import altair as alt++ # Chart with no selection param+ chart = alt.Chart().mark_point()+ assert _has_selection_param(chart) is False++ # Chart with selection param but bound to input+ chart = (+ alt.Chart()+ .mark_point()+ .add_params(+ alt.selection_point(+ name="my_selection", encodings=["x"], bind="legend"+ )+ )+ )+ assert _has_selection_param(chart) is False++ # Chart with unbound selection param+ chart = (+ alt.Chart()+ .mark_point()+ .add_params(alt.selection_point(name="my_selection"))+ )+ assert chart.params[0].bind is alt.Undefined+ assert _has_selection_param(chart) is True++ # Layer chart+ rule = alt.Chart().mark_rule(strokeDash=[2, 2]).encode(y=alt.datum(2))+ layered = alt.layer(chart, rule)+ assert _has_selection_param(layered) is True++ # Invalid chart+ chart = None+ assert _has_selection_param(chart) is False++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+def test_has_legend_param() -> None:+ import altair as alt++ # Chart with no legend param+ chart = alt.Chart().mark_point()+ assert _has_legend_param(chart) is False++ # Chart with legend binding+ chart = (+ alt.Chart()+ .mark_point()+ .add_params(alt.selection_point(fields=["color"], bind="legend"))+ )+ assert _has_legend_param(chart) is True++ # Layer chart+ rule = alt.Chart().mark_rule(strokeDash=[2, 2]).encode(y=alt.datum(2))+ layered = alt.layer(chart, rule)+ assert _has_legend_param(layered) is True++ # Chart with non-legend binding+ chart = alt.Chart().mark_point().add_params(alt.selection_point())+ assert _has_legend_param(chart) is False++ layered = alt.layer(chart, rule)+ assert _has_legend_param(layered) is False++ # Invalid chart+ chart = None+ assert _has_legend_param(chart) is False