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 with transform_filter (#734)
Myles Scolnick8090342da0d5
diff --git a/docs/guides/plotting.md b/docs/guides/plotting.mdindex 4ff8a7e401..4cbbd3412a 100644--- a/docs/guides/plotting.md+++ b/docs/guides/plotting.md@@ -7,7 +7,6 @@ as you normally would.For Altair plots, marimo does something special: use [`mo.ui.altair_chart`](#reactive-plots)to connect frontend selections to Python!-```{admonition} Reactive plots!:class: important@@ -17,7 +16,6 @@ filter with your mouse, and marimo _automatically makes the selected dataavailable in Python as a Pandas dataframe_!```-## Reactive plots! ⚡<!-- <iframe class="demo" src="https://components.marimo.io/?component=slider" frameborder="no"></iframe> -->@@ -32,12 +30,12 @@ automatically made available as Pandas dataframes in Python._</figure></div>-```{admonition} Requirements:class: warningReactive plots currently require Altair. Install it with `pip install altair`In the future, we may make other plotting libraries reactive.```+Wrap an Altair chart in [`mo.ui.altair_chart`](../api/plotting.md#marimo.ui.altair_chart)to make it **reactive**: select data on the frontend, access it via the chart's`value` attribute (`chart.value`).@@ -139,6 +137,19 @@ You may still add your own selection parameters via Altair or Vega-Lite.marimo will not override your selections.```+### Altair transformations++Altair supports a variety of transformations, such as filtering, aggregation, and sorting. These transformations can be used to create more complex and nuanced visualizations. For example, you can use a filter to show only the points that meet a certain condition, or use an aggregation to show the average value of a variable.++In order for marimo's reactive plots to work with transformations, you must install `vegafusion`, as this feature uses `chart.transformed_data` (which requires version 1.4.0 or greater of the `vegafusion` packages).++```bash+# These can be installed with pip using:+pip install "vegafusion[embed]>=1.4.0"+# Or with conda using:+conda install -c conda-forge "vegafusion-python-embed>=1.4.0" "vegafusion>=1.4.0"+```+## matplotlibTo output a matplotlib plot in a cell's output area, include its `Axes` ordiff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.pyindex 5ab57c2f5b..d9cdb9e6b5 100644--- a/marimo/_plugins/ui/_impl/altair_chart.py+++ b/marimo/_plugins/ui/_impl/altair_chart.py@@ -124,6 +124,11 @@ def _parse_spec(spec: altair.TopLevelMixin) -> VegaSpec:return spec.to_dict() # type: ignore+def _has_transforms(spec: VegaSpec) -> bool:+ """Return True if the spec has transforms."""+ return "transform" in spec and len(spec["transform"]) > 0++@mddocclass altair_chart(UIElement[ChartSelection, "pd.DataFrame"]):"""Make reactive charts with Altair@@ -234,6 +239,10 @@ class altair_chart(UIElement[ChartSelection, "pd.DataFrame"]):self.dataframe = chart.data+ # Private attributes+ self._chart = chart+ self._spec = vega_spec+super().__init__(component_name="marimo-vega",initial_value={},@@ -257,4 +266,20 @@ class altair_chart(UIElement[ChartSelection, "pd.DataFrame"]):import pandas as pdreturn pd.DataFrame()++ # If we have transforms, we need to filter the dataframe+ # with those transforms, before applying the selection+ if _has_transforms(self._spec):+ try:+ df: pd.DataFrame = self._chart.transformed_data()+ return _filter_dataframe(df, value)+ except ImportError as e:+ sys.stderr.write(+ "Failed to filter dataframe that includes a transform. "+ + "This could be due to a missing dependency.\n\n"+ + e.msg+ )+ # Fall back to the untransformed dataframe+ return _filter_dataframe(self.dataframe, value)+return _filter_dataframe(self.dataframe, value)diff --git a/marimo/_smoke_tests/altair_charts.py b/marimo/_smoke_tests/altair_charts.pyindex 8aef98a66d..f23c7dd844 100644--- a/marimo/_smoke_tests/altair_charts.py+++ b/marimo/_smoke_tests/altair_charts.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.import marimo-__generated_with = "0.1.59"+__generated_with = "0.2.1"app = marimo.App(width="full")@@ -508,5 +508,40 @@ def __(facet_chart, mo):return+def __(mo):+ mo.md(+ """+ # With `transform_filter`+ > Bug https://github.com/marimo-team/marimo/issues/727+ """+ )+ return+++def __(alt, data, mo):+ from altair import datum++ _chart = (+ alt.Chart(data.cars())+ .mark_point()+ .encode(+ x="Horsepower",+ y="Miles_per_Gallon",+ color="Origin",+ )+ .transform_filter(datum.Origin == "Europe")+ )+ with_transform = mo.ui.altair_chart(_chart)+ return datum, with_transform+++def __(mo, with_transform):+ mo.vstack([with_transform, with_transform.value])+ return++if __name__ == "__main__":app.run()