Skip to content

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.

improvement: add .apply_selection() to mo.ui.altair_chart for layered/stacked charts (#1557)

Myles Scolnick23235ac7fba2
diff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.py
index 7faa61a8b9..d579503e34 100644
--- a/marimo/_plugins/ui/_impl/altair_chart.py
+++ b/marimo/_plugins/ui/_impl/altair_chart.py
@@ -245,7 +245,7 @@ class altair_chart(UIElement[ChartSelection, "pd.DataFrame"]):
chart_selection = False
legend_selection = False
- self.dataframe = chart.data
+ self.dataframe: alt.UndefinedType | pd.DataFrame = chart.data
# Private attributes
self._chart = chart
@@ -268,6 +268,8 @@ class altair_chart(UIElement[ChartSelection, "pd.DataFrame"]):
return self._chart_selection
def _convert_value(self, value: ChartSelection) -> Any:
+ from altair import UndefinedType
+
self._chart_selection = value
flat, _ = flatten.flatten(value)
if not value or not flat:
@@ -275,6 +277,12 @@ class altair_chart(UIElement[ChartSelection, "pd.DataFrame"]):
return pd.DataFrame()
+ # When using layered charts, you can no longer access the
+ # chart data directly
+ # Instead, we should push user to call .apply_selection(df)
+ if isinstance(self.dataframe, UndefinedType):
+ return self.dataframe
+
# If we have transforms, we need to filter the dataframe
# with those transforms, before applying the selection
if _has_transforms(self._spec):
@@ -291,3 +299,59 @@ class altair_chart(UIElement[ChartSelection, "pd.DataFrame"]):
return _filter_dataframe(self.dataframe, value)
return _filter_dataframe(self.dataframe, value)
+
+ def apply_selection(self, df: pd.DataFrame) -> pd.DataFrame:
+ """Apply the selection to a DataFrame.
+
+ This method is useful when you have a layered chart and you want to
+ apply the selection to a DataFrame.
+
+ **Example.**
+
+ ```python
+ import altair as alt
+ import marimo as mo
+ from vega_datasets import data
+
+ cars = data.cars()
+
+ _chart = (
+ alt.Chart(cars)
+ .mark_point()
+ .encode(
+ x="Horsepower",
+ y="Miles_per_Gallon",
+ color="Origin",
+ )
+ )
+
+ chart = mo.ui.altair_chart(_chart)
+ chart
+
+ # In another cell
+ selected_df = chart.apply_selection(cars)
+ ```
+
+ **Args.**
+
+ - `df`: a Pandas DataFrame to apply the selection to
+
+ **Returns.**
+
+ - a Pandas DataFrame of the plot data filtered by the selections
+ """
+ return _filter_dataframe(df, self.selections)
+
+ @property
+ def value(self) -> pd.DataFrame:
+ from altair import UndefinedType
+
+ value = super().value
+ if isinstance(value, UndefinedType):
+ sys.stderr.write(
+ "The underlying chart data is not available in layered"
+ " or stacked charts. "
+ "Use `.apply_selection(df)` to filter a DataFrame"
+ " based on the selection.",
+ )
+ return value
diff --git a/marimo/_smoke_tests/bugs/1545.py b/marimo/_smoke_tests/bugs/1545.py
new file mode 100644
index 0000000000..cb1eec38e8
--- /dev/null
+++ b/marimo/_smoke_tests/bugs/1545.py
@@ -0,0 +1,74 @@
+import marimo
+
+__generated_with = "0.6.14"
+app = marimo.App(width="full")
+
+
+def __():
+ import altair as alt
+ import marimo as mo
+ import pandas as pd
+ return alt, mo, pd
+
+
+def __(pd):
+ df = pd.DataFrame(
+ data={
+ "annotation": ["w", "x", "y", "a", "b", "c", "d", "e", "f", "g"],
+ "x": [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6],
+ "y": pd.Series(
+ [9, 4, 1, 0, 1, 4, 9, 16, 25, 36],
+ index=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
+ ),
+ },
+ index=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
+ )
+ return df,
+
+
+def __(alt, df, pd):
+ scatter = alt.Chart(df).mark_point().encode(x="x", y="y", tooltip="annotation")
+ y_line = (
+ alt.Chart(pd.DataFrame({"var1": [0, 0], "var2": [0, 40]}))
+ .mark_line(color="grey")
+ .encode(alt.X("var1"), alt.Y("var2"))
+ )
+ return scatter, y_line
+
+
+def __(alt, mo, scatter, y_line):
+ layer_plot = mo.ui.altair_chart(
+ alt.layer(scatter, y_line)
+ .configure_axis(grid=False)
+ .configure_view(strokeWidth=0)
+ )
+
+ layer_plot
+ return layer_plot,
+
+
+def __(layer_plot):
+ layer_plot.selections
+ return
+
+
+def __(layer_plot):
+ print(layer_plot.value)
+ return
+
+
+def __(df, layer_plot):
+ print(layer_plot.apply_selection(df))
+ # should return a table of selected points based on the scatter plot
+ return
+
+
+if __name__ == "__main__":
+ app.run()