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
improvement: support operators on mo.ui.altair, improve docs for custom selection (#1814)
Myles Scolnick6a2e720e0290
diff --git a/docs/api/plotting.md b/docs/api/plotting.mdindex e9855ef0f5..7e9bc23bf3 100644--- a/docs/api/plotting.md+++ b/docs/api/plotting.md@@ -41,6 +41,30 @@ For more information about plotting, see the [plotting guide](../guides/plottingreturn```+### Disabling automatic selection++marimo automatically adds a default selection based on the mark type, however, you may want to customize the selection behavior of your Altair chart. You can do this by setting `chart_selection` and `legend_selection` to `False`, and using `.add_params` directly on your Altair chart.++```python+# Create an interval selection+brush = alt.selection_interval(encodings=["x"])++_chart = (+ alt.Chart(traces, height=150)+ .mark_line()+ .encode(x="index:Q", y="value:Q", color="traces:N")+ .add_params(brush) # add the selection to the chart+)++chart = mo.ui.altair_chart(+ _chart,+ # disable automatic selection+ chart_selection=False,+ legend_selection=False+)+chart # You can now access chart.value to get the selected data+```+```{eval-rst}.. autofunction:: marimo.ui.altair_chart```diff --git a/docs/guides/plotting.md b/docs/guides/plotting.mdindex e5b63b04f1..f9c0fcbd47 100644--- a/docs/guides/plotting.md+++ b/docs/guides/plotting.md@@ -76,6 +76,30 @@ Wrap an Altair chart in [`mo.ui.altair_chart`](../api/plotting.md#marimo.ui.altato make it **reactive**: select data on the frontend, access it via the chart's`value` attribute (`chart.value`).+#### Disabling automatic selection++marimo automatically adds a default selection based on the mark type, however, you may want to customize the selection behavior of your Altair chart. You can do this by setting `chart_selection` and `legend_selection` to `False`, and using `.add_params` directly on your Altair chart.++```python+# Create an interval selection+brush = alt.selection_interval(encodings=["x"])++_chart = (+ alt.Chart(traces, height=150)+ .mark_line()+ .encode(x="index:Q", y="value:Q", color="traces:N")+ .add_params(brush) # add the selection to the chart+)++chart = mo.ui.altair_chart(+ _chart,+ # disable automatic selection+ chart_selection=False,+ legend_selection=False+)+chart # You can now access chart.value to get the selected data+```+_Reactive plots are just one way that marimo **makes your data tangible**._#### Examplediff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.pyindex 9347e82b04..2e42e85a02 100644--- a/marimo/_plugins/ui/_impl/altair_chart.py+++ b/marimo/_plugins/ui/_impl/altair_chart.py@@ -203,6 +203,8 @@ class altair_chart(UIElement[ChartSelection, "pd.DataFrame"]):register_transformers()+ self._chart = chart+if not isinstance(chart, (alt.TopLevelMixin)):raise ValueError("Invalid type for chart: "@@ -230,6 +232,13 @@ class altair_chart(UIElement[ChartSelection, "pd.DataFrame"]):if "autosize" not in vega_spec:vega_spec["autosize"] = "fit-x"+ # Types say this is not possible,+ # but a user still may pass none+ if chart_selection is None: # type: ignore+ chart_selection = False+ if legend_selection is None: # type: ignore+ 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@@ -247,8 +256,6 @@ class altair_chart(UIElement[ChartSelection, "pd.DataFrame"]):self.dataframe: alt.UndefinedType | pd.DataFrame = chart.data- # Private attributes- self._chart = chartself._spec = vega_specsuper().__init__(@@ -342,6 +349,35 @@ class altair_chart(UIElement[ChartSelection, "pd.DataFrame"]):"""return _filter_dataframe(df, self.selections)+ # Proxy all of altair's attributes+ def __getattr__(self, name: str) -> Any:+ return getattr(self._chart, name)++ def __add__(self, other: Any) -> Any:+ if isinstance(other, altair_chart):+ other = other._chart+ return altair_chart(self._chart + other)++ def __or__(self, value: Any) -> Any:+ if isinstance(value, altair_chart):+ value = value._chart+ return altair_chart(self._chart | value)++ def __radd__(self, other: Any) -> Any:+ if isinstance(other, altair_chart):+ other = other._chart+ return altair_chart(other + self._chart)++ def __ror__(self, value: Any) -> Any:+ if isinstance(value, altair_chart):+ value = value._chart+ return altair_chart(value | self._chart)++ def __and__(self, value: Any) -> Any:+ if isinstance(value, altair_chart):+ value = value._chart+ return altair_chart(self._chart & value)+@propertydef value(self) -> pd.DataFrame:from altair import UndefinedTypediff --git a/marimo/_smoke_tests/altair/altair_brush.py b/marimo/_smoke_tests/altair/altair_brush.pynew file mode 100644index 0000000000..9580c00337--- /dev/null+++ b/marimo/_smoke_tests/altair/altair_brush.py@@ -0,0 +1,111 @@+import marimo++__generated_with = "0.7.5"+app = marimo.App(width="medium")+++def __(mo):+ mo.md(r"## Data")+ return+++def __():+ import pandas as pd+ import numpy as np+ import altair as alt+ import marimo as mo+++ data = {+ "index": np.tile(np.arange(100), 3),+ "value": np.random.randn(300),+ "traces": np.repeat(["Trace 1", "Trace 2", "Trace 3"], 100),+ }++ traces = pd.DataFrame(data)++ print(traces.head())+ return alt, data, mo, np, pd, traces+++def __(mo):+ mo.md(r"## Plain Altair")+ return+++def __(alt, traces):+ _brush = alt.selection_interval(encodings=["x"])++ _chart_overview = (+ alt.Chart(traces, height=150, width=550)+ .mark_line()+ .encode(x="index:Q", y="value:Q", color="traces:N")+ .add_params(_brush)+ )++ _chart_detail = (+ alt.Chart(traces)+ .mark_line()+ .encode(x="index:Q", y="value:Q", color="traces:N")+ .transform_filter(_brush)+ )++ _chart_overview | _chart_detail+ return+++def __(mo):+ mo.md(r"## Example of the Or ( | ) operator")+ return+++def __(alt, mo, traces):+ _brush = alt.selection_interval(encodings=["x"])++ chart_overview = mo.ui.altair_chart(+ alt.Chart(traces, height=150, width=550)+ .mark_line()+ .encode(x="index:Q", y="value:Q", color="traces:N")+ .add_params(_brush),+ chart_selection=False,+ legend_selection=False,+ )++ chart_detail = mo.ui.altair_chart(+ alt.Chart(traces)+ .mark_line()+ .encode(x="index:Q", y="value:Q", color="traces:N")+ .transform_filter(_brush),+ )++ chart_overview | chart_detail+ return chart_detail, chart_overview+++def __(mo):+ mo.md(r"## Example of the Or ( | ) operator with selection")+ return+++def __(chart_detail, chart_overview):+ combined = chart_overview | chart_detail+ combined+ return combined,+++def __(combined):+ combined.value+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_smoke_tests/altair_charts.py b/marimo/_smoke_tests/altair/altair_charts.pysimilarity index 100%rename from marimo/_smoke_tests/altair_charts.pyrename to marimo/_smoke_tests/altair/altair_charts.pydiff --git a/tests/_plugins/ui/_impl/test_altair_chart.py b/tests/_plugins/ui/_impl/test_altair_chart.pyindex 54bb8be322..577dbe6acb 100644--- a/tests/_plugins/ui/_impl/test_altair_chart.py+++ b/tests/_plugins/ui/_impl/test_altair_chart.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport pytestfrom marimo._dependencies.dependencies import DependencyManager+from marimo._plugins.ui._impl import altair_chartfrom marimo._plugins.ui._impl.altair_chart import (ChartSelection,_filter_dataframe,@@ -137,3 +138,80 @@ class TestAltairChart:assert k.globals["initial_options"] == {}assert k.globals["options_1"] == {"max_rows": None}assert k.globals["options_2"] == {"max_rows": None}++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+def test_can_add_altair_chart() -> None:+ import altair as alt++ data = {"values": [1, 2, 3]}+ 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")+ )++ assert chart1 + chart2 is not None+ assert chart2 + chart1 is not None+ assert chart2 + unwrapped is not None+ with pytest.raises(ValueError):+ assert unwrapped + chart2++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+def test_can_or_altair_chart() -> None:+ import altair as alt++ data = {"values": [1, 2, 3]}+ 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")+ )++ assert chart1 | chart2 is not None+ assert chart2 | chart1 is not None+ assert chart2 | unwrapped is not None+ with pytest.raises(ValueError):+ assert unwrapped + chart2++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+def test_can_and_altair_chart() -> None:+ import altair as alt++ data = {"values": [1, 2, 3]}+ 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")+ )++ assert chart1 & chart2 is not None+ assert chart2 & chart1 is not None+ assert chart2 & unwrapped is not None+ with pytest.raises(ValueError):+ assert unwrapped + chart2++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+def test_does_not_modify_original() -> None:+ import altair as alt++ data = {"values": [1, 2, 3]}+ alt1 = (+ alt.Chart(data).mark_point().encode(x="values:Q").properties(width=200)+ )+ 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+ )++ assert combined1 == combined2._chart