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.

fix: support datetime values in `mo.ui.matplotlib` selection masks (#8940)

Myles Scolnicke72c47a0186d
diff --git a/marimo/_plugins/ui/_impl/mpl.py b/marimo/_plugins/ui/_impl/mpl.py
index 8a9d7fa2e7..69a665752f 100644
--- a/marimo/_plugins/ui/_impl/mpl.py
+++ b/marimo/_plugins/ui/_impl/mpl.py
@@ -6,6 +6,7 @@ import io
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
+ Any,
Final,
Protocol,
cast,
@@ -27,6 +28,19 @@ class MatplotlibSelection(Protocol):
def get_mask(self, x: ArrayLike, y: ArrayLike) -> NDArray[np.bool_]: ...
+def _to_numeric(arr: NDArray[Any]) -> NDArray[Any]:
+ """Convert a numpy array to matplotlib's numeric representation.
+
+ Only called on the slow path when a direct comparison raises
+ ``TypeError`` (e.g. datetime vs float). Uses
+ ``matplotlib.dates.date2num`` which handles ``datetime.datetime``,
+ ``datetime.date``, and ``numpy.datetime64``.
+ """
+ from matplotlib.dates import date2num # type: ignore[import-untyped]
+
+ return date2num(arr) # type: ignore[no-any-return,no-untyped-call]
+
+
@dataclass(frozen=True)
class BoxSelection:
"""A rectangular box selection on a matplotlib plot.
@@ -47,8 +61,8 @@ class BoxSelection:
"""Get a boolean mask for points within this selection.
Args:
- x: Array-like of x-coordinates.
- y: Array-like of y-coordinates.
+ x: Array-like of x-coordinates (numeric or datetime).
+ y: Array-like of y-coordinates (numeric or datetime).
Returns:
A boolean numpy array where `True` indicates the point is
@@ -58,12 +72,22 @@ class BoxSelection:
x_arr = np.asarray(x)
y_arr = np.asarray(y)
- return (
- (x_arr >= self.x_min)
- & (x_arr <= self.x_max)
- & (y_arr >= self.y_min)
- & (y_arr <= self.y_max)
- )
+ try:
+ return (
+ (x_arr >= self.x_min)
+ & (x_arr <= self.x_max)
+ & (y_arr >= self.y_min)
+ & (y_arr <= self.y_max)
+ )
+ except TypeError:
+ x_arr = _to_numeric(x_arr)
+ y_arr = _to_numeric(y_arr)
+ return (
+ (x_arr >= self.x_min)
+ & (x_arr <= self.x_max)
+ & (y_arr >= self.y_min)
+ & (y_arr <= self.y_max)
+ )
@dataclass(frozen=True)
@@ -80,8 +104,8 @@ class LassoSelection:
"""Get a boolean mask for points within this selection.
Args:
- x: Array-like of x-coordinates.
- y: Array-like of y-coordinates.
+ x: Array-like of x-coordinates (numeric or datetime).
+ y: Array-like of y-coordinates (numeric or datetime).
Returns:
A boolean numpy array where `True` indicates the point is
@@ -93,8 +117,14 @@ class LassoSelection:
x_arr = np.asarray(x)
y_arr = np.asarray(y)
path = Path(self.vertices)
- points = np.column_stack([x_arr, y_arr])
- return path.contains_points(points)
+ try:
+ points = np.column_stack([x_arr, y_arr])
+ return path.contains_points(points)
+ except TypeError:
+ x_arr = _to_numeric(x_arr)
+ y_arr = _to_numeric(y_arr)
+ points = np.column_stack([x_arr, y_arr])
+ return path.contains_points(points)
@dataclass(frozen=True)
diff --git a/tests/_plugins/ui/_impl/test_ui_mpl.py b/tests/_plugins/ui/_impl/test_ui_mpl.py
index e375a8621e..e1ee40a3ff 100644
--- a/tests/_plugins/ui/_impl/test_ui_mpl.py
+++ b/tests/_plugins/ui/_impl/test_ui_mpl.py
@@ -2,9 +2,9 @@
from __future__ import annotations
import io
+from datetime import datetime
from typing import Any
-import matplotlib.pyplot as plt # noqa: E402
import pytest
from marimo._plugins.ui._impl.mpl import ( # noqa: E402
@@ -21,6 +21,8 @@ mpl.use("Agg") # Non-interactive backend for testing
np = pytest.importorskip("numpy")
+import matplotlib.pyplot as plt # noqa: E402
+from matplotlib.dates import date2num # noqa: E402
# ============================================================================
# Constructor tests
@@ -332,3 +334,81 @@ def test_html_contains_tag() -> None:
fig = matplotlib(ax)
html = fig.text
assert "marimo-matplotlib" in html
+
+
+# ============================================================================
+# Datetime support tests
+# ============================================================================
+
+
+def test_box_selection_get_mask_datetime() -> None:
+ """BoxSelection.get_mask should work with datetime objects."""
+ dates_x = [
+ datetime(2020, 1, 1),
+ datetime(2022, 6, 15),
+ datetime(2025, 12, 31),
+ ]
+ dates_y = [
+ datetime(2000, 3, 10),
+ datetime(2010, 7, 20),
+ datetime(2020, 11, 5),
+ ]
+
+ # Selection bounds in matplotlib's internal float representation,
+ # matching what the frontend sends.
+ sel = BoxSelection(
+ x_min=date2num(datetime(2021, 1, 1)),
+ x_max=date2num(datetime(2026, 1, 1)),
+ y_min=date2num(datetime(2005, 1, 1)),
+ y_max=date2num(datetime(2015, 1, 1)),
+ )
+
+ mask = sel.get_mask(dates_x, dates_y)
+ # Only (2022-06-15, 2010-07-20) falls within the box
+ assert mask.tolist() == [False, True, False]
+
+
+def test_box_selection_get_mask_numpy_datetime64() -> None:
+ """BoxSelection.get_mask should work with numpy datetime64 arrays."""
+ x = np.array(
+ ["2020-01-01", "2022-06-15", "2025-12-31"], dtype="datetime64"
+ )
+ y = np.array(
+ ["2000-03-10", "2010-07-20", "2020-11-05"], dtype="datetime64"
+ )
+
+ sel = BoxSelection(
+ x_min=date2num(datetime(2021, 1, 1)),
+ x_max=date2num(datetime(2026, 1, 1)),
+ y_min=date2num(datetime(2005, 1, 1)),
+ y_max=date2num(datetime(2015, 1, 1)),
+ )
+
+ mask = sel.get_mask(x, y)
+ assert mask.tolist() == [False, True, False]
+
+
+def test_lasso_selection_get_mask_datetime() -> None:
+ """LassoSelection.get_mask should work with datetime objects."""
+ # Triangle that contains (2022-06-15, 2010-07-20) but not the others
+ v0 = (date2num(datetime(2021, 1, 1)), date2num(datetime(2005, 1, 1)))
+ v1 = (date2num(datetime(2026, 1, 1)), date2num(datetime(2005, 1, 1)))
+ v2 = (date2num(datetime(2023, 6, 1)), date2num(datetime(2015, 1, 1)))
+
+ sel = LassoSelection(vertices=(v0, v1, v2))
+
+ dates_x = [
+ datetime(2020, 1, 1),
+ datetime(2022, 6, 15),
+ datetime(2025, 12, 31),
+ ]
+ dates_y = [
+ datetime(2000, 3, 10),
+ datetime(2010, 7, 20),
+ datetime(2020, 11, 5),
+ ]
+
+ mask = sel.get_mask(dates_x, dates_y)
+ assert not mask[0] # outside triangle
+ assert mask[1] # inside triangle
+ assert not mask[2] # outside triangle