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
improvement: support sunburst and treemap plotly selection (#2463)
Myles Scolnick218870cee12f
diff --git a/frontend/package.json b/frontend/package.jsonindex 107bb2297f..bfbd411b9c 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -218,5 +218,10 @@"vite-tsconfig-paths": "^4.3.2","vitest": "^1.6.0"},- "packageManager": "[email protected]"+ "packageManager": "[email protected]",+ "pnpm": {+ "patchedDependencies": {+ "react-plotly.js": "patches/react-plotly.js.patch"+ }+ }}diff --git a/frontend/patches/react-plotly.js.patch b/frontend/patches/react-plotly.js.patchnew file mode 100644index 0000000000..96b632c4c8--- /dev/null+++ b/frontend/patches/react-plotly.js.patch@@ -0,0 +1,15 @@+diff --git a/factory.js b/factory.js+index 40f3edccbebc45b491dd3488ed619ec9208be8d9..f88f451588d656805d1ae76ce4184a486a179eb1 100644+--- a/factory.js++++ b/factory.js+@@ -40,8 +40,8 @@ function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.g+ // The naming convention is:+ // - events are attached as `'plotly_' + eventName.toLowerCase()`+ // - react props are `'on' + eventName`+-var eventNames = ['AfterExport', 'AfterPlot', 'Animated', 'AnimatingFrame', 'AnimationInterrupted', 'AutoSize', 'BeforeExport', 'BeforeHover', 'ButtonClicked', 'Click', 'ClickAnnotation', 'Deselect', 'DoubleClick', 'Framework', 'Hover', 'LegendClick', 'LegendDoubleClick', 'Relayout', 'Relayouting', 'Restyle', 'Redraw', 'Selected', 'Selecting', 'SliderChange', 'SliderEnd', 'SliderStart', 'SunburstClick', 'Transitioning', 'TransitionInterrupted', 'Unhover', 'WebGlContextLost'];+-var updateEvents = ['plotly_restyle', 'plotly_redraw', 'plotly_relayout', 'plotly_relayouting', 'plotly_doubleclick', 'plotly_animated', 'plotly_sunburstclick']; // Check if a window is available since SSR (server-side rendering)++var eventNames = ['AfterExport', 'AfterPlot', 'Animated', 'AnimatingFrame', 'AnimationInterrupted', 'AutoSize', 'BeforeExport', 'BeforeHover', 'ButtonClicked', 'Click', 'ClickAnnotation', 'Deselect', 'DoubleClick', 'Framework', 'Hover', 'LegendClick', 'LegendDoubleClick', 'Relayout', 'Relayouting', 'Restyle', 'Redraw', 'Selected', 'Selecting', 'SliderChange', 'SliderEnd', 'SliderStart', 'SunburstClick', 'TreemapClick', 'Transitioning', 'TransitionInterrupted', 'Unhover', 'WebGlContextLost'];++var updateEvents = ['plotly_restyle', 'plotly_redraw', 'plotly_relayout', 'plotly_relayouting', 'plotly_doubleclick', 'plotly_animated', 'plotly_sunburstclick', 'plotly_treemapclick']; // Check if a window is available since SSR (server-side rendering)+ // breaks unnecessarily if you try to use it server-side.++ var isBrowser = typeof window !== 'undefined';diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex dca4efae51..9712d85902 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -6,6 +6,11 @@ settings:pnpmfileChecksum: eqzj7c6t3bs5v7xcjer2wfwkp4+patchedDependencies:+ react-plotly.js:+ hash: bpeex744nmt6722etqry6essaq+ path: patches/react-plotly.js.patch+importers:.:@@ -330,7 +335,7 @@ importers:version: 7.52.2([email protected])react-plotly.js:specifier: ^2.6.0+ version: 2.6.0(patch_hash=bpeex744nmt6722etqry6essaq)([email protected]([email protected]))([email protected])react-resizable-panels:specifier: 2.0.19@@ -19530,7 +19535,7 @@ snapshots:+ [email protected](patch_hash=bpeex744nmt6722etqry6essaq)([email protected]([email protected]))([email protected]):dependencies:plotly.js: 2.34.0([email protected])prop-types: 15.8.1diff --git a/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx b/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsxindex 2859a42f81..781b7afe53 100644--- a/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx+++ b/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx@@ -12,7 +12,7 @@ import { lazy, memo, useEffect, useMemo, useState } from "react";import useEvent from "react-use-event-hook";import { type PlotlyTemplateParser, createParser } from "./parse-from-template";import { Objects } from "@/utils/objects";-import { isEqual, set } from "lodash-es";+import { isEqual, pick, set } from "lodash-es";import { useDeepCompareMemoize } from "@/hooks/useDeepCompareMemoize";import { usePrevious } from "@uidotdev/usehooks";import { Arrays } from "@/utils/arrays";@@ -27,7 +27,7 @@ type AxisDatum = unknown;type T =| {- points?: Array<Record<AxisName, AxisDatum>>;+ points?: Array<Record<AxisName, AxisDatum>> | Plotly.PlotDatum[];indices?: number[];range?: {x?: number[];@@ -85,8 +85,30 @@ function initialLayout(figure: Figure): Partial<Plotly.Layout> {};}+const SUNBURST_DATA_KEYS: Array<keyof Plotly.SunburstPlotDatum> = [+ "color",+ "curveNumber",+ "entry",+ "hovertext",+ "id",+ "label",+ "parent",+ "percentEntry",+ "percentParent",+ "percentRoot",+ "pointNumber",+ "root",+ "value",+] as const;+const TREE_MAP_DATA_KEYS = SUNBURST_DATA_KEYS;+export const PlotlyComponent = memo(- ({ figure, value, setValue, config }: PlotlyPluginProps) => {+ ({ figure: originalFigure, value, setValue, config }: PlotlyPluginProps) => {+ 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 {...initialLayout(figure),@@ -95,12 +117,11 @@ export const PlotlyComponent = memo(};});- const [nonce, setNonce] = useState(0);-const handleReset = useEvent(() => {- setLayout(initialLayout(figure));+ const nextFigure = structuredClone(originalFigure);+ setFigure(nextFigure);+ setLayout(initialLayout(nextFigure));setValue({});- setNonce((prev) => prev + 1);});const plotlyConfig = useMemo((): Partial<Plotly.Config> => {@@ -154,7 +175,6 @@ export const PlotlyComponent = memo(return (<LazyPlot- key={nonce}{...figure}layout={layout}onRelayout={(layoutUpdate) => {@@ -189,6 +209,27 @@ export const PlotlyComponent = memo(};});})}+ // @ts-expect-error We patched this prop here so it doesn't exist in the types+ onTreemapClick={useEvent((evt: Readonly<Plotly.PlotMouseEvent>) => {+ if (!evt) {+ return;+ }++ setValue((prev) => ({+ ...prev,+ points: evt.points.map((point) => pick(point, TREE_MAP_DATA_KEYS)),+ }));+ })}+ onSunburstClick={useEvent((evt: Readonly<Plotly.PlotMouseEvent>) => {+ if (!evt) {+ return;+ }++ setValue((prev) => ({+ ...prev,+ points: evt.points.map((point) => pick(point, SUNBURST_DATA_KEYS)),+ }));+ })}config={plotlyConfig}onSelected={useEvent((evt: Readonly<Plotly.PlotSelectionEvent>) => {if (!evt) {diff --git a/marimo/_smoke_tests/bugs/2457-plotly-section.py b/marimo/_smoke_tests/bugs/2457-plotly-section.pynew file mode 100644index 0000000000..a348b6812e--- /dev/null+++ b/marimo/_smoke_tests/bugs/2457-plotly-section.py@@ -0,0 +1,69 @@+++import marimo++__generated_with = "0.8.22"+app = marimo.App(width="medium")+++def __():+ import marimo as mo+ import plotly.express as px++ df = px.data.tips()+ mo.md("# Plotly Selection")+ return df, mo, px+++def __(df):+ df+ return+++def __(df, mo, px):+ _fig = px.treemap(df, path=[px.Constant("all"), 'day', 'time', 'sex'], values='total_bill')+ plot = mo.ui.plotly(_fig)+ return (plot,)+++def __(mo, plot):+ mo.vstack([plot], align="stretch")+ return+++def __(plot):+ plot.value+ return+++def __(mo, px):+ _data = dict(+ character=["Eve", "Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura"],+ parent=["", "Eve", "Eve", "Seth", "Seth", "Eve", "Eve", "Awan", "Eve" ],+ value=[10, 14, 12, 10, 2, 6, 6, 4, 4])++ sunburst = mo.ui.plotly(px.sunburst(+ _data,+ names='character',+ parents='parent',+ values='value',+ ))++ sunburst+ return (sunburst,)+++def __(sunburst):+ sunburst.value+ return+++if __name__ == "__main__":+ app.run()