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.

Add mo.ui.plotly_plot for reactive Plotly (#331)

Myles Scolnick652b58d99694
diff --git a/docs/api/plotting.md b/docs/api/plotting.md
index 5efef2f5ac..bd44d5abcc 100644
--- a/docs/api/plotting.md
+++ b/docs/api/plotting.md
@@ -6,7 +6,7 @@ as you normally would.
For more information about plotting, see the [plotting guide](../guides/plotting.md).
-## Reactive charts
+## Reactive charts with Altair
<iframe class="demo large" src="https://components.marimo.io/?component=altair-chart" frameborder="no"></iframe>
@@ -14,6 +14,12 @@ For more information about plotting, see the [plotting guide](../guides/plotting
.. autofunction:: marimo.ui.altair_chart
```
+## Reactive plots with Plotly
+
+```{eval-rst}
+.. autofunction:: marimo.ui.plotly
+```
+
## matplotlib
```{eval-rst}
diff --git a/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx b/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx
index 72d82e3382..6b4aa8af75 100644
--- a/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx
+++ b/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx
@@ -1,20 +1,34 @@
/* Copyright 2023 Marimo. All rights reserved. */
import { z } from "zod";
-import { IPluginProps } from "@/plugins/types";
+import { IPlugin, IPluginProps } from "@/plugins/types";
import Plot, { Figure } from "react-plotly.js";
-import { IStatelessPlugin } from "@/plugins/stateless-plugin";
-import { T } from "vitest/dist/reporters-5f784f42";
import { Logger } from "@/utils/Logger";
import "./plotly.css";
+import { Objects } from "@/utils/objects";
+import { memo, useMemo } from "react";
+import useEvent from "react-use-event-hook";
interface Data {
figure: Figure;
}
-export class PlotlyPlugin implements IStatelessPlugin<Data> {
+type AxisName = string;
+type AxisDatum = unknown;
+
+type T =
+ | {
+ points?: Array<Record<AxisName, AxisDatum>>;
+ range?: {
+ x?: number[];
+ y?: number[];
+ };
+ }
+ | undefined;
+
+export class PlotlyPlugin implements IPlugin<T, Data> {
tagName = "marimo-plotly";
validator = z.object({
@@ -25,34 +39,80 @@ export class PlotlyPlugin implements IStatelessPlugin<Data> {
});
render(props: IPluginProps<T, Data>): JSX.Element {
- return <PlotlyComponent {...props.data} host={props.host} />;
+ return (
+ <PlotlyComponent
+ {...props.data}
+ host={props.host}
+ value={props.value}
+ setValue={props.setValue}
+ />
+ );
}
}
interface PlotlyPluginProps extends Data {
+ value: T;
+ setValue: (value: T) => void;
host: HTMLElement;
}
-export const PlotlyComponent = ({ figure, host }: PlotlyPluginProps) => {
- // Enable autosize if width is not specified
- const shouldAutoSize = figure.layout.width === undefined;
- return (
- <Plot
- {...figure}
- layout={{
+const config = {
+ displaylogo: false,
+};
+
+export const PlotlyComponent = memo(
+ ({ figure, setValue }: PlotlyPluginProps) => {
+ const layout: Partial<Plotly.Layout> = useMemo(() => {
+ // Enable autosize if width is not specified
+ const shouldAutoSize = figure.layout.width === undefined;
+ return {
autosize: shouldAutoSize,
+ dragmode: "select",
+ height: 560,
// Prioritize user's config
...figure.layout,
- }}
- config={{
- displaylogo: false,
- }}
- className="w-full h-full"
- useResizeHandler={true}
- frames={figure.frames ?? undefined}
- onError={(err) => {
- Logger.error("PlotlyPlugin: ", err);
- }}
- />
- );
-};
+ };
+ }, [figure.layout]);
+
+ return (
+ <Plot
+ {...figure}
+ layout={layout}
+ config={config}
+ onSelected={useEvent((evt) => {
+ setValue({
+ points: extractPoints(evt.points),
+ range: evt.range,
+ });
+ })}
+ className="w-full h-full"
+ useResizeHandler={true}
+ frames={figure.frames ?? undefined}
+ onError={useEvent((err) => {
+ Logger.error("PlotlyPlugin: ", err);
+ })}
+ />
+ );
+ }
+);
+PlotlyComponent.displayName = "PlotlyComponent";
+
+const keysToInclude = new Set(["x", "y", "value", "label"]);
+function extractPoints(
+ points: Plotly.PlotDatum[]
+): Array<Record<AxisName, AxisDatum>> {
+ if (!points) {
+ return [];
+ }
+
+ return points.map((point) => {
+ const data: Record<AxisName, AxisDatum> = Objects.filter(point, (_v, key) =>
+ keysToInclude.has(key)
+ );
+ // Add name if it exists
+ if (point.data.name) {
+ data.name = point.data.name;
+ }
+ return data;
+ });
+}
diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.ts
index f9fbc732bb..d7902a4558 100644
--- a/frontend/src/plugins/plugins.ts
+++ b/frontend/src/plugins/plugins.ts
@@ -53,6 +53,7 @@ export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [
new TextAreaPlugin(),
new TextInputPlugin(),
new VegaPlugin(),
+ new PlotlyPlugin(),
DataFramePlugin,
];
@@ -62,7 +63,6 @@ const LAYOUT_PLUGINS: Array<IStatelessPlugin<unknown>> = [
new CalloutPlugin(),
new DownloadPlugin(),
new JsonOutputPlugin(),
- new PlotlyPlugin(),
new ProgressPlugin(),
new StatPlugin(),
new TabsPlugin(),
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index c2c85625ad..331aa3a2a2 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -67,6 +67,21 @@ class DependencyManager:
+ "You can install it with 'pip install altair'"
) from None
+ @staticmethod
+ def require_plotly(why: str) -> None:
+ """
+ Raise an ModuleNotFoundError if plotly is not installed.
+
+ Args:
+ why: A string of the form "for <reason>" that will be appended
+
+ """
+ if not DependencyManager.has_plotly():
+ raise ModuleNotFoundError(
+ f"plotly is required {why}. "
+ + "You can install it with 'pip install plotly'"
+ ) from None
+
@staticmethod
def has_pandas() -> bool:
"""Return True if pandas is installed."""
@@ -86,3 +101,8 @@ class DependencyManager:
def has_altair() -> bool:
"""Return True if altair is installed."""
return importlib.util.find_spec("altair") is not None
+
+ @staticmethod
+ def has_plotly() -> bool:
+ """Return True if plotly is installed."""
+ return importlib.util.find_spec("plotly") is not None
diff --git a/marimo/_plugins/ui/__init__.py b/marimo/_plugins/ui/__init__.py
index c92f83e588..a903b70c43 100644
--- a/marimo/_plugins/ui/__init__.py
+++ b/marimo/_plugins/ui/__init__.py
@@ -19,6 +19,7 @@ __all__ = [
"microphone",
"multiselect",
"number",
+ "plotly",
"radio",
"refresh",
"slider",
@@ -49,6 +50,7 @@ from marimo._plugins.ui._impl.input import (
text_area,
)
from marimo._plugins.ui._impl.microphone import microphone
+from marimo._plugins.ui._impl.plotly import plotly
from marimo._plugins.ui._impl.refresh import refresh
from marimo._plugins.ui._impl.switch import switch
from marimo._plugins.ui._impl.table import table
diff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.py
new file mode 100644
index 0000000000..0aa91ab96c
--- /dev/null
+++ b/marimo/_plugins/ui/_impl/plotly.py
@@ -0,0 +1,127 @@
+# Copyright 2023 Marimo. All rights reserved.
+from __future__ import annotations
+
+import json
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Dict,
+ Final,
+ List,
+ Optional,
+)
+
+from marimo import _loggers
+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
+
+LOGGER = _loggers.marimo_logger()
+
+if TYPE_CHECKING:
+ import plotly.graph_objects as go # type:ignore
+
+# Selection is a dictionary of the form:
+# {
+# "points": {
+# "field1": "value1",
+# "field2": "value2",
+# }[],
+# "range": {
+# "field1": [min, max],
+# "field2": [min, max],
+# },
+# }
+PlotlySelection = Dict[str, JSONType]
+
+
+@mddoc
+class plotly(UIElement[PlotlySelection, List[Dict[str, Any]]]):
+ """Make reactive plots with Plotly.
+
+ Use `mo.ui.plotly` to make plotly plots reactive: select data
+ with your cursor on the frontend, get them as a list of dicts in Python!
+
+ **Example.**
+
+ ```python
+ import plotly.express as px
+ import marimo as mo
+ from vega_datasets import data
+
+ _plot = px.scatter(
+ data.cars(),
+ x="Horsepower",
+ y="Miles_per_Gallon",
+ color="Origin"
+ )
+
+ plot = mo.ui.plotly(_plot)
+ ```
+
+ ```
+ # View the plot and selected data
+ mo.hstack([plot, plot.value])
+ ```
+
+ **Attributes.**
+
+ - `value`: a dict of the plot data
+ - `ranges`: the selection of the plot; this may be an interval along
+ the name of an axis
+
+ **Initialization Args.**
+
+ - `figure`: A `plotly.graph_objects.Figure`
+ - `label`: optional text label for the element
+ - `on_change`: optional callback to run when this element's value changes
+ """
+
+ name: Final[str] = "marimo-plotly"
+
+ def __init__(
+ self,
+ figure: go.Figure,
+ *,
+ label: str = "",
+ on_change: Optional[Callable[[JSONType], None]] = None,
+ ) -> None:
+ DependencyManager.require_plotly("for `mo.ui.plotly`")
+
+ import plotly.io as pio # type:ignore
+
+ json_str = pio.to_json(figure)
+
+ super().__init__(
+ component_name=plotly.name,
+ initial_value={},
+ label=label,
+ args={
+ "figure": json.loads(json_str),
+ },
+ on_change=on_change,
+ )
+
+ @property
+ def ranges(self) -> Dict[str, List[float]]:
+ if not self._selection_data:
+ return {}
+ if "range" not in self._selection_data:
+ return {}
+ return self._selection_data["range"] # type:ignore
+
+ @property
+ def points(self) -> List[Dict[str, Any]]:
+ if not self._selection_data:
+ return []
+ if "points" not in self._selection_data:
+ return []
+ return self._selection_data["points"] # type:ignore
+
+ def _convert_value(self, value: PlotlySelection) -> Any:
+ # Store the selection data
+ self._selection_data = value
+ # Default to returning the points
+ return self.points
diff --git a/marimo/_smoke_tests/third_party/plotly.py b/marimo/_smoke_tests/third_party/plotly.py
index 1f29c6f29f..6b4c5ff1fb 100644
--- a/marimo/_smoke_tests/third_party/plotly.py
+++ b/marimo/_smoke_tests/third_party/plotly.py
@@ -1,7 +1,7 @@
# Copyright 2023 Marimo. All rights reserved.
import marimo
-__generated_with = "0.1.39"
+__generated_with = "0.1.47"
app = marimo.App(width="full")
@@ -21,12 +21,34 @@ def __():
@app.cell
def __(mo, px):
+ plot = mo.ui.plotly(
+ px.scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16], width=600)
+ )
mo.vstack(
[
mo.md("# Fixed width"),
- px.scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16], width=600),
+ plot,
]
)
+ return plot,
+
+
+def __(mo, plot):
+ mo.hstack(
+ [
+ mo.ui.table(plot.value, label="Points", selection=None),
+ mo.ui.table(
+ [
+ {"start": r[0], "end": r[1], "axis": key}
+ for key, r in plot.ranges.items()
+ ],
+ selection=None,
+ label="Ranges",
+ ),
+ ],
+ widths="equal",
+ )
return
@@ -37,7 +59,7 @@ def __(mo):
@app.cell
-def __():
+def __(mo):
import pandas as pd
import plotly.graph_objects as go
@@ -81,8 +103,15 @@ def __():
fig.update_xaxes(title_text="Fruit")
fig.update_yaxes(title_text="Number Eaten")
- fig
- return contestant, df, fig, go, group, pd
+ plot2 = mo.ui.plotly(fig)
+ plot2
+ return contestant, df, fig, go, group, pd, plot2
+
+
+def __(mo, plot2):
+ mo.ui.table(plot2.value, selection=None)
+ return
@app.cell
@@ -108,7 +137,7 @@ def __(cars, mo):
@app.cell
-def __(cars, px, sample_size):
+def __(cars, mo, px, sample_size):
_fig = px.scatter(
cars.sample(sample_size.value),
x="Horsepower",
@@ -119,6 +148,14 @@ def __(cars, px, sample_size):
)
_fig
+ plot3 = mo.ui.plotly(_fig)
+ plot3
+ return plot3,
+
+
+def __(mo, plot3):
+ mo.ui.table(plot3.value, selection=None)
return