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
feature: initial selection support for mo.ui.matplotlib (#10177)
Yair Chuchem360f0b6958f3
diff --git a/docs/guides/working_with_data/plotting.md b/docs/guides/working_with_data/plotting.mdindex b59fdc3094..d1eac1c1d2 100644--- a/docs/guides/working_with_data/plotting.md+++ b/docs/guides/working_with_data/plotting.md@@ -120,6 +120,18 @@ so you can always write:mask = ax.value.get_mask(x, y)```+Pass `value` to start with a box selection:++```python+ax = mo.ui.matplotlib(+ plt.gca(),+ value={"x": (1, 3), "y": (2, 4)},+)+```++The initial selection is clamped to the axes. If it does not overlap the+axes, `ax.value` is an `EmptySelection`.+### Altair/// marimo-embeddiff --git a/frontend/src/plugins/impl/matplotlib/__tests__/matplotlib-renderer.test.ts b/frontend/src/plugins/impl/matplotlib/__tests__/matplotlib-renderer.test.tsindex 4213f898dc..1ef747da48 100644--- a/frontend/src/plugins/impl/matplotlib/__tests__/matplotlib-renderer.test.ts+++ b/frontend/src/plugins/impl/matplotlib/__tests__/matplotlib-renderer.test.ts@@ -1,7 +1,11 @@/* Copyright 2026 Marimo. All rights reserved. */-import { describe, expect, it } from "vitest";-import type { Data } from "../matplotlib-renderer";-import { visibleForTesting } from "../matplotlib-renderer";+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ type Data,+ MatplotlibRenderer,+ type MatplotlibState,+ visibleForTesting,+} from "../matplotlib-renderer";const {pixelToData,@@ -185,3 +189,67 @@ describe("isInAxes", () => {expect(isInAxes({ x: 300, y: 351 }, LINEAR_AXES)).toBe(false);});});++describe("MatplotlibRenderer", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ it("restores a new selection when the chart changes", () => {+ vi.stubGlobal(+ "matchMedia",+ vi.fn(() => ({ addEventListener: vi.fn() })),+ );+ vi.stubGlobal(+ "requestAnimationFrame",+ vi.fn(() => 1),+ );+ vi.stubGlobal("cancelAnimationFrame", vi.fn());+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);++ const value = {+ type: "box",+ has_selection: true,+ data: { x_min: 2, x_max: 4, y_min: 2, y_max: 4 },+ } as const;+ const state: MatplotlibState = {+ ...LINEAR_AXES,+ axesPixelBounds: [0, 0, 100, 100],+ yBounds: [0, 10],+ chartBase64: "first",+ width: 100,+ height: 100,+ selectionColor: "blue",+ selectionOpacity: 0.15,+ strokeWidth: 2,+ debounce: false,+ value: { has_selection: false },+ setValue: vi.fn(),+ };+ const container = document.createElement("div");+ const controller = new AbortController();+ const renderer = new MatplotlibRenderer(container, {+ state,+ signal: controller.signal,+ });++ // Cell reruns reuse the renderer, updating the chart and initial value together.+ renderer.update({ ...state, chartBase64: "second", value });++ const canvas = container.querySelector("canvas");+ expect(canvas).not.toBeNull();+ if (!canvas) {+ return;+ }+ vi.spyOn(canvas, "getBoundingClientRect").mockReturnValue(+ DOMRect.fromRect({ width: 100, height: 100 }),+ );+ canvas.dispatchEvent(+ new MouseEvent("pointermove", { clientX: 30, clientY: 70 }),+ );++ expect(canvas.style.cursor).toBe("move");+ controller.abort();+ });+});diff --git a/frontend/src/plugins/impl/matplotlib/matplotlib-renderer.ts b/frontend/src/plugins/impl/matplotlib/matplotlib-renderer.tsindex 25bbdf5c05..e2079d954b 100644--- a/frontend/src/plugins/impl/matplotlib/matplotlib-renderer.ts+++ b/frontend/src/plugins/impl/matplotlib/matplotlib-renderer.ts@@ -377,6 +377,7 @@ export class MatplotlibRenderer {if (state.chartBase64 !== this.#currentChartBase64) {this.#loadImage(state.chartBase64);+ this.#restoreSelection(state.value);return;}diff --git a/marimo/_plugins/ui/_impl/mpl.py b/marimo/_plugins/ui/_impl/mpl.pyindex 5148c21ad7..f843428d67 100644--- a/marimo/_plugins/ui/_impl/mpl.py+++ b/marimo/_plugins/ui/_impl/mpl.py@@ -218,13 +218,21 @@ class matplotlib(UIElement[dict[str, JSONType], MatplotlibSelection]):Args:axes: A matplotlib `Axes` object. The full figure is rendered,but selections map to this axes' coordinate space.+ value: Initial box selection as `{"x": (min, max), "y": (min, max)}`.+ The selection is clamped to the axes' bounds.debounce: If `True`, the selection is only sent to Python onmouse-up. If `False` (the default), it streams while dragging."""name: Final[str] = "marimo-matplotlib"- def __init__(self, axes: Axes, *, debounce: bool = False) -> None:+ def __init__(+ self,+ axes: Axes,+ value: dict[str, tuple[float, float]] | None = None,+ *,+ debounce: bool = False,+ ) -> None:DependencyManager.matplotlib.require("for `mo.ui.matplotlib`")from matplotlib.figure import Figure # type: ignore[import-untyped]@@ -263,14 +271,46 @@ class matplotlib(UIElement[dict[str, JSONType], MatplotlibSelection]):(1 - bbox.y0) * fig_height_px, # bottom]+ x_bounds = axes.get_xlim()+ y_bounds = axes.get_ylim()+ initial_value: dict[str, JSONType] = {}+ if value is not None:+ try:+ selection_x_min, selection_x_max = sorted(+ map(float, value["x"])+ )+ selection_y_min, selection_y_max = sorted(+ map(float, value["y"])+ )+ except Exception:+ raise ValueError(+ "`value` must be of the form {'x': (min, max), 'y': (min, max)}."+ ) from None+ axes_x_min, axes_x_max = sorted(x_bounds)+ axes_y_min, axes_y_max = sorted(y_bounds)+ x_min = max(selection_x_min, axes_x_min)+ x_max = min(selection_x_max, axes_x_max)+ y_min = max(selection_y_min, axes_y_min)+ y_max = min(selection_y_max, axes_y_max)+ if x_min <= x_max and y_min <= y_max:+ initial_value = {+ "type": "box",+ "has_selection": True,+ "data": {+ "x_min": x_min,+ "x_max": x_max,+ "y_min": y_min,+ "y_max": y_max,+ },+ }super().__init__(component_name=matplotlib.name,- initial_value={},+ initial_value=initial_value,label="",args={"chart-base64": chart_base64,- "x-bounds": list(axes.get_xlim()),- "y-bounds": list(axes.get_ylim()),+ "x-bounds": list(x_bounds),+ "y-bounds": list(y_bounds),"axes-pixel-bounds": axes_pixel_bounds,"width": fig_width_px,"height": fig_height_px,diff --git a/tests/_plugins/ui/_impl/test_ui_mpl.py b/tests/_plugins/ui/_impl/test_ui_mpl.pyindex 39c9d2829e..46ce7e8f41 100644--- a/tests/_plugins/ui/_impl/test_ui_mpl.py+++ b/tests/_plugins/ui/_impl/test_ui_mpl.py@@ -45,6 +45,55 @@ def test_basic_construction() -> None:assert not fig.value+def test_initial_box_selection() -> None:+ ax = _make_scatter_ax()+ fig = matplotlib(ax, value={"x": (1.0, 3.0), "y": (2.0, 4.0)})++ assert fig._args.initial_value == {+ "type": "box",+ "has_selection": True,+ "data": {+ "x_min": 1.0,+ "x_max": 3.0,+ "y_min": 2.0,+ "y_max": 4.0,+ },+ }+ assert fig.value == BoxSelection(+ x_min=1.0,+ x_max=3.0,+ y_min=2.0,+ y_max=4.0,+ )+++def test_initial_box_selection_clamps_to_axes() -> None:+ ax = _make_scatter_ax()+ axes_x_min, axes_x_max = sorted(ax.get_xlim())+ axes_y_min, axes_y_max = sorted(ax.get_ylim())++ partial = matplotlib(+ ax,+ value={+ "x": (3.0, axes_x_min - 1),+ "y": (axes_y_max + 1, 2.0),+ },+ )+ assert partial.value == BoxSelection(+ x_min=axes_x_min,+ x_max=3.0,+ y_min=2.0,+ y_max=axes_y_max,+ )++ outside = matplotlib(+ ax,+ value={"x": (axes_x_max + 1, axes_x_max + 2), "y": (2.0, 4.0)},+ )+ assert isinstance(outside.value, EmptySelection)+ assert outside._args.initial_value == {}++def test_construction_no_figure_raises() -> None:fig = plt.figure()ax = fig.add_subplot(111)