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: plotly shapes not clearing when removed from figure (#7974)
Myles Scolnick511fc44b141d
diff --git a/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx b/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsxindex 70a1188dc0..2efe311e65 100644--- a/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx+++ b/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx@@ -7,15 +7,14 @@ import { Logger } from "@/utils/Logger";import "./plotly.css";import "./mapbox.css";-import { usePrevious } from "@uidotdev/usehooks";-import { isEqual, pick, set } from "lodash-es";-import { type JSX, lazy, memo, useEffect, useMemo, useState } from "react";+import { pick, set } from "lodash-es";+import { type JSX, lazy, memo, useMemo } from "react";import useEvent from "react-use-event-hook";import { useDeepCompareMemoize } from "@/hooks/useDeepCompareMemoize";import { useScript } from "@/hooks/useScript";import { Arrays } from "@/utils/arrays";-import { Objects } from "@/utils/objects";import { createParser, type PlotlyTemplateParser } from "./parse-from-template";+import { usePlotlyLayout } from "./usePlotlyLayout";interface Data {figure: Figure;@@ -80,18 +79,6 @@ export const LazyPlot = lazy(() =>}),);-function initialLayout(figure: Figure): Partial<Plotly.Layout> {- // Enable autosize if width is not specified- const shouldAutoSize = figure.layout.width === undefined;- return {- autosize: shouldAutoSize,- dragmode: "select",- height: 540,- // Prioritize user's config- ...figure.layout,- };-}-const SUNBURST_DATA_KEYS: (keyof Plotly.SunburstPlotDatum)[] = ["color","curveNumber",@@ -111,38 +98,20 @@ const TREE_MAP_DATA_KEYS = SUNBURST_DATA_KEYS;export const PlotlyComponent = memo(({ figure: originalFigure, value, setValue, config }: PlotlyPluginProps) => {- const [figure, setFigure] = useState(() => {- // We clone the figure since Plotly mutates the figure in place- return structuredClone(originalFigure);- });-// Used for rendering LaTeX. TODO: Serve this library from Marimoconst scriptStatus = useScript("https://cdn.jsdelivr.net/npm/[email protected]/es5/tex-mml-svg.min.js",);const isScriptLoaded = scriptStatus === "ready";- useEffect(() => {- const nextFigure = structuredClone(originalFigure);- setFigure(nextFigure);- setLayout((prev) => ({- ...initialLayout(nextFigure),- ...prev,- }));- }, [originalFigure, isScriptLoaded]);-- const [layout, setLayout] = useState<Partial<Plotly.Layout>>(() => {- return {- ...initialLayout(figure),- // Override with persisted values (dragmode, xaxis, yaxis)- ...value,- };+ const { figure, layout, handleReset } = usePlotlyLayout({+ originalFigure,+ initialValue: value,+ isScriptLoaded,});- const handleReset = useEvent(() => {- const nextFigure = structuredClone(originalFigure);- setFigure(nextFigure);- setLayout(initialLayout(nextFigure));+ const handleResetWithClear = useEvent(() => {+ handleReset();setValue({});});@@ -163,37 +132,13 @@ export const PlotlyComponent = memo(<path d="M3 3v5h5" /></svg>`,},- click: handleReset,+ click: handleResetWithClear,},],// Prioritize user's config...configMemo,};- }, [handleReset, configMemo]);-- const prevFigure = usePrevious(figure) ?? figure;-- useEffect(() => {- const omitKeys = new Set<keyof Plotly.Layout>([- "autosize",- "dragmode",- "xaxis",- "yaxis",- ]);-- // If the key was updated externally (e.g. can be specifically passed in the config)- // then we need to update the layout- for (const key of omitKeys) {- if (!isEqual(figure.layout[key], prevFigure.layout[key])) {- omitKeys.delete(key);- }- }-- // Update layout when figure.layout changes- // Omit keys that we don't want to override- const layout = Objects.omit(figure.layout, omitKeys);- setLayout((prev) => ({ ...prev, ...layout }));- }, [figure.layout, prevFigure.layout]);+ }, [handleResetWithClear, configMemo]);return (<LazyPlotdiff --git a/frontend/src/plugins/impl/plotly/__tests__/usePlotlyLayout.test.ts b/frontend/src/plugins/impl/plotly/__tests__/usePlotlyLayout.test.tsnew file mode 100644index 0000000000..cdd143979f--- /dev/null+++ b/frontend/src/plugins/impl/plotly/__tests__/usePlotlyLayout.test.ts@@ -0,0 +1,113 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type { Figure } from "react-plotly.js";+import { describe, expect, it } from "vitest";+import {+ computeLayoutOnFigureChange,+ computeLayoutUpdate,+ computeOmitKeys,+ createInitialLayout,+} from "../usePlotlyLayout";++function createFigure(layoutOverrides: Partial<Plotly.Layout> = {}): Figure {+ return {+ data: [],+ layout: { ...layoutOverrides } as Plotly.Layout,+ frames: null,+ };+}++describe("createInitialLayout", () => {+ it("sets defaults and merges figure layout", () => {+ const figure = createFigure({ title: { text: "Test" }, dragmode: "zoom" });+ const result = createInitialLayout(figure);++ expect(result.autosize).toBe(true);+ expect(result.height).toBe(540);+ expect(result.dragmode).toBe("zoom"); // figure overrides default+ expect(result.title).toEqual({ text: "Test" });+ });++ it("disables autosize when width is specified", () => {+ const result = createInitialLayout(createFigure({ width: 800 }));+ expect(result.autosize).toBe(false);+ });+});++describe("computeLayoutOnFigureChange", () => {+ it("preserves only dragmode/xaxis/yaxis from previous layout (#7964)", () => {+ const nextFigure = createFigure({ title: { text: "New" } });+ const prevLayout: Partial<Plotly.Layout> = {+ dragmode: "zoom",+ xaxis: { range: [0, 10] },+ yaxis: { range: [0, 100] },+ shapes: [{ type: "rect", x0: 0, x1: 1, y0: 0, y1: 1 }],+ annotations: [{ text: "Old", x: 0, y: 0 }],+ };++ const result = computeLayoutOnFigureChange(nextFigure, prevLayout);++ // Preserved from prev+ expect(result.dragmode).toBe("zoom");+ expect(result.xaxis).toEqual({ range: [0, 10] });+ expect(result.yaxis).toEqual({ range: [0, 100] });+ // From new figure+ expect(result.title).toEqual({ text: "New" });+ // NOT preserved (the bug fix)+ expect(result.shapes).toBeUndefined();+ expect(result.annotations).toBeUndefined();+ });++ it("uses shapes from new figure, not previous layout", () => {+ const nextFigure = createFigure({+ shapes: [{ type: "circle", x0: 0, x1: 1, y0: 0, y1: 1 }],+ });+ const prevLayout: Partial<Plotly.Layout> = {+ shapes: [{ type: "rect", x0: 0, x1: 1, y0: 0, y1: 1 }],+ };++ const result = computeLayoutOnFigureChange(nextFigure, prevLayout);++ expect(result.shapes).toHaveLength(1);+ expect(result.shapes?.[0].type).toBe("circle");+ });+});++describe("computeOmitKeys", () => {+ it("omits user-interaction keys unless they changed in figure", () => {+ const unchanged = computeOmitKeys({}, {});+ expect([...unchanged]).toEqual(+ expect.arrayContaining(["autosize", "dragmode", "xaxis", "yaxis"]),+ );++ const changed = computeOmitKeys(+ { dragmode: "zoom", xaxis: { range: [0, 10] } },+ { dragmode: "select", xaxis: { range: [0, 5] } },+ );+ expect(changed.has("dragmode")).toBe(false);+ expect(changed.has("xaxis")).toBe(false);+ expect(changed.has("autosize")).toBe(true);+ });+});++describe("computeLayoutUpdate", () => {+ it("merges figure layout while respecting omit keys", () => {+ // dragmode unchanged in figure -> preserve prev layout's dragmode+ const result1 = computeLayoutUpdate(+ { dragmode: "pan", title: { text: "New" } },+ { dragmode: "pan" },+ { dragmode: "zoom", height: 400 },+ );+ expect(result1.dragmode).toBe("zoom");+ expect(result1.title).toEqual({ text: "New" });+ expect(result1.height).toBe(400);++ // dragmode changed in figure -> use figure's dragmode+ const result2 = computeLayoutUpdate(+ { dragmode: "pan" },+ { dragmode: "select" },+ { dragmode: "zoom" },+ );+ expect(result2.dragmode).toBe("pan");+ });+});diff --git a/frontend/src/plugins/impl/plotly/usePlotlyLayout.ts b/frontend/src/plugins/impl/plotly/usePlotlyLayout.tsnew file mode 100644index 0000000000..c7a9e32a69--- /dev/null+++ b/frontend/src/plugins/impl/plotly/usePlotlyLayout.ts@@ -0,0 +1,163 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { usePrevious } from "@uidotdev/usehooks";+import { isEqual, pick } from "lodash-es";+import { useEffect, useState } from "react";+import type { Figure } from "react-plotly.js";+import { Objects } from "@/utils/objects";++/**+ * Keys that are preserved across figure updates when set by user interaction.+ * These include dragmode and axis settings that users may adjust.+ */+export const PERSISTED_LAYOUT_KEYS = ["dragmode", "xaxis", "yaxis"] as const;++/**+ * Keys that are omitted from layout updates unless they changed in the figure.+ * This prevents overwriting user interactions like zoom/pan.+ */+export const LAYOUT_OMIT_KEYS: (keyof Plotly.Layout)[] = [+ "autosize",+ "dragmode",+ "xaxis",+ "yaxis",+];++/**+ * Creates the initial layout for a Plotly figure with sensible defaults.+ */+export function createInitialLayout(figure: Figure): Partial<Plotly.Layout> {+ // Enable autosize if width is not specified+ const shouldAutoSize = figure.layout.width === undefined;+ return {+ autosize: shouldAutoSize,+ dragmode: "select",+ height: 540,+ // Prioritize user's config+ ...figure.layout,+ };+}++/**+ * Computes the updated layout when the figure changes.+ * Preserves user-interaction values (dragmode, xaxis, yaxis) while+ * taking everything else from the new figure's layout.+ */+export function computeLayoutOnFigureChange(+ nextFigure: Figure,+ prevLayout: Partial<Plotly.Layout>,+): Partial<Plotly.Layout> {+ return {+ ...createInitialLayout(nextFigure),+ ...pick(prevLayout, PERSISTED_LAYOUT_KEYS),+ };+}++/**+ * Computes which keys to omit from layout updates based on what changed.+ * If a key changed in the figure, we should update it even if it's normally omitted.+ */+export function computeOmitKeys(+ currentLayout: Partial<Plotly.Layout>,+ previousLayout: Partial<Plotly.Layout>,+): Set<keyof Plotly.Layout> {+ const omitKeys = new Set<keyof Plotly.Layout>(LAYOUT_OMIT_KEYS);++ // If the key was updated externally (e.g. can be specifically passed in the config)+ // then we need to update the layout+ for (const key of omitKeys) {+ if (!isEqual(currentLayout[key], previousLayout[key])) {+ omitKeys.delete(key);+ }+ }++ return omitKeys;+}++/**+ * Computes the layout update when figure.layout changes.+ * Omits keys that shouldn't override user interactions unless they changed.+ */+export function computeLayoutUpdate(+ figureLayout: Partial<Plotly.Layout>,+ previousFigureLayout: Partial<Plotly.Layout>,+ prevLayout: Partial<Plotly.Layout>,+): Partial<Plotly.Layout> {+ const omitKeys = computeOmitKeys(figureLayout, previousFigureLayout);+ const layoutUpdate = Objects.omit(figureLayout, omitKeys);+ return { ...prevLayout, ...layoutUpdate };+}++interface UsePlotlyLayoutOptions {+ originalFigure: Figure;+ initialValue?: Partial<Plotly.Layout>;+ isScriptLoaded?: boolean;+}++interface UsePlotlyLayoutResult {+ figure: Figure;+ layout: Partial<Plotly.Layout>;+ setLayout: React.Dispatch<React.SetStateAction<Partial<Plotly.Layout>>>;+ handleReset: () => void;+}++/**+ * Hook that manages the Plotly figure and layout state.+ *+ * This hook handles:+ * - Cloning the figure to prevent Plotly mutations+ * - Managing layout state with proper preservation of user interactions+ * - Syncing layout when the figure changes+ * - Providing a reset function to restore original state+ */+export function usePlotlyLayout({+ originalFigure,+ initialValue,+ isScriptLoaded = true,+}: UsePlotlyLayoutOptions): UsePlotlyLayoutResult {+ const [figure, setFigure] = useState(() => {+ // We clone the figure since Plotly mutates the figure in place+ return structuredClone(originalFigure);+ });++ const [layout, setLayout] = useState<Partial<Plotly.Layout>>(() => {+ return {+ ...createInitialLayout(figure),+ // Override with persisted values (dragmode, xaxis, yaxis)+ ...initialValue,+ };+ });++ // Update figure and layout when originalFigure changes+ useEffect(() => {+ const nextFigure = structuredClone(originalFigure);+ setFigure(nextFigure);+ // Start with the new figure's layout, then only preserve user-interaction+ // values (dragmode, xaxis, yaxis) from the previous layout.+ // We don't want to preserve other properties like `shapes` from the previous+ // layout, as they should be fully controlled by the figure prop.+ setLayout((prev) => computeLayoutOnFigureChange(nextFigure, prev));+ }, [originalFigure, isScriptLoaded]);++ const prevFigure = usePrevious(figure) ?? figure;++ // Sync layout when figure.layout changes+ useEffect(() => {+ setLayout((prev) =>+ computeLayoutUpdate(figure.layout, prevFigure.layout, prev),+ );+ }, [figure.layout, prevFigure.layout]);++ const handleReset = () => {+ const nextFigure = structuredClone(originalFigure);+ setFigure(nextFigure);+ setLayout(createInitialLayout(nextFigure));+ };++ return {+ figure,+ layout,+ setLayout,+ handleReset,+ };+}diff --git a/marimo/_smoke_tests/plotly/shapes.py b/marimo/_smoke_tests/plotly/shapes.pynew file mode 100644index 0000000000..2e5b50ef49--- /dev/null+++ b/marimo/_smoke_tests/plotly/shapes.py@@ -0,0 +1,62 @@+import marimo++__generated_with = "0.19.5"+app = marimo.App(width="medium", auto_download=["html"])+++def _():+ import marimo as mo+ return (mo,)+++def _():+ import plotly.express as px+ import numpy as np+ return np, px+++def _(mo):+ plot_boxes = mo.ui.checkbox(label="Plot boxes", value=False)+ return (plot_boxes,)+++def _(plot_boxes):+ plot_boxes+ return+++def _(np, plot_boxes, px):+ img_rgb = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]],+ [[0, 255, 0], [0, 0, 255], [255, 0, 0]]+ ], dtype=np.uint8)+ fig = px.imshow(img_rgb)+ if plot_boxes.value:+ fig.add_shape(type="rect",+ xref="paper", yref="paper",+ x0=0.4, y0=0.4,+ x1=0.6, y1=0.6,+ line=dict(+ color="Red",+ width=3,+ )+ )+ fig.update_layout(+ dragmode='drawrect',+ newshape=dict(line_color='cyan'))+ fig+ return (fig,)+++def _(fig):+ fig.layout.shapes+ return+++if __name__ == "__main__":+ app.run()