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: date filtering/selection for mo.ui.altair_chart (#349)
Myles Scolnick76cb32996f79
diff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.pyindex ffa96e0fab..cd43cc30fd 100644--- a/marimo/_plugins/ui/_impl/altair_chart.py+++ b/marimo/_plugins/ui/_impl/altair_chart.py@@ -88,10 +88,9 @@ def _filter_dataframe(elif len(resolved_values) == 2 and isinstance(resolved_values[0], (int, float, np.number)):- df = df[- (df[field] >= resolved_values[0])- & (df[field] <= resolved_values[1])- ]+ left_value = _coerce_value(dtype, resolved_values[0])+ right_value = _coerce_value(dtype, resolved_values[1])+ df = df[(df[field] >= left_value) & (df[field] <= right_value)]# Multi-selection via range# This can happen when you use an interval selection# on categorical data@@ -104,6 +103,17 @@ def _filter_dataframe(return df+def _coerce_value(dtype: Any, value: Any) -> Any:+ # If dtype is datetime[ns], then we need to convert the value+ # from milliseconds (which is what vega returns for dates)+ if dtype == "datetime64[ns]":+ import pandas as pd++ return pd.to_datetime(value, unit="ms")++ return value++def _parse_spec(spec: altair.TopLevelMixin) -> VegaSpec:import altairdiff --git a/marimo/_plugins/ui/_impl/test_altair_chart.py b/marimo/_plugins/ui/_impl/test_altair_chart.pyindex e5bb7c4bb5..ab4ebc40fa 100644--- a/marimo/_plugins/ui/_impl/test_altair_chart.py+++ b/marimo/_plugins/ui/_impl/test_altair_chart.py@@ -60,3 +60,36 @@ def test_filter_dataframe() -> None:}# Filter the DataFrame with the multi-field selectionassert len(_filter_dataframe(df, interval_and_point_selection)) == 1+++def test_filter_dataframe_with_dates() -> None:+ df = pd.DataFrame(+ {+ "field": ["value1", "value2", "value3", "value4"],+ "color": ["red", "red", "blue", "blue"],+ "field_2": [1, 2, 3, 4],+ "field_3": [10, 20, 30, 40],+ "date": pd.to_datetime(+ ["2020-01-01", "2020-01-03", "2020-01-05", "2020-01-07"]+ ),+ }+ )++ # Check that the date column is a datetime64[ns] column+ assert df["date"].dtype == "datetime64[ns]"++ # Define an interval selection+ interval_selection: ChartSelection = {+ "signal_channel_2": {+ "date": [+ # Vega passes back milliseconds since epoch+ 1577000000000, # Sunday, December 22, 2019 7:33:20 AM+ 1578009600000, # Friday, January 3, 2020 12:00:00 AM+ ]+ }+ }+ # Filter the DataFrame with the interval selection+ assert len(_filter_dataframe(df, interval_selection)) == 2+ first, second = _filter_dataframe(df, interval_selection)["field"].values+ assert first == "value1"+ assert second == "value2"diff --git a/marimo/_smoke_tests/altair_charts.py b/marimo/_smoke_tests/altair_charts.pyindex 08d5c2e4f5..efddb78d7b 100644--- a/marimo/_smoke_tests/altair_charts.py+++ b/marimo/_smoke_tests/altair_charts.py@@ -1,7 +1,7 @@# Copyright 2023 Marimo. All rights reserved.import marimo-__generated_with = "0.1.24"+__generated_with = "0.1.50"app = marimo.App(width="full")@@ -11,7 +11,8 @@ def __():from vega_datasets import dataimport jsonimport pandas as pd- return data, json, mo, pd+ import numpy as np+ return data, json, mo, np, pd@app.cell@@ -383,5 +384,101 @@ def __(mo, pie):return+def __(mo):+ mo.md("# Line Chart")+ return+++def __(alt, mo, np, pd):+ x = np.arange(100)+ source = pd.DataFrame({"x": x, "f(x)": np.sin(x / 5)})++ line_chart = mo.ui.altair_chart(+ alt.Chart(source).mark_line().encode(x="x", y="f(x)"),+ chart_selection="interval",+ )+ line_chart+ return line_chart, source, x+++def __(line_chart, mo):+ mo.hstack([line_chart.value, line_chart.selections])+ return+++def __(mo):+ mo.md("# Multi-Line Chart")+ return+++def __(alt, data, mo):+ _source = data.stocks()++ alt.Chart(_source).mark_line().encode(+ x="date:T",+ y="price:Q",+ color="symbol:N",+ )++ multiline_chart = mo.ui.altair_chart(+ alt.Chart(_source)+ .mark_line()+ .encode(+ x="date:T",+ y="price:Q",+ color="symbol:N",+ ),+ )+ multiline_chart+ return multiline_chart,+++def __(mo, multiline_chart):+ mo.hstack([multiline_chart.value, multiline_chart.selections])+ return+++def __(alt, mo, np, pd):+ # Example dataset+ _data = pd.DataFrame(+ {+ "date": pd.date_range(start="2021-01-01", periods=90, freq="D"),+ "value": np.random.randn(90).cumsum(),+ "category": ["A", "B", "C"] * 30,+ "color": ["red", "green", "blue"] * 30,+ }+ )++ # Create a base chart+ facet_chart = (+ alt.Chart(_data)+ .mark_line()+ .encode(+ x="date:T", # T indicates temporal (time-based) data+ y="value:Q", # Q indicates a quantitative field+ row="category:N", # N indicates a nominal field+ )+ .properties(title="Faceted Time Series Chart")+ .configure_facet(spacing=10) # Adjust spacing between facets+ )++ facet_chart = mo.ui.altair_chart(facet_chart, chart_selection="interval")+ facet_chart+ return facet_chart,+++def __(facet_chart, mo):+ mo.hstack([facet_chart.value, facet_chart.selections])+ return++if __name__ == "__main__":app.run()