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.

improvement: patch plotly show to open in the notebook (#2423)

Myles Scolnick995cd935473e
diff --git a/marimo/_output/formatters/plotly_formatters.py b/marimo/_output/formatters/plotly_formatters.py
index 18315cafa2..cb39b66e3e 100644
--- a/marimo/_output/formatters/plotly_formatters.py
+++ b/marimo/_output/formatters/plotly_formatters.py
@@ -5,7 +5,9 @@ import json
from typing import Any
from marimo._config.config import Theme
+from marimo._messaging.cell_output import CellChannel
from marimo._messaging.mimetypes import KnownMimeType
+from marimo._messaging.ops import CellOp
from marimo._output.formatters.formatter_factory import FormatterFactory
from marimo._output.hypertext import Html
from marimo._plugins.core.web_component import build_stateless_plugin
@@ -34,6 +36,23 @@ class PlotlyFormatter(FormatterFactory):
plugin = PlotlyFormatter.render_plotly_dict(json.loads(json_str))
return ("text/html", plugin.text)
+ # Patch Figure.show to add to console output instead of opening a
+ # browser.
+ def patched_show(
+ self: plotly.graph_objects.Figure, *args: Any, **kwargs: Any
+ ) -> None:
+ del args, kwargs
+ mimetype, data = _show_plotly_figure(self)
+ CellOp.broadcast_console_output(
+ channel=CellChannel.MEDIA,
+ mimetype=mimetype,
+ data=data,
+ cell_id=None,
+ status=None,
+ )
+
+ plotly.graph_objects.Figure.show = patched_show
+
@staticmethod
def render_plotly_dict(json: dict[Any, Any]) -> Html:
import plotly.io as pio # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501