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
feat: mo.ui.matplotlib() (#8342)
Akshay Agrawal4fe9ebe38f56
diff --git a/docs/api/plotting.md b/docs/api/plotting.mdindex 1c5f318c34..4383853b1b 100644--- a/docs/api/plotting.md+++ b/docs/api/plotting.md@@ -6,6 +6,10 @@ as you normally would.For more information about plotting, see the [plotting guide](../guides/working_with_data/plotting.md).+## Reactive plots with matplotlib++::: marimo.ui.matplotlib+## Reactive charts with Altair/// marimo-embed@@ -105,13 +109,13 @@ alt.data_transformers.enable('marimo_csv')show_root_heading: trueshow_source: true-## Leafmap support+## Leafmapmarimo supports rendering [Leafmap](https://leafmap.org/) maps using the `folium` and `plotly` backends.## Other plotting libraries-You can use all the popular plotting libraries with marimo. Such as:+You can use all the popular plotting libraries with marimo, such as:- [Matplotlib](https://matplotlib.org/)- [Plotly](https://plotly.com/)diff --git a/docs/guides/working_with_data/plotting.md b/docs/guides/working_with_data/plotting.mdindex 3a912ce20b..0de3ae7f3d 100644--- a/docs/guides/working_with_data/plotting.md+++ b/docs/guides/working_with_data/plotting.md@@ -4,29 +4,90 @@ marimo supports most major plotting libraries, including Matplotlib, Seaborn,Plotly, Altair, and HoloViews. Just import your plotting library of choice anduse it as you normally would.-For Altair and Plotly plots, marimo does something special: use+For matplotlib, Altair, and Plotly plots, marimo does something special: wrap+your plot in [`mo.ui.matplotlib`][marimo.ui.matplotlib],[`mo.ui.altair_chart`][marimo.ui.altair_chart] or-[`mo.ui.plotly`][marimo.ui.plotly] to connect frontend-selections to Python!+[`mo.ui.plotly`][marimo.ui.plotly], then select and filter with your mouse —+marimo automatically sends the selected data back to Python!-> For a video overview of reactive plots, check out our [YouTube tutorial](https://youtu.be/KFXsm1wr408).--!!! important "Reactive plots!"- marimo supports reactive plots via- [`mo.ui.altair_chart`][marimo.ui.altair_chart] and- [`mo.ui.plotly`][marimo.ui.plotly]! Select and- filter with your mouse, and marimo _automatically makes the selected data- available in Python as a Pandas dataframe_!+> For a video overview of reactive plots, check out our [YouTube tutorial](https://youtu.be/KFXsm1wr408).## Reactive plots! ⚡!!! warning "Requirements"- Reactive plots currently require Altair or Plotly. Install with `pip install- altair` or `pip install plotly`, depending on which library you are using.- Selections in plotly are limited to scatter plots, treemaps charts, and sunbursts charts, while Altair supports- a larger class of plots for selections.+ Reactive plots currently require matplotlib, Altair, or Plotly. Matplotlib+ supports box and lasso selections (best suited for scatter plots);+ selections in Plotly are limited to scatter plots, bar charts, heatmaps,+ treemaps, and sunburst charts; Altair supports a larger class of plots+ for selections.++### matplotlib++Use [`mo.ui.matplotlib`][marimo.ui.matplotlib] to make matplotlib plots+**reactive**: select data on the frontend, then use the selection to filter+your data in Python.++Two selection modes are supported:++- **Box selection** — click and drag to draw a rectangular region.+- **Lasso selection** — hold <kbd>Shift</kbd> and drag to draw a freehand+ polygon.++After selecting, use `fig.value.get_mask(x, y)` to get a boolean mask of the+points inside the selection. When nothing is selected, `fig.value` is falsy and+`get_mask()` returns an all-`False` array.++#### Example++<!-- TODO add a WASM version when shipped. -->++```python+import matplotlib.pyplot as plt+import marimo as mo+import numpy as np++x = np.random.randn(500)+y = np.random.randn(500)+plt.scatter(x, y)+# Wrap the Axes in mo.ui.matplotlib to make them reactive ⚡+ax = mo.ui.matplotlib(plt.gca())+ax+```++```python+# In another cell — filter your data using the selection+mask = ax.value.get_mask(x, y)+selected_x, selected_y = x[mask], y[mask]+```++#### Debouncing++By default, the selection streams to Python as you drag. For expensive+downstream computations or very large datasets, pass `debounce=True` so the+value is only sent on mouse-up:++```python+ax = mo.ui.matplotlib(plt.gca(), debounce=True)+```++#### Selection types++`ax.value` is one of three types:++| Type | When | Attributes |+|------|------|------------|+| `EmptySelection` | Nothing selected (falsy) | — |+| `BoxSelection` | Box drag | `x_min`, `x_max`, `y_min`, `y_max` |+| `LassoSelection` | <kbd>Shift</kbd>+drag | `vertices` (tuple of `(x, y)` pairs) |++All three have a `get_mask(x, y)` method that returns a boolean NumPy array,+so you can always write:++```python+mask = ax.value.get_mask(x, y)+```### Altair@@ -271,11 +332,10 @@ axIf you want to output the plot in the console area, use `plt.show()` or`fig.show()`.-### Interactive plots+### Interactive plots with pan and zoom-To make matplotlib plots interactive, use-[mo.mpl.interactive][marimo.mpl.interactive].-(Matplotlib plots are not yet reactive.)+To make matplotlib plots interactive with pan and zoom, use+[mo.mpl.interactive][marimo.mpl.interactive]. This does not support reactive selection.## Chart builderdiff --git a/examples/outputs/plots.py b/examples/outputs/plots.pyindex 52d25f1868..7624156810 100644--- a/examples/outputs/plots.py+++ b/examples/outputs/plots.py@@ -61,5 +61,30 @@ def _(plt, x):return[email protected](hide_code=True)+def _(mo):+ mo.md("""+ Wrap an `Axes` in `mo.ui.matplotlib` to enable reactive selections.+ Click-drag for box selection, shift-drag for lasso selection.+ """)+ return+++def _(mo, np, plt):+ _x = np.random.randn(200)+ _y = np.random.randn(200)+ plt.scatter(_x, _y)+ scatter_fig = mo.ui.matplotlib(plt.gca())+ scatter_fig+ return (scatter_fig,)+++def _(scatter_fig):+ scatter_fig.value+ return++if __name__ == "__main__":app.run()diff --git a/frontend/src/plugins/impl/matplotlib/MatplotlibPlugin.tsx b/frontend/src/plugins/impl/matplotlib/MatplotlibPlugin.tsxnew file mode 100644index 0000000000..1e1245355e--- /dev/null+++ b/frontend/src/plugins/impl/matplotlib/MatplotlibPlugin.tsx@@ -0,0 +1,70 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { type JSX, useEffect, useRef } from "react";+import { z } from "zod";+import type { IPlugin, IPluginProps } from "@/plugins/types";+import {+ type Data,+ MatplotlibRenderer,+ type MatplotlibState,+ type SelectionValue as T,+} from "./matplotlib-renderer";++export class MatplotlibPlugin implements IPlugin<T, Data> {+ tagName = "marimo-matplotlib";++ validator = z.object({+ chartBase64: z.string(),+ xBounds: z.tuple([z.number(), z.number()]),+ yBounds: z.tuple([z.number(), z.number()]),+ axesPixelBounds: z.tuple([z.number(), z.number(), z.number(), z.number()]),+ width: z.number(),+ height: z.number(),+ selectionColor: z.string().default("#3b82f6"),+ selectionOpacity: z.number().default(0.15),+ strokeWidth: z.number().default(2),+ debounce: z.boolean(),+ xScale: z.enum(["linear", "log"]).default("linear"),+ yScale: z.enum(["linear", "log"]).default("linear"),+ });++ render(props: IPluginProps<T, Data>): JSX.Element {+ return (+ <MatplotlibComponent+ {...props.data}+ value={props.value}+ setValue={props.setValue}+ />+ );+ }+}++const MatplotlibComponent = (props: MatplotlibState) => {+ const ref = useRef<HTMLDivElement>(null);+ const instance = useRef<MatplotlibRenderer | null>(null);++ useEffect(() => {+ const container = ref.current;+ if (!container) {+ return;+ }+ const controller = new AbortController();+ instance.current = new MatplotlibRenderer(container, {+ state: props,+ signal: controller.signal,+ });+ return () => {+ controller.abort();+ instance.current = null;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ // No dependency array: intentionally syncs all props into the imperative+ // renderer after every render. The renderer's update() method diffs internally.+ useEffect(() => {+ instance.current?.update(props);+ });++ return <div ref={ref} />;+};diff --git a/frontend/src/plugins/impl/matplotlib/__tests__/matplotlib-renderer.test.ts b/frontend/src/plugins/impl/matplotlib/__tests__/matplotlib-renderer.test.tsnew file mode 100644index 0000000000..c68443b592--- /dev/null+++ b/frontend/src/plugins/impl/matplotlib/__tests__/matplotlib-renderer.test.ts@@ -0,0 +1,152 @@+/* Copyright 2026 Marimo. All rights reserved. */+import { describe, expect, it } from "vitest";+import type { Data } from "../matplotlib-renderer";+import { visibleForTesting } from "../matplotlib-renderer";++const { pixelToData, dataToPixel, pointInPolygon, clampToAxes, isPointInBox } =+ visibleForTesting;++// A simple axes geometry for testing:+// axes occupy pixels [100, 50] to [500, 350] (400px wide, 300px tall)+// data range x: [0, 10], y: [0, 100]+const LINEAR_AXES: Pick<+ Data,+ "axesPixelBounds" | "xBounds" | "xScale" | "yBounds" | "yScale"+> = {+ axesPixelBounds: [100, 50, 500, 350],+ xBounds: [0, 10],+ yBounds: [0, 100],+ xScale: "linear",+ yScale: "linear",+};++const LOG_AXES: Pick<+ Data,+ "axesPixelBounds" | "xBounds" | "xScale" | "yBounds" | "yScale"+> = {+ axesPixelBounds: [100, 50, 500, 350],+ xBounds: [1, 1000],+ yBounds: [1, 1000],+ xScale: "log",+ yScale: "log",+};++describe("pixelToData", () => {+ it("maps top-left of axes to (xMin, yMax)", () => {+ const result = pixelToData({ x: 100, y: 50 }, LINEAR_AXES);+ expect(result.x).toBeCloseTo(0);+ expect(result.y).toBeCloseTo(100);+ });++ it("maps bottom-right of axes to (xMax, yMin)", () => {+ const result = pixelToData({ x: 500, y: 350 }, LINEAR_AXES);+ expect(result.x).toBeCloseTo(10);+ expect(result.y).toBeCloseTo(0);+ });++ it("maps center of axes to midpoint of data range", () => {+ const result = pixelToData({ x: 300, y: 200 }, LINEAR_AXES);+ expect(result.x).toBeCloseTo(5);+ expect(result.y).toBeCloseTo(50);+ });+});++describe("dataToPixel", () => {+ it("maps (xMin, yMax) to top-left of axes", () => {+ const result = dataToPixel({ x: 0, y: 100 }, LINEAR_AXES);+ expect(result.x).toBeCloseTo(100);+ expect(result.y).toBeCloseTo(50);+ });++ it("maps (xMax, yMin) to bottom-right of axes", () => {+ const result = dataToPixel({ x: 10, y: 0 }, LINEAR_AXES);+ expect(result.x).toBeCloseTo(500);+ expect(result.y).toBeCloseTo(350);+ });+});++describe("pixelToData / dataToPixel roundtrip", () => {+ it("roundtrips linear coordinates", () => {+ const pixel = { x: 250, y: 175 };+ const data = pixelToData(pixel, LINEAR_AXES);+ const back = dataToPixel(data, LINEAR_AXES);+ expect(back.x).toBeCloseTo(pixel.x);+ expect(back.y).toBeCloseTo(pixel.y);+ });++ it("roundtrips log coordinates", () => {+ const pixel = { x: 300, y: 200 };+ const data = pixelToData(pixel, LOG_AXES);+ const back = dataToPixel(data, LOG_AXES);+ expect(back.x).toBeCloseTo(pixel.x);+ expect(back.y).toBeCloseTo(pixel.y);+ });+});++describe("pointInPolygon", () => {+ // Triangle with vertices at (0,0), (10,0), (5,10)+ const triangle = [+ { x: 0, y: 0 },+ { x: 10, y: 0 },+ { x: 5, y: 10 },+ ];++ it("returns true for a point inside", () => {+ expect(pointInPolygon({ x: 5, y: 3 }, triangle)).toBe(true);+ });++ it("returns false for a point outside", () => {+ expect(pointInPolygon({ x: 20, y: 20 }, triangle)).toBe(false);+ });++ it("returns false for a point just outside a side", () => {+ expect(pointInPolygon({ x: 0, y: 5 }, triangle)).toBe(false);+ });+});++describe("clampToAxes", () => {+ it("does not change a point inside the axes", () => {+ const result = clampToAxes({ x: 300, y: 200 }, LINEAR_AXES);+ expect(result).toEqual({ x: 300, y: 200 });+ });++ it("clamps a point left of axes to left edge", () => {+ const result = clampToAxes({ x: 50, y: 200 }, LINEAR_AXES);+ expect(result.x).toBe(100);+ expect(result.y).toBe(200);+ });++ it("clamps a point above axes to top edge", () => {+ const result = clampToAxes({ x: 300, y: 10 }, LINEAR_AXES);+ expect(result.x).toBe(300);+ expect(result.y).toBe(50);+ });++ it("clamps a point beyond bottom-right to corner", () => {+ const result = clampToAxes({ x: 600, y: 400 }, LINEAR_AXES);+ expect(result).toEqual({ x: 500, y: 350 });+ });+});++describe("isPointInBox", () => {+ const boxStart = { x: 10, y: 10 };+ const boxEnd = { x: 50, y: 50 };++ it("returns true for a point inside", () => {+ expect(isPointInBox({ x: 30, y: 30 }, boxStart, boxEnd)).toBe(true);+ });++ it("returns true for a point on the edge", () => {+ expect(isPointInBox({ x: 10, y: 30 }, boxStart, boxEnd)).toBe(true);+ });++ it("returns false for a point outside", () => {+ expect(isPointInBox({ x: 5, y: 30 }, boxStart, boxEnd)).toBe(false);+ });++ it("works regardless of start/end order", () => {+ // Swap start and end (end is top-left, start is bottom-right)+ expect(isPointInBox({ x: 30, y: 30 }, boxEnd, boxStart)).toBe(true);+ expect(isPointInBox({ x: 5, y: 30 }, boxEnd, boxStart)).toBe(false);+ });+});diff --git a/frontend/src/plugins/impl/matplotlib/matplotlib-renderer.ts b/frontend/src/plugins/impl/matplotlib/matplotlib-renderer.tsnew file mode 100644index 0000000000..8655a92a9c--- /dev/null+++ b/frontend/src/plugins/impl/matplotlib/matplotlib-renderer.ts@@ -0,0 +1,781 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type { Setter } from "@/plugins/types";++export type ScaleType = "linear" | "log";++export interface Data {+ chartBase64: string;+ xBounds: [number, number];+ yBounds: [number, number];+ axesPixelBounds: [number, number, number, number]; // [left, top, right, bottom]+ width: number;+ height: number;+ selectionColor: string;+ selectionOpacity: number;+ strokeWidth: number;+ debounce: boolean;+ xScale: ScaleType;+ yScale: ScaleType;+}++export interface BoxData {+ x_min: number;+ x_max: number;+ y_min: number;+ y_max: number;+}++export type SelectionValue =+ | { type: "box"; has_selection: true; data: BoxData }+ | { type: "lasso"; has_selection: true; data: [number, number][] }+ | { has_selection: false }+ | undefined;++type AxesGeometry = Pick<+ Data,+ "axesPixelBounds" | "xBounds" | "xScale" | "yBounds" | "yScale"+>;++// Pixel coordinate in canvas space+interface PixelPoint {+ x: number;+ y: number;+}++// Data coordinate in plot space+interface DataPoint {+ x: number;+ y: number;+}++// -- State machine types --++type BoxAction =+ | { type: "drawing" }+ | { type: "dragging"; origin: PixelPoint }+ | {+ type: "resizing";+ anchor: PixelPoint;+ lockX: number | null;+ lockY: number | null;+ };++type LassoAction =+ | { type: "drawing" }+ | { type: "dragging"; origin: PixelPoint };++type Interaction =+ | { type: "idle" }+ | {+ type: "box";+ start: PixelPoint;+ end: PixelPoint;+ action: BoxAction | null;+ }+ | { type: "lasso"; points: PixelPoint[]; action: LassoAction | null };++// -- Resize handle detection --++type ResizeHandle = "n" | "s" | "e" | "w" | "nw" | "ne" | "sw" | "se";++const HANDLE_SIZE = 7; // pixels from edge to trigger resize++const RESIZE_CURSORS: Record<ResizeHandle, string> = {+ n: "ns-resize",+ s: "ns-resize",+ e: "ew-resize",+ w: "ew-resize",+ nw: "nwse-resize",+ se: "nwse-resize",+ ne: "nesw-resize",+ sw: "nesw-resize",+};++function getResizeHandle(+ pt: PixelPoint,+ boxStart: PixelPoint,+ boxEnd: PixelPoint,+): ResizeHandle | null {+ const minX = Math.min(boxStart.x, boxEnd.x);+ const maxX = Math.max(boxStart.x, boxEnd.x);+ const minY = Math.min(boxStart.y, boxEnd.y);+ const maxY = Math.max(boxStart.y, boxEnd.y);++ const nearLeft = Math.abs(pt.x - minX) <= HANDLE_SIZE;+ const nearRight = Math.abs(pt.x - maxX) <= HANDLE_SIZE;+ const nearTop = Math.abs(pt.y - minY) <= HANDLE_SIZE;+ const nearBottom = Math.abs(pt.y - maxY) <= HANDLE_SIZE;+ const withinX = pt.x >= minX - HANDLE_SIZE && pt.x <= maxX + HANDLE_SIZE;+ const withinY = pt.y >= minY - HANDLE_SIZE && pt.y <= maxY + HANDLE_SIZE;++ // Corners first (more specific)+ if (nearLeft && nearTop) {+ return "nw";+ }+ if (nearRight && nearTop) {+ return "ne";+ }+ if (nearLeft && nearBottom) {+ return "sw";+ }+ if (nearRight && nearBottom) {+ return "se";+ }++ // Edges+ if (nearTop && withinX) {+ return "n";+ }+ if (nearBottom && withinX) {+ return "s";+ }+ if (nearLeft && withinY) {+ return "w";+ }+ if (nearRight && withinY) {+ return "e";+ }++ return null;+}++function getResizeConfig(+ handle: ResizeHandle,+ start: PixelPoint,+ end: PixelPoint,+): { anchor: PixelPoint; lockX: number | null; lockY: number | null } {+ const minX = Math.min(start.x, end.x);+ const maxX = Math.max(start.x, end.x);+ const minY = Math.min(start.y, end.y);+ const maxY = Math.max(start.y, end.y);++ switch (handle) {+ case "nw":+ return { anchor: { x: maxX, y: maxY }, lockX: null, lockY: null };+ case "ne":+ return { anchor: { x: minX, y: maxY }, lockX: null, lockY: null };+ case "sw":+ return { anchor: { x: maxX, y: minY }, lockX: null, lockY: null };+ case "se":+ return { anchor: { x: minX, y: minY }, lockX: null, lockY: null };+ case "n":+ return { anchor: { x: minX, y: maxY }, lockX: maxX, lockY: null };+ case "s":+ return { anchor: { x: minX, y: minY }, lockX: maxX, lockY: null };+ case "w":+ return { anchor: { x: maxX, y: minY }, lockX: null, lockY: maxY };+ case "e":+ return { anchor: { x: minX, y: minY }, lockX: null, lockY: maxY };+ }+}++export interface MatplotlibState extends Data {+ value: SelectionValue;+ setValue: Setter<SelectionValue>;+}++// Minimal d3-like scale: maps between data domain and [0, 1] fraction+interface Scale {+ /** data value → normalized [0, 1] */+ normalize(value: number): number;+ /** normalized [0, 1] → data value */+ invert(frac: number): number;+}++function createScale(type: ScaleType, bounds: [number, number]): Scale {+ const [min, max] = bounds;+ if (type === "log") {+ const logMin = Math.log10(min);+ const logRange = Math.log10(max) - logMin;+ return {+ normalize: (v) => (Math.log10(v) - logMin) / logRange,+ invert: (f) => 10 ** (logMin + f * logRange),+ };+ }+ const range = max - min;+ return {+ normalize: (v) => (v - min) / range,+ invert: (f) => min + f * range,+ };+}++// Ray-casting point-in-polygon test+function pointInPolygon(pt: PixelPoint, polygon: PixelPoint[]): boolean {+ let inside = false;+ for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {+ const xi = polygon[i].x;+ const yi = polygon[i].y;+ const xj = polygon[j].x;+ const yj = polygon[j].y;+ if (+ yi > pt.y !== yj > pt.y &&+ pt.x < ((xj - xi) * (pt.y - yi)) / (yj - yi) + xi+ ) {+ inside = !inside;+ }+ }+ return inside;+}++function pixelToData(px: PixelPoint, g: AxesGeometry): DataPoint {+ const [axLeft, axTop, axRight, axBottom] = g.axesPixelBounds;+ const fracX = (px.x - axLeft) / (axRight - axLeft);+ const fracY = (px.y - axTop) / (axBottom - axTop);+ const sx = createScale(g.xScale, g.xBounds);+ const sy = createScale(g.yScale, g.yBounds);+ return { x: sx.invert(fracX), y: sy.invert(1 - fracY) };+}++function dataToPixel(data: DataPoint, g: AxesGeometry): PixelPoint {+ const [axLeft, axTop, axRight, axBottom] = g.axesPixelBounds;+ const sx = createScale(g.xScale, g.xBounds);+ const sy = createScale(g.yScale, g.yBounds);+ return {+ x: axLeft + sx.normalize(data.x) * (axRight - axLeft),+ y: axTop + (1 - sy.normalize(data.y)) * (axBottom - axTop),+ };+}++function clampToAxes(pt: PixelPoint, g: AxesGeometry) {+ const [axLeft, axTop, axRight, axBottom] = g.axesPixelBounds;+ return {+ x: Math.max(axLeft, Math.min(axRight, pt.x)),+ y: Math.max(axTop, Math.min(axBottom, pt.y)),+ };+}++function isPointInBox(+ pt: PixelPoint,+ boxStart: PixelPoint,+ boxEnd: PixelPoint,+): boolean {+ const minX = Math.min(boxStart.x, boxEnd.x);+ const maxX = Math.max(boxStart.x, boxEnd.x);+ const minY = Math.min(boxStart.y, boxEnd.y);+ const maxY = Math.max(boxStart.y, boxEnd.y);+ return pt.x >= minX && pt.x <= maxX && pt.y >= minY && pt.y <= maxY;+}++export const visibleForTesting = {+ createScale,+ pixelToData,+ dataToPixel,+ pointInPolygon,+ clampToAxes,+ isPointInBox,+};++export class MatplotlibRenderer {+ #canvas: HTMLCanvasElement;+ #container: HTMLDivElement;+ #state: MatplotlibState;+ #interaction: Interaction = { type: "idle" };+ #rafId = 0;+ #image: HTMLImageElement | null = null;+ #imageGeneration = 0;+ #currentChartBase64 = "";++ constructor(+ container: HTMLDivElement,+ options: { state: MatplotlibState; signal: AbortSignal },+ ) {+ this.#container = container;+ this.#state = options.state;++ // Configure container+ container.tabIndex = -1;+ container.role = "application";+ container.className = "relative inline-block select-none outline-none";++ // Create canvas+ const canvas = document.createElement("canvas");+ canvas.className = "block cursor-crosshair";+ const dpr = globalThis.devicePixelRatio ?? 1;+ canvas.width = this.#state.width * dpr;+ canvas.height = this.#state.height * dpr;+ canvas.style.width = `${this.#state.width}px`;+ canvas.style.height = `${this.#state.height}px`;+ canvas.style.maxWidth = "100%";+ canvas.style.touchAction = "none";+ container.append(canvas);+ this.#canvas = canvas;++ // Register event listeners with AbortSignal for auto-cleanup+ canvas.addEventListener("pointerdown", this.#handlePointerDown, {+ signal: options.signal,+ });+ canvas.addEventListener("pointermove", this.#handlePointerMove, {+ signal: options.signal,+ });+ canvas.addEventListener("pointerup", this.#handlePointerUp, {+ signal: options.signal,+ });+ container.addEventListener("keydown", this.#handleKeyDown, {+ signal: options.signal,+ });++ // Clean up on abort+ options.signal.addEventListener("abort", () => {+ cancelAnimationFrame(this.#rafId);+ this.#canvas.remove();+ });++ // Initial load+ this.#loadImage(this.#state.chartBase64);+ this.#restoreSelection(this.#state.value);+ }++ update(state: MatplotlibState): void {+ const prev = this.#state;+ this.#state = state;++ if (state.chartBase64 !== this.#currentChartBase64) {+ this.#loadImage(state.chartBase64);+ return;+ }++ // Update canvas dimensions if changed+ if (state.width !== prev.width || state.height !== prev.height) {+ const dpr = globalThis.devicePixelRatio ?? 1;+ this.#canvas.width = state.width * dpr;+ this.#canvas.height = state.height * dpr;+ this.#canvas.style.width = `${state.width}px`;+ this.#canvas.style.height = `${state.height}px`;+ }++ // Redraw if style props changed or dimensions changed+ if (+ state.selectionColor !== prev.selectionColor ||+ state.selectionOpacity !== prev.selectionOpacity ||+ state.strokeWidth !== prev.strokeWidth ||+ state.width !== prev.width ||+ state.height !== prev.height+ ) {+ this.#drawCanvas();+ }+ }++ #loadImage(chartBase64: string): void {+ this.#currentChartBase64 = chartBase64;+ this.#imageGeneration++;+ const generation = this.#imageGeneration;++ // Clear selection on new chart+ this.#interaction = { type: "idle" };++ const img = new Image();+ img.onload = () => {+ if (generation !== this.#imageGeneration) {+ return;+ }+ this.#image = img;+ this.#drawCanvas();+ };+ img.src = chartBase64;+ }++ #drawCanvas = (): void => {+ const img = this.#image;+ if (!img) {+ return;+ }++ const ctx = this.#canvas.getContext("2d");+ if (!ctx) {+ return;+ }++ const s = this.#state;+ const ix = this.#interaction;++ // Scale for HiDPI: all coordinates remain in logical pixels+ const dpr = globalThis.devicePixelRatio ?? 1;+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);++ // Clear and draw the base image+ ctx.clearRect(0, 0, s.width, s.height);+ ctx.drawImage(img, 0, 0, s.width, s.height);++ // Draw box selection overlay+ if (ix.type === "box") {+ const x = Math.min(ix.start.x, ix.end.x);+ const y = Math.min(ix.start.y, ix.end.y);+ const w = Math.abs(ix.end.x - ix.start.x);+ const h = Math.abs(ix.end.y - ix.start.y);++ ctx.save();+ ctx.fillStyle = s.selectionColor;+ ctx.globalAlpha = s.selectionOpacity;+ ctx.fillRect(x, y, w, h);+ ctx.restore();++ ctx.strokeStyle = s.selectionColor;+ ctx.lineWidth = s.strokeWidth;+ ctx.strokeRect(x, y, w, h);+ }++ // Draw lasso selection overlay+ if (ix.type === "lasso" && ix.points.length >= 2) {+ ctx.beginPath();+ ctx.moveTo(ix.points[0].x, ix.points[0].y);+ for (let i = 1; i < ix.points.length; i++) {+ ctx.lineTo(ix.points[i].x, ix.points[i].y);+ }+ ctx.closePath();++ ctx.save();+ ctx.fillStyle = s.selectionColor;+ ctx.globalAlpha = s.selectionOpacity;+ ctx.fill();+ ctx.restore();++ ctx.strokeStyle = s.selectionColor;+ ctx.lineWidth = s.strokeWidth;+ ctx.stroke();+ }+ };++ #scheduleRedraw = (): void => {+ cancelAnimationFrame(this.#rafId);+ this.#rafId = requestAnimationFrame(this.#drawCanvas);+ };++ #getCanvasPoint = (e: PointerEvent): PixelPoint => {+ const rect = this.#canvas.getBoundingClientRect();+ const scaleX = this.#state.width / rect.width;+ const scaleY = this.#state.height / rect.height;+ return {+ x: (e.clientX - rect.left) * scaleX,+ y: (e.clientY - rect.top) * scaleY,+ };+ };++ #emitBoxSelection = (start: PixelPoint, end: PixelPoint): void => {+ const d1 = pixelToData(start, this.#state);+ const d2 = pixelToData(end, this.#state);+ this.#state.setValue({+ type: "box",+ has_selection: true,+ data: {+ x_min: Math.min(d1.x, d2.x),+ x_max: Math.max(d1.x, d2.x),+ y_min: Math.min(d1.y, d2.y),+ y_max: Math.max(d1.y, d2.y),+ },+ });+ };++ #emitLassoSelection = (points: PixelPoint[]): void => {+ if (points.length >= 3) {+ const data: [number, number][] = points.map((p) => {+ const d = pixelToData(p, this.#state);+ return [d.x, d.y];+ });+ this.#state.setValue({+ type: "lasso",+ has_selection: true,+ data,+ });+ }+ };++ #clearSelection = (): void => {+ this.#interaction = { type: "idle" };+ this.#state.setValue({ has_selection: false });+ this.#scheduleRedraw();+ };++ #hasSelection = (): boolean => {+ return this.#interaction.type !== "idle";+ };++ #isPointInSelection = (pt: PixelPoint): boolean => {+ const ix = this.#interaction;+ if (ix.type === "box") {+ return isPointInBox(pt, ix.start, ix.end);+ }+ if (ix.type === "lasso") {+ return pointInPolygon(pt, ix.points);+ }+ return false;+ };++ #updateCursor = (pt: PixelPoint): void => {+ const [axLeft, axTop, axRight, axBottom] = this.#state.axesPixelBounds;+ const inAxes =+ pt.x >= axLeft && pt.x <= axRight && pt.y >= axTop && pt.y <= axBottom;++ if (!inAxes) {+ this.#canvas.style.cursor = "default";+ return;+ }++ const ix = this.#interaction;++ // Resize handles on idle box selection+ if (ix.type === "box" && ix.action === null) {+ const handle = getResizeHandle(pt, ix.start, ix.end);+ if (handle) {+ this.#canvas.style.cursor = RESIZE_CURSORS[handle];+ return;+ }+ }++ if (this.#hasSelection() && this.#isPointInSelection(pt)) {+ this.#canvas.style.cursor = "move";+ return;+ }++ this.#canvas.style.cursor = "crosshair";+ };++ #restoreSelection = (value: SelectionValue): void => {+ if (!value || !("has_selection" in value) || !value.has_selection) {+ return;+ }++ if (value.type === "box") {+ const sel = value.data;+ const start = dataToPixel({ x: sel.x_min, y: sel.y_min }, this.#state);+ const end = dataToPixel({ x: sel.x_max, y: sel.y_max }, this.#state);+ this.#interaction = { type: "box", start, end, action: null };+ } else if (value.type === "lasso") {+ const points = value.data.map(([vx, vy]) =>+ dataToPixel({ x: vx, y: vy }, this.#state),+ );+ this.#interaction = { type: "lasso", points, action: null };+ }+ this.#scheduleRedraw();+ };++ #handlePointerDown = (e: PointerEvent): void => {+ this.#canvas.setPointerCapture(e.pointerId);+ this.#container.focus();+ const pt = this.#getCanvasPoint(e);+ const ix = this.#interaction;++ // Shift+click -> start lasso+ if (e.shiftKey) {+ this.#interaction = {+ type: "lasso",+ points: [clampToAxes(pt, this.#state)],+ action: { type: "drawing" },+ };+ this.#scheduleRedraw();+ return;+ }++ // Box exists + near edge/corner -> start resize+ if (ix.type === "box" && ix.action === null) {+ const handle = getResizeHandle(pt, ix.start, ix.end);+ if (handle) {+ const { anchor, lockX, lockY } = getResizeConfig(+ handle,+ ix.start,+ ix.end,+ );+ this.#interaction = {+ type: "box",+ start: ix.start,+ end: ix.end,+ action: { type: "resizing", anchor, lockX, lockY },+ };+ return;+ }+ }++ // Inside existing selection -> start drag+ if (this.#hasSelection() && this.#isPointInSelection(pt)) {+ if (ix.type === "box") {+ this.#interaction = {+ type: "box",+ start: ix.start,+ end: ix.end,+ action: { type: "dragging", origin: pt },+ };+ } else if (ix.type === "lasso") {+ this.#interaction = {+ type: "lasso",+ points: ix.points,+ action: { type: "dragging", origin: pt },+ };+ }+ return;+ }++ // Outside selection with existing one -> clear, then start new box+ if (this.#hasSelection()) {+ this.#clearSelection();+ }++ // Start new box selection+ const clamped = clampToAxes(pt, this.#state);+ this.#interaction = {+ type: "box",+ start: clamped,+ end: clamped,+ action: { type: "drawing" },+ };+ this.#scheduleRedraw();+ };++ #handlePointerMove = (e: PointerEvent): void => {+ const pt = this.#getCanvasPoint(e);+ const ix = this.#interaction;+ const s = this.#state;++ // No active action -> just update cursor+ if (ix.type === "idle" || ix.action === null) {+ this.#updateCursor(pt);+ return;+ }++ // Lasso drawing: append clamped point+ if (ix.type === "lasso" && ix.action.type === "drawing") {+ ix.points.push(clampToAxes(pt, s));+ this.#scheduleRedraw();+ return;+ }++ // Box drawing: update end point+ if (ix.type === "box" && ix.action.type === "drawing") {+ const clamped = clampToAxes(pt, s);+ ix.end = clamped;+ this.#scheduleRedraw();+ if (!s.debounce) {+ this.#emitBoxSelection(ix.start, clamped);+ }+ return;+ }++ // Box resizing: recompute box from anchor + clamped mouse+ if (ix.type === "box" && ix.action.type === "resizing") {+ const clamped = clampToAxes(pt, s);+ const { anchor, lockX, lockY } = ix.action;+ ix.start = anchor;+ ix.end = { x: lockX ?? clamped.x, y: lockY ?? clamped.y };+ this.#scheduleRedraw();+ if (!s.debounce) {+ this.#emitBoxSelection(ix.start, ix.end);+ }+ return;+ }++ // Box dragging+ if (ix.type === "box" && ix.action.type === "dragging") {+ const [axLeft, axTop, axRight, axBottom] = s.axesPixelBounds;+ let dx = pt.x - ix.action.origin.x;+ let dy = pt.y - ix.action.origin.y;+ ix.action.origin = pt;++ const minX = Math.min(ix.start.x, ix.end.x);+ const maxX = Math.max(ix.start.x, ix.end.x);+ const minY = Math.min(ix.start.y, ix.end.y);+ const maxY = Math.max(ix.start.y, ix.end.y);+ dx = Math.max(axLeft - minX, Math.min(axRight - maxX, dx));+ dy = Math.max(axTop - minY, Math.min(axBottom - maxY, dy));+ ix.start = { x: ix.start.x + dx, y: ix.start.y + dy };+ ix.end = { x: ix.end.x + dx, y: ix.end.y + dy };+ this.#scheduleRedraw();+ if (!s.debounce) {+ this.#emitBoxSelection(ix.start, ix.end);+ }+ return;+ }++ // Lasso dragging+ if (ix.type === "lasso" && ix.action.type === "dragging") {+ const [axLeft, axTop, axRight, axBottom] = s.axesPixelBounds;+ let dx = pt.x - ix.action.origin.x;+ let dy = pt.y - ix.action.origin.y;+ ix.action.origin = pt;++ let lMinX = Number.POSITIVE_INFINITY;+ let lMaxX = Number.NEGATIVE_INFINITY;+ let lMinY = Number.POSITIVE_INFINITY;+ let lMaxY = Number.NEGATIVE_INFINITY;+ for (const lp of ix.points) {+ if (lp.x < lMinX) {+ lMinX = lp.x;+ }+ if (lp.x > lMaxX) {+ lMaxX = lp.x;+ }+ if (lp.y < lMinY) {+ lMinY = lp.y;+ }+ if (lp.y > lMaxY) {+ lMaxY = lp.y;+ }+ }+ dx = Math.max(axLeft - lMinX, Math.min(axRight - lMaxX, dx));+ dy = Math.max(axTop - lMinY, Math.min(axBottom - lMaxY, dy));+ for (let i = 0; i < ix.points.length; i++) {+ ix.points[i] = {+ x: ix.points[i].x + dx,+ y: ix.points[i].y + dy,+ };+ }+ this.#scheduleRedraw();+ if (!s.debounce) {+ this.#emitLassoSelection(ix.points);+ }+ }+ };++ #handlePointerUp = (e: PointerEvent): void => {+ this.#canvas.releasePointerCapture(e.pointerId);++ const ix = this.#interaction;+ const s = this.#state;++ // Lasso drawing complete+ if (ix.type === "lasso" && ix.action?.type === "drawing") {+ if (ix.points.length >= 3) {+ ix.action = null;+ this.#emitLassoSelection(ix.points);+ } else {+ this.#interaction = { type: "idle" };+ this.#state.setValue({ has_selection: false });+ }+ this.#scheduleRedraw();+ return;+ }++ // Lasso dragging complete+ if (ix.type === "lasso" && ix.action?.type === "dragging") {+ ix.action = null;+ if (s.debounce) {+ this.#emitLassoSelection(ix.points);+ }+ return;+ }++ // Box action complete (drawing, dragging, or resizing)+ if (ix.type === "box" && ix.action !== null) {+ ix.action = null;+ if (s.debounce) {+ this.#emitBoxSelection(ix.start, ix.end);+ }+ }+ };++ #handleKeyDown = (e: KeyboardEvent): void => {+ if (e.key === "Escape") {+ const ix = this.#interaction;+ if (ix.type === "idle") {+ return;+ }++ // During initial drawing -> cancel without emitting+ if (ix.action?.type === "drawing") {+ this.#interaction = { type: "idle" };+ this.#scheduleRedraw();+ } else {+ // Completed selection, dragging, or resizing -> clear+ this.#clearSelection();+ }+ }+ };+}diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.tsindex 6edc406c3e..aea158f4a4 100644--- a/frontend/src/plugins/plugins.ts+++ b/frontend/src/plugins/plugins.ts@@ -25,6 +25,7 @@ import { FormPlugin } from "./impl/FormPlugin";import { MatrixPlugin } from "./impl/MatrixPlugin";import { MicrophonePlugin } from "./impl/MicrophonePlugin";import { MultiselectPlugin } from "./impl/MultiselectPlugin";+import { MatplotlibPlugin } from "./impl/matplotlib/MatplotlibPlugin";import { NumberPlugin } from "./impl/NumberPlugin";import { PanelPlugin } from "./impl/panel/PanelPlugin";import { PlotlyPlugin } from "./impl/plotly/PlotlyPlugin";@@ -81,6 +82,7 @@ export const UI_PLUGINS: IPlugin<any, unknown>[] = [new TextAreaPlugin(),new TextInputPlugin(),new VegaPlugin(),+ new MatplotlibPlugin(),new PlotlyPlugin(),ChatPlugin,DataExplorerPlugin,diff --git a/marimo/_plugins/ui/__init__.py b/marimo/_plugins/ui/__init__.pyindex b65d796e8b..a350597843 100644--- a/marimo/_plugins/ui/__init__.py+++ b/marimo/_plugins/ui/__init__.py@@ -25,6 +25,7 @@ __all__ = ["file_browser","file","form",+ "matplotlib","matrix","microphone","multiselect",@@ -80,6 +81,7 @@ from marimo._plugins.ui._impl.input import ()from marimo._plugins.ui._impl.matrix import matrixfrom marimo._plugins.ui._impl.microphone import microphone+from marimo._plugins.ui._impl.mpl import matplotlibfrom marimo._plugins.ui._impl.plotly import plotlyfrom marimo._plugins.ui._impl.refresh import refreshfrom marimo._plugins.ui._impl.run_button import run_buttondiff --git a/marimo/_plugins/ui/_impl/mpl.py b/marimo/_plugins/ui/_impl/mpl.pynew file mode 100644index 0000000000..d4ad978404--- /dev/null+++ b/marimo/_plugins/ui/_impl/mpl.py@@ -0,0 +1,277 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import base64+import io+from dataclasses import dataclass+from typing import (+ TYPE_CHECKING,+ Final,+ Protocol,+ cast,+)++from marimo._dependencies.dependencies import DependencyManager+from marimo._output.rich_help import mddoc+from marimo._plugins.core.web_component import JSONType+from marimo._plugins.ui._core.ui_element import UIElement++if TYPE_CHECKING:+ import numpy as np+ from matplotlib.axes import Axes # type: ignore[import-untyped]+ from matplotlib.figure import Figure # type: ignore[import-untyped]+ from numpy.typing import ArrayLike, NDArray+++class MatplotlibSelection(Protocol):+ def get_mask(self, x: ArrayLike, y: ArrayLike) -> NDArray[np.bool_]: ...+++@dataclass(frozen=True)+class BoxSelection:+ """A rectangular box selection on a matplotlib plot.++ Attributes:+ x_min: Left boundary of the selection.+ x_max: Right boundary of the selection.+ y_min: Bottom boundary of the selection.+ y_max: Top boundary of the selection.+ """++ x_min: float+ x_max: float+ y_min: float+ y_max: float++ def get_mask(self, x: ArrayLike, y: ArrayLike) -> NDArray[np.bool_]:+ """Get a boolean mask for points within this selection.++ Args:+ x: Array-like of x-coordinates.+ y: Array-like of y-coordinates.++ Returns:+ A boolean numpy array where `True` indicates the point is+ within the selection.+ """+ import numpy as np++ 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)+ )+++@dataclass(frozen=True)+class LassoSelection:+ """A freehand polygon (lasso) selection on a matplotlib plot.++ Attributes:+ vertices: The polygon vertices as a tuple of (x, y) pairs.+ """++ vertices: tuple[tuple[float, float], ...]++ def get_mask(self, x: ArrayLike, y: ArrayLike) -> NDArray[np.bool_]:+ """Get a boolean mask for points within this selection.++ Args:+ x: Array-like of x-coordinates.+ y: Array-like of y-coordinates.++ Returns:+ A boolean numpy array where `True` indicates the point is+ within the selection.+ """+ import numpy as np+ from matplotlib.path import Path # type: ignore[import-untyped]++ 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)+++@dataclass(frozen=True)+class EmptySelection:+ """Sentinel representing no selection.++ Returned by `mo.ui.matplotlib.value` when nothing is selected.++ Behaves like a selection with no points, and evaluates to False+ when coerced as a bool.+ """++ def get_mask(self, x: ArrayLike, y: ArrayLike) -> NDArray[np.bool_]: # noqa: ARG002+ """Return an all-``False`` mask.++ Args:+ x: Array-like of x-coordinates.+ y: Array-like of y-coordinates.++ Returns:+ A boolean numpy array of all ``False``.+ """+ import numpy as np++ return np.zeros(len(np.asarray(x)), dtype=bool)++ def __bool__(self) -> bool:+ return False+++def _figure_pixel_size(figure: Figure) -> tuple[float, float]:+ """Get figure dimensions in pixels."""+ dpi = figure.get_dpi()+ width_in, height_in = figure.get_size_inches()+ return width_in * dpi, height_in * dpi+++def _figure_to_base64(figure: Figure) -> str:+ """Render a matplotlib figure to a base64-encoded PNG data URL."""+ buf = io.BytesIO()+ figure.savefig(buf, format="png")+ buf.seek(0)+ encoded = base64.b64encode(buf.read()).decode("utf-8")+ buf.close()+ return f"data:image/png;base64,{encoded}"+++@mddoc+class matplotlib(UIElement[dict[str, JSONType], MatplotlibSelection]):+ """Make reactive selections on matplotlib plots.++ Use `mo.ui.matplotlib` to make matplotlib plots interactive: draw a box+ selection or a freehand lasso selection on the frontend, then use the+ selection geometry in Python to filter your data.++ The figure is rendered as a static image with an interactive selection+ overlay:++ - click and drag for box selection;+ - hold the `Shift` key and drag for lasso selection.++ Example:+ ```python+ import matplotlib.pyplot as plt+ import marimo as mo+ import numpy as np++ x = np.arange(5)+ y = x**2+ plt.scatter(x=x, y=y)+ ax = mo.ui.matplotlib(plt.gca())+ ax+ ```++ ```python+ # Filter data using the selection+ mask = ax.value.get_mask(x, y)+ selected_x, selected_y = x[mask], y[mask]+ ```++ ```python+ # Check if anything is selected+ if ax.value:+ print("Data has been selected")+ ```++ Attributes:+ value: The selected data, with `get_mask(x, y)` returning a+ mask array corresponding to the selection.++ Args:+ axes: A matplotlib `Axes` object. The full figure is rendered,+ but selections map to this axes' coordinate space.+ debounce: If `True`, the selection is only sent to Python on+ mouse-up. If `False` (the default), it streams while dragging.+ """++ name: Final[str] = "marimo-matplotlib"++ def __init__(self, axes: Axes, *, debounce: bool = False) -> None:+ DependencyManager.matplotlib.require("for `mo.ui.matplotlib`")++ from matplotlib.figure import Figure # type: ignore[import-untyped]++ figure = axes.get_figure()+ if not isinstance(figure, Figure):+ raise ValueError("Axes must be attached to a figure.")+ self._ax: Axes = axes++ fig_width_px, fig_height_px = _figure_pixel_size(figure)++ # Axes pixel bounds: [left, top, right, bottom]+ # relative to the full figure image+ bbox = axes.get_position()+ axes_pixel_bounds: list[float] = [+ bbox.x0 * fig_width_px, # left+ (1 - bbox.y1) * fig_height_px, # top+ bbox.x1 * fig_width_px, # right+ (1 - bbox.y0) * fig_height_px, # bottom+ ]++ _SUPPORTED_SCALES = ("linear", "log")+ x_scale = axes.get_xscale()+ y_scale = axes.get_yscale()+ if x_scale not in _SUPPORTED_SCALES:+ raise ValueError(+ f"Unsupported x-axis scale {x_scale!r}. "+ f"mo.ui.matplotlib supports: {', '.join(_SUPPORTED_SCALES)}."+ )+ if y_scale not in _SUPPORTED_SCALES:+ raise ValueError(+ f"Unsupported y-axis scale {y_scale!r}. "+ f"mo.ui.matplotlib supports: {', '.join(_SUPPORTED_SCALES)}."+ )++ super().__init__(+ component_name=matplotlib.name,+ initial_value={},+ label="",+ args={+ "chart-base64": _figure_to_base64(figure),+ "x-bounds": list(axes.get_xlim()),+ "y-bounds": list(axes.get_ylim()),+ "axes-pixel-bounds": axes_pixel_bounds,+ "width": fig_width_px,+ "height": fig_height_px,+ "debounce": debounce,+ "x-scale": x_scale,+ "y-scale": y_scale,+ },+ on_change=None,+ )++ @property+ def axes(self) -> Axes:+ """The associated matplotlib Axes object."""+ return self._ax++ def _convert_value(+ self, value: dict[str, JSONType]+ ) -> MatplotlibSelection:+ if not value or not value.get("has_selection"):+ return EmptySelection()+ sel_type = value.get("type")+ data = value.get("data")++ if sel_type == "box":+ data = cast(dict[str, float], data)+ return BoxSelection(+ x_min=float(data["x_min"]),+ x_max=float(data["x_max"]),+ y_min=float(data["y_min"]),+ y_max=float(data["y_max"]),+ )+ if sel_type == "lasso":+ data = cast(list[list[float]], data)+ return LassoSelection(+ vertices=tuple((float(v[0]), float(v[1])) for v in data),+ )+ return EmptySelection()diff --git a/marimo/_smoke_tests/pandas/dates.py b/marimo/_smoke_tests/pandas_smoke_tests/dates.pysimilarity index 100%rename from marimo/_smoke_tests/pandas/dates.pyrename to marimo/_smoke_tests/pandas_smoke_tests/dates.pydiff --git a/marimo/_smoke_tests/pandas/datetime_index_columns.py b/marimo/_smoke_tests/pandas_smoke_tests/datetime_index_columns.pysimilarity index 100%rename from marimo/_smoke_tests/pandas/datetime_index_columns.pyrename to marimo/_smoke_tests/pandas_smoke_tests/datetime_index_columns.pydiff --git a/marimo/_smoke_tests/pandas/pandas_multi_idx.py b/marimo/_smoke_tests/pandas_smoke_tests/pandas_multi_idx.pysimilarity index 100%rename from marimo/_smoke_tests/pandas/pandas_multi_idx.pyrename to marimo/_smoke_tests/pandas_smoke_tests/pandas_multi_idx.pydiff --git a/marimo/_smoke_tests/pandas/pandas_nan.py b/marimo/_smoke_tests/pandas_smoke_tests/pandas_nan.pysimilarity index 100%rename from marimo/_smoke_tests/pandas/pandas_nan.pyrename to marimo/_smoke_tests/pandas_smoke_tests/pandas_nan.pydiff --git a/marimo/_smoke_tests/pandas/pandas_subplots.py b/marimo/_smoke_tests/pandas_smoke_tests/pandas_subplots.pysimilarity index 100%rename from marimo/_smoke_tests/pandas/pandas_subplots.pyrename to marimo/_smoke_tests/pandas_smoke_tests/pandas_subplots.pydiff --git a/marimo/_smoke_tests/ui_matplotlib.py b/marimo/_smoke_tests/ui_matplotlib.pynew file mode 100644index 0000000000..5dfd744eea--- /dev/null+++ b/marimo/_smoke_tests/ui_matplotlib.py@@ -0,0 +1,121 @@+import marimo++__generated_with = "0.19.11"+app = marimo.App()+++def _():+ import marimo as mo++ import matplotlib.pyplot as plt+ import pymde+ import numpy as np++ return mo, np, plt, pymde+++def _(pymde):+ mnist = pymde.datasets.MNIST()+ return (mnist,)+++def _(mnist, mo, pymde):+ @mo.persistent_cache+ def compute_embedding():+ return pymde.preserve_neighbors(+ mnist.data, constraint=pymde.Standardized(), verbose=True+ ).embed(verbose=True)++ return (compute_embedding,)+++def _(compute_embedding):+ embedding = compute_embedding()+ return (embedding,)+++def _(embedding, mnist, plt):+ x = embedding[:, 0]+ y = embedding[:, 1]++ plt.scatter(x=x, y=y, s=0.05, cmap="Spectral", c=mnist.attributes["digits"])+ plt.yticks([-2, 0, 2])+ plt.xticks([-2, 0, 2])+ plt.ylim(-2.5, 2.5)+ plt.xlim(-2.5, 2.5)+ ax = plt.gca()+ return ax, x, y+++def _(ax, mo):+ fig = mo.ui.matplotlib(ax)+ fig+ return (fig,)+++def _(embedding, fig, x, y):+ embedding[fig.value.get_mask(x, y)]+ return+++def _(fig):+ fig.value if fig.value else "No selection!"+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## Log-scale axes test+ """)+ return+++def _(np, plt):+ # Exponentially distributed data for log-scale testing+ np.random.seed(42)+ log_x = np.random.lognormal(mean=2, sigma=1, size=500)+ log_y = np.random.lognormal(mean=3, sigma=0.8, size=500)++ plt.figure()+ plt.scatter(log_x, log_y, s=10, alpha=0.6)+ plt.yscale("log")+ plt.xlabel("X (linear scale)")+ plt.ylabel("Y (log scale)")+ plt.title("Log-scale scatter")+ log_ax = plt.gca()+ return log_ax, log_x, log_y+++def _(log_ax, mo):+ log_fig = mo.ui.matplotlib(log_ax)+ log_fig+ return (log_fig,)+++def _(log_fig, log_x, log_y, np):+ _m = log_fig.value.get_mask(log_x, log_y)+ log_x_sel, log_y_sel = log_x[_m], log_y[_m]+ np.column_stack([log_x_sel, log_y_sel])+ return+++def _(log_fig):+ log_fig.value if log_fig.value else "No selection!"+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_tutorials/plots.py b/marimo/_tutorials/plots.pyindex 69e88f7600..d655711d2c 100644--- a/marimo/_tutorials/plots.py+++ b/marimo/_tutorials/plots.py@@ -10,7 +10,7 @@import marimo-__generated_with = "0.19.7"+__generated_with = "0.19.11"app = marimo.App()@@ -203,6 +203,35 @@ def _(exponent, mo, plot_power):return[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ### Reactive selections with `mo.ui.matplotlib`++ Wrap a matplotlib `Axes` in `mo.ui.matplotlib` to let users select+ data with box selections (click-drag) or lasso selections+ (shift-drag). Use `fig.value.get_mask(x, y)` to get a boolean mask+ of the selected points.+ """)+ return+++def _(mo, np, plt):+ XY = np.random.randn(1000, 1000)+ plt.scatter(XY[:, 0], XY[:, 1], s=1)+ scatter_fig = mo.ui.matplotlib(plt.gca())+ scatter_fig+ return XY, scatter_fig+++def _(XY, scatter_fig):+ _mask = scatter_fig.value.get_mask(XY[:, 0], XY[:, 1])+ XY[_mask]+ return++@app.cell(hide_code=True)def _(mo):mo.md("""diff --git a/tests/_plugins/ui/_impl/test_ui_mpl.py b/tests/_plugins/ui/_impl/test_ui_mpl.pynew file mode 100644index 0000000000..08a0e99d45--- /dev/null+++ b/tests/_plugins/ui/_impl/test_ui_mpl.py@@ -0,0 +1,267 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++from typing import Any++import matplotlib.pyplot as plt # noqa: E402+import pytest++from marimo._plugins.ui._impl.mpl import ( # noqa: E402+ BoxSelection,+ EmptySelection,+ LassoSelection,+ _figure_pixel_size,+ _figure_to_base64,+ matplotlib,+)++mpl = pytest.importorskip("matplotlib")+mpl.use("Agg") # Non-interactive backend for testing++np = pytest.importorskip("numpy")+++# ============================================================================+# Constructor tests+# ============================================================================+++def _make_scatter_ax() -> Any:+ fig, ax = plt.subplots()+ ax.scatter([1, 2, 3, 4, 5], [2, 4, 1, 5, 3])+ plt.close(fig)+ return ax+++def test_basic_construction() -> None:+ ax = _make_scatter_ax()+ fig = matplotlib(ax)++ assert fig is not None+ assert isinstance(fig.value, EmptySelection)+ assert not fig.value+++def test_construction_no_figure_raises() -> None:+ fig = plt.figure()+ ax = fig.add_subplot(111)+ ax.scatter([1, 2, 3], [4, 5, 6])+ # Remove ax from figure to simulate detached axes+ # Actually, axes are always attached. Test empty figure differently.+ plt.close(fig)+ # We can still construct since ax.get_figure() returns the figure+ fig = matplotlib(ax)+ assert fig is not None+++def test_unsupported_scale_raises() -> None:+ fig, ax = plt.subplots()+ ax.scatter([1, 2, 3], [4, 5, 6])+ ax.set_xscale("symlog")+ plt.close(fig)+ with pytest.raises(ValueError, match="Unsupported x-axis scale"):+ matplotlib(ax)+++def test_unsupported_yscale_raises() -> None:+ fig, ax = plt.subplots()+ ax.scatter([1, 2, 3], [4, 5, 6])+ ax.set_yscale("logit")+ plt.close(fig)+ with pytest.raises(ValueError, match="Unsupported y-axis scale"):+ matplotlib(ax)+++def test_construction_args() -> None:+ ax = _make_scatter_ax()+ fig = matplotlib(ax)++ args = fig._component_args+ assert "chart-base64" in args+ assert "x-bounds" in args+ assert "y-bounds" in args+ assert "axes-pixel-bounds" in args+ assert "width" in args+ assert "height" in args++ assert isinstance(args["chart-base64"], str)+ assert args["chart-base64"].startswith("data:image/png;base64,")+ assert len(args["x-bounds"]) == 2+ assert len(args["y-bounds"]) == 2+ assert len(args["axes-pixel-bounds"]) == 4+ assert args["width"] > 0+ assert args["height"] > 0++ # Style args should NOT be present (removed from public API)+ assert "selection-color" not in args+ assert "selection-opacity" not in args+ assert "stroke-width" not in args+++# ============================================================================+# _convert_value tests+# ============================================================================+++def test_convert_value_empty() -> None:+ ax = _make_scatter_ax()+ fig = matplotlib(ax)+ result = fig._convert_value({})+ assert isinstance(result, EmptySelection)+ assert not result+++def test_convert_value_no_selection() -> None:+ ax = _make_scatter_ax()+ fig = matplotlib(ax)+ result = fig._convert_value({"has_selection": False})+ assert isinstance(result, EmptySelection)+ assert not result+++def test_convert_value_box() -> None:+ ax = _make_scatter_ax()+ fig = matplotlib(ax)+ value = {+ "type": "box",+ "has_selection": True,+ "data": {+ "x_min": 1.0,+ "x_max": 3.0,+ "y_min": 2.0,+ "y_max": 4.0,+ },+ }+ result = fig._convert_value(value)+ assert isinstance(result, BoxSelection)+ assert result.x_min == 1.0+ assert result.x_max == 3.0+ assert result.y_min == 2.0+ assert result.y_max == 4.0+++def test_convert_value_lasso() -> None:+ ax = _make_scatter_ax()+ fig = matplotlib(ax)+ value = {+ "type": "lasso",+ "has_selection": True,+ "data": [[1.0, 2.0], [3.0, 4.0], [5.0, 2.0]],+ }+ result = fig._convert_value(value)+ assert isinstance(result, LassoSelection)+ assert result.vertices == ((1.0, 2.0), (3.0, 4.0), (5.0, 2.0))+++# ============================================================================+# EmptySelection tests+# ============================================================================+++def test_empty_selection_is_falsy() -> None:+ sel = EmptySelection()+ assert not sel+ assert bool(sel) is False+++def test_empty_selection_get_mask() -> None:+ sel = EmptySelection()+ x = np.array([1, 2, 3, 4, 5])+ y = np.array([2, 4, 1, 5, 3])+ mask = sel.get_mask(x, y)+ assert mask.sum() == 0+ assert len(mask) == 5+++def test_empty_selection_frozen() -> None:+ sel = EmptySelection()+ with pytest.raises(AttributeError):+ sel.foo = 1 # type: ignore[attr-defined]+++def test_value_get_mask_before_selection() -> None:+ """fig.value.get_mask() should work even with no selection."""+ ax = _make_scatter_ax()+ fig = matplotlib(ax)+ x = np.array([1, 2, 3])+ y = np.array([4, 5, 6])+ mask = fig.value.get_mask(x, y)+ assert mask.sum() == 0+++# ============================================================================+# BoxSelection dataclass tests+# ============================================================================+++def test_box_selection_frozen() -> None:+ sel = BoxSelection(x_min=1.0, x_max=3.0, y_min=2.0, y_max=4.0)+ with pytest.raises(AttributeError):+ sel.x_min = 5.0 # type: ignore[misc]+++def test_box_selection_get_mask() -> None:+ sel = BoxSelection(x_min=1.5, x_max=3.5, y_min=1.5, y_max=4.5)+ x = np.array([1, 2, 3, 4, 5])+ y = np.array([2, 4, 1, 5, 3])+ mask = sel.get_mask(x, y)+ assert mask[1] is np.True_ # (2, 4) in range+ assert not mask[2] # (3, 1) y out of range+ assert not mask[0] # (1, 2) x out of range+++# ============================================================================+# LassoSelection dataclass tests+# ============================================================================+++def test_lasso_selection_frozen() -> None:+ sel = LassoSelection(vertices=((0.0, 0.0), (4.0, 0.0), (2.0, 3.0)))+ with pytest.raises(AttributeError):+ sel.vertices = () # type: ignore[misc]+++def test_lasso_selection_get_mask() -> None:+ sel = LassoSelection(vertices=((0.0, 0.0), (10.0, 0.0), (5.0, 10.0)))+ x = np.array([5.0, 0.0, 10.0, 5.0])+ y = np.array([1.0, 5.0, 5.0, 5.0])+ mask = sel.get_mask(x, y)+ assert mask[0] # (5, 1) inside+ assert not mask[1] # (0, 5) outside+ assert not mask[2] # (10, 5) outside+ assert mask[3] # (5, 5) inside+++# ============================================================================+# Helper function tests+# ============================================================================+++def test_figure_pixel_size() -> None:+ fig, ax = plt.subplots()+ ax.scatter([1, 2, 3], [4, 5, 6])+ plt.close(fig)+ w, h = _figure_pixel_size(fig)+ assert w > 0+ assert h > 0+++def test_figure_to_base64() -> None:+ fig, ax = plt.subplots()+ ax.scatter([1, 2, 3], [4, 5, 6])+ plt.close(fig)+ result = _figure_to_base64(fig)+ assert result.startswith("data:image/png;base64,")+ assert len(result) > 50+++# ============================================================================+# HTML output tests+# ============================================================================+++def test_html_contains_tag() -> None:+ ax = _make_scatter_ax()+ fig = matplotlib(ax)+ html = fig.text+ assert "marimo-matplotlib" in htmldiff --git a/tests/snapshots/api.txt b/tests/snapshots/api.txtindex 78ac712cc2..6e2d57d91a 100644--- a/tests/snapshots/api.txt+++ b/tests/snapshots/api.txt@@ -104,6 +104,7 @@ uifilefile_browserform+ matplotlibmatrixmicrophonemultiselect@@ -125,4 +126,4 @@ videovstackwatchdirectory- file\ No newline at end of file+ file