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: Interactive Matplotlib Plots (#158)
Akshay Agrawala49228de3c01
diff --git a/frontend/src/editor/Output.tsx b/frontend/src/editor/Output.tsxindex aad430c68c..0a2301cc93 100644--- a/frontend/src/editor/Output.tsx+++ b/frontend/src/editor/Output.tsx@@ -12,6 +12,7 @@ import { TextOutput } from "./output/TextOutput";import { VideoOutput } from "./output/VideoOutput";import { CellId } from "@/core/model/ids";import { cn } from "@/lib/utils";+import { ErrorBoundary } from "./boundary/ErrorBoundary";import "./output/Outputs.css";@@ -96,17 +97,22 @@ export const OutputArea = React.memo(// 3. This output is stale (its inputs have changed)const title = props.stale ? "This output is stale" : undefined;return (- <div- title={title}- id={`output-${props.cellId}`}- className={cn(props.stale && "marimo-output-stale", props.className)}- >- {formatOutput({- message: props.output,- // eslint-disable-next-line @typescript-eslint/no-explicit-any- parsedJsonData: parsedJsonData as Record<string, any>,- })}- </div>+ <ErrorBoundary>+ <div+ title={title}+ id={`output-${props.cellId}`}+ className={cn(+ props.stale && "marimo-output-stale",+ props.className+ )}+ >+ {formatOutput({+ message: props.output,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ parsedJsonData: parsedJsonData as Record<string, any>,+ })}+ </div>+ </ErrorBoundary>);}}diff --git a/frontend/src/editor/output/HtmlOutput.tsx b/frontend/src/editor/output/HtmlOutput.tsxindex ac175d1616..d323f22ddd 100644--- a/frontend/src/editor/output/HtmlOutput.tsx+++ b/frontend/src/editor/output/HtmlOutput.tsx@@ -70,6 +70,10 @@ export const HtmlOutput: React.FC<Props> = memo(}}, [html, nodeRef]);+ if (!html) {+ return null;+ }+return (<divclassName={cn(className, {diff --git a/marimo/__init__.py b/marimo/__init__.pyindex 2870a5db1d..da650b252e 100644--- a/marimo/__init__.py+++ b/marimo/__init__.py@@ -28,6 +28,7 @@ __all__ = ["image","left","md",+ "mpl","pdf","refs","right",@@ -47,6 +48,7 @@ from marimo._output.hypertext import Htmlfrom marimo._output.justify import center, left, rightfrom marimo._output.md import mdfrom marimo._plugins import ui+from marimo._plugins.stateless import mplfrom marimo._plugins.stateless.accordion import accordionfrom marimo._plugins.stateless.audio import audiofrom marimo._plugins.stateless.callout_output import calloutdiff --git a/marimo/_plugins/stateless/mpl/__init__.py b/marimo/_plugins/stateless/mpl/__init__.pynew file mode 100644index 0000000000..c801b1621e--- /dev/null+++ b/marimo/_plugins/stateless/mpl/__init__.py@@ -0,0 +1,10 @@+# Copyright 2023 Marimo. All rights reserved.+"""Utilities for working with matplotlib."""+++__all__ = [+ "interactive",+]+++from marimo._plugins.stateless.mpl._mpl import interactivediff --git a/marimo/_plugins/stateless/mpl/_mpl.py b/marimo/_plugins/stateless/mpl/_mpl.pynew file mode 100644index 0000000000..6b12c5ba86--- /dev/null+++ b/marimo/_plugins/stateless/mpl/_mpl.py@@ -0,0 +1,402 @@+# Copyright 2023 Marimo. All rights reserved.+"""+Interactive matplotlib plots, based on WebAgg.++Adapted from https://matplotlib.org/stable/gallery/user_interfaces/embedding_webagg_sgskip.html+"""++from __future__ import annotations++import asyncio+import io+import json+import mimetypes+import socket+import threading+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Optional++import tornado+import tornado.httpserver+import tornado.ioloop+import tornado.netutil+import tornado.web+import tornado.websocket++from marimo._ast.cell import CellId_t+from marimo._output.builder import h+from marimo._output.hypertext import Html+from marimo._output.rich_help import mddoc+from marimo._runtime.context import get_context+++class MplApplication(tornado.web.Application):+ # Figure Manager, Any type because matplotlib doesn't have typings+ manager: Any++ class MainPage(tornado.web.RequestHandler):+ """+ Serves the main HTML page.+ """++ application: MplApplication++ def get(self) -> None:+ manager = self.application.manager+ ws_uri = f"ws://{self.request.host}/"+ content = html_content % {+ "ws_uri": ws_uri,+ "fig_id": manager.num,+ "custom_css": css_content,+ }+ self.write(content)++ class MplJs(tornado.web.RequestHandler):+ """+ Serves the generated matplotlib javascript file. The content+ is dynamically generated based on which toolbar functions the+ user has defined. Call `FigureManagerWebAgg` to get its+ content.+ """++ application: MplApplication++ def get(self) -> None:+ from matplotlib.backends.backend_webagg import ( # type: ignore+ FigureManagerWebAgg,+ )++ self.set_header("Content-Type", "application/javascript")+ js_content = FigureManagerWebAgg.get_javascript()++ self.write(js_content)++ class Download(tornado.web.RequestHandler):+ """+ Handles downloading of the figure in various file formats.+ """++ application: MplApplication++ def get(self, fmt: str) -> None:+ manager = self.application.manager+ self.set_header(+ "Content-Type", mimetypes.types_map.get(fmt, "binary")+ )+ buff = io.BytesIO()+ manager.canvas.figure.savefig(buff, format=fmt)+ self.write(buff.getvalue())++ class WebSocket(tornado.websocket.WebSocketHandler):+ """+ A websocket for interactive communication between the plot in+ the browser and the server.++ In addition to the methods required by tornado, it is required to+ have two callback methods:++ - ``send_json(json_content)`` is called by matplotlib when+ it needs to send json to the browser. `json_content` is+ a JSON tree (Python dictionary), and it is the responsibility+ of this implementation to encode it as a string to send over+ the socket.++ - ``send_binary(blob)`` is called to send binary image data+ to the browser.+ """++ application: MplApplication+ supports_binary = True++ def open(self, *args: str, **kwargs: str) -> None:+ del args+ del kwargs+ # Register the websocket with the FigureManager.+ manager = self.application.manager+ manager.add_web_socket(self)+ if hasattr(self, "set_nodelay"):+ self.set_nodelay(True)++ def on_close(self) -> None:+ # When the socket is closed, deregister the websocket with+ # the FigureManager.+ manager = self.application.manager+ manager.remove_web_socket(self)++ def on_message(self, message: Any) -> None:+ # The 'supports_binary' message is relevant to the+ # websocket itself. The other messages get passed along+ # to matplotlib as-is.++ # Every message has a "type" and a "figure_id".+ message = json.loads(message)+ if message["type"] == "supports_binary":+ self.supports_binary = message["value"]+ else:+ manager = self.application.manager+ manager.handle_json(message)++ def send_json(self, content: str) -> None:+ self.write_message(json.dumps(content))++ def send_binary(self, blob: Any) -> None:+ if self.supports_binary:+ self.write_message(blob, binary=True)+ else:+ data_uri = "data:image/png;base64," + blob.encode(+ "base64"+ ).replace("\n", "")+ self.write_message(data_uri)++ def __init__(self, figure: Any) -> None:+ import matplotlib as mpl # type: ignore[import]+ from matplotlib.backends.backend_webagg import (+ FigureManagerWebAgg,+ new_figure_manager_given_figure,+ )++ self.figure = figure+ self.manager = new_figure_manager_given_figure(id(figure), figure)++ super().__init__(+ [+ # Static files for the CSS and JS+ (+ r"/mpl/_static/(.*)",+ tornado.web.StaticFileHandler,+ {"path": FigureManagerWebAgg.get_static_file_path()},+ ),+ # Static images for the toolbar+ (+ r"/_images/(.*)",+ tornado.web.StaticFileHandler,+ {"path": Path(mpl.get_data_path(), "images")},+ ),+ # The page that contains all of the pieces+ ("/", self.MainPage),+ ("/mpl/mpl.js", self.MplJs),+ # Sends images and events to the browser, and receives+ # events from the browser+ ("/ws", self.WebSocket),+ # Handles the downloading (i.e., saving) of static images+ (r"/download.([a-z0-9.]+)", self.Download),+ ]+ )+++@dataclass+class CleanupHandle:+ """Handle to shutdown a figure server."""++ shutdown_event: Optional[asyncio.Event] = None+++class InteractiveMplRegistry:+ """Registry of figures created by each cell.++ Allows the kernel to tear down all figures for a given cell.+ """++ _registry: dict[CellId_t, list[CleanupHandle]] = {}++ def register(+ self, cell_id: CellId_t, cleanup_handle: CleanupHandle+ ) -> None:+ """Register a figure's cleanup handle for a cell."""+ if cell_id not in self._registry:+ self._registry[cell_id] = [cleanup_handle]+ else:+ self._registry[cell_id].append(cleanup_handle)++ def cleanup(self, cell_id: CellId_t) -> None:+ """Tear down figures for a cell."""+ if cell_id in self._registry:+ for cleanup_handle in self._registry[cell_id]:+ if cleanup_handle.shutdown_event is not None:+ cleanup_handle.shutdown_event.set()+ del self._registry[cell_id]+++@mddoc+def interactive(figure: "Figure | Axes") -> Html: # type: ignore[name-defined] # noqa:F821,E501+ """Render a matplotlib figure using an interactive viewer.++ The interactive viewer allows you to pan, zoom, and see plot coordinates+ on mouse hover.++ **Example**:++ ```python+ plt.plot([1, 2])+ # plt.gcf() gets the current figure+ mo.mpl.interactive(plt.gcf())+ ```++ **Args**:++ - figure: a matplotlib `Figure` or `Axes` object++ **Returns**:++ - An interactive matplotlib figure as an `Html` object+ """+ # No top-level imports of matplotlib, since it isn't a required+ # dependency+ from matplotlib.axes import Axes # type: ignore[import]++ if isinstance(figure, Axes):+ figure = figure.get_figure()++ ctx = get_context()+ if not ctx.initialized:+ raise RuntimeError(+ "marimo.mpl.interactive can't be used when running as a script."+ )++ # TODO(akshayka): Proxy this server through the marimo server to help with+ # deployment.+ application = MplApplication(figure)+ cleanup_handle = CleanupHandle()+ sockets = tornado.netutil.bind_sockets(0, "")++ async def main() -> None:+ # create the shutdown event in the coroutine for py3.8, 3.9 compat+ cleanup_handle.shutdown_event = asyncio.Event()+ http_server = tornado.httpserver.HTTPServer(application)+ http_server.add_sockets(sockets)+ await cleanup_handle.shutdown_event.wait()++ def start_server() -> None:+ asyncio.run(main())++ addr: Optional[str] = None+ port: Optional[int] = None+ for s in sockets:+ addr, port = s.getsockname()[:2]+ if s.family is socket.AF_INET6:+ addr = f"[{addr}]"+ if addr is None or port is None:+ raise RuntimeError("Failed to create sockets for mpl.interactive.")++ assert ctx.kernel.execution_context is not None+ ctx.interactive_mpl_registry.register(+ cell_id=ctx.kernel.execution_context.cell_id,+ cleanup_handle=cleanup_handle,+ )++ threading.Thread(target=start_server).start()+ return Html(+ h.iframe(+ src=f"http://{addr}:{port}/",+ width="100%",+ height="550px",+ )+ )+++html_content = """+<!DOCTYPE html>+<html lang="en">+ <head>+ <link rel="stylesheet" href="mpl/_static/css/page.css" type="text/css" />+ <link rel="stylesheet" href="mpl/_static/css/boilerplate.css" type="text/css" />+ <link rel="stylesheet" href="mpl/_static/css/fbm.css" type="text/css" />+ <link rel="stylesheet" href="mpl/_static/css/mpl.css" type="text/css" />+ <script src="mpl/mpl.js"></script>+ <style>+ %(custom_css)s+ </style>++ <script>+ function ondownload(figure, format) {+ window.open('download.' + format, '_blank');+ };++ function ready(fn) {+ if (document.readyState != "loading") {+ fn();+ } else {+ document.addEventListener("DOMContentLoaded", fn);+ }+ }++ ready(+ function() {+ var websocket_type = mpl.get_websocket_type();+ var websocket = new websocket_type("%(ws_uri)sws");++ // mpl.figure creates a new figure on the webpage.+ var fig = new mpl.figure(+ // A unique numeric identifier for the figure+ %(fig_id)s,+ // A websocket object+ websocket,+ // A function called when a file type is selected for download+ ondownload,+ // The HTML element in which to place the figure+ document.getElementById("figure"));+ }+ );+ </script>++ <title>marimo</title>+ </head>++ <body>+ <div id="figure"></div>+ </body>+</html>+""".strip() # noqa: E501++# Custom CSS to make the mpl toolbar fit the marimo UI+# We do not support dark mode at the moment as the iframe does not know+# the theme of the parent page.+css_content = """+body {+ background-color: transparent;+}+.ui-dialog-titlebar + div {+ border-radius: 4px;+}+.ui-dialog-titlebar {+ display: none;+}+.mpl-toolbar {+ display: flex;+ align-items: center;+ gap: 8px;+}+select.mpl-widget,+.mpl-button-group {+ margin: 4px 0;+ border-radius: 6px;+ box-shadow: rgba(0, 0, 0, 0) 0px 0px 0px 0px,+ rgba(0, 0, 0, 0) 0px 0px 0px 0px,+ rgba(15, 23, 42, 0.1) 1px 1px 0px 0px,+ rgba(15, 23, 42, 0.1) 0px 0px 2px 0px;+}+.mpl-button-group + .mpl-button-group {+ margin-left: 0;+}+.mpl-button-group > .mpl-widget {+ padding: 4px;+}+.mpl-button-group > .mpl-widget > img {+ height: 16px;+ width: 16px;+}+.mpl-widget:disabled, .mpl-widget[disabled]+.mpl-widget:disabled, .mpl-widget[disabled]:hover {+ opacity: 0.5;+ background-color: #fff;+ border-color: #ccc !important;+}+.mpl-message {+ color: rgb(139, 141, 152);+ font-size: 11px;+}+.mpl-widget img {+ filter: invert(0.3);+}+""".strip()diff --git a/marimo/_runtime/conftest.py b/marimo/_runtime/conftest.pyindex 1690249917..3965d6c7b0 100644--- a/marimo/_runtime/conftest.py+++ b/marimo/_runtime/conftest.py@@ -7,6 +7,7 @@ from typing import Any, Generatorimport pytestfrom marimo._ast.cell import CellId_t+from marimo._plugins.stateless.mpl._mpl import InteractiveMplRegistryfrom marimo._plugins.ui._core.registry import UIElementRegistryfrom marimo._runtime.context import get_contextfrom marimo._runtime.requests import ExecutionRequest@@ -27,6 +28,7 @@ def k() -> Generator[Kernel, None, None]:get_context().initialize(kernel=k,ui_element_registry=UIElementRegistry(),+ interactive_mpl_registry=InteractiveMplRegistry(),stream=_MockStream(), # type: ignorestdout=None,stderr=None,diff --git a/marimo/_runtime/context.py b/marimo/_runtime/context.pyindex 73848662d8..9707056fcd 100644--- a/marimo/_runtime/context.py+++ b/marimo/_runtime/context.py@@ -15,6 +15,7 @@ from marimo._plugins.ui._core.ids import IDProvider, NoIDProviderExceptionif TYPE_CHECKING:from marimo._messaging.streams import Stderr, Stdout, Stream+ from marimo._plugins.stateless.mpl._mpl import InteractiveMplRegistryfrom marimo._plugins.ui._core.registry import UIElementRegistryfrom marimo._runtime.runtime import Kernel@@ -56,12 +57,14 @@ class RuntimeContext(threading.local):self,kernel: Kernel,ui_element_registry: UIElementRegistry,+ interactive_mpl_registry: InteractiveMplRegistry,stream: Stream,stdout: Optional[Stdout],stderr: Optional[Stderr],) -> None:self._kernel = kernelself._ui_element_registry = ui_element_registry+ self._interactive_mpl_registry = interactive_mpl_registryself._stream = streamself._stdout = stdoutself._stderr = stderr@@ -77,6 +80,11 @@ class RuntimeContext(threading.local):assert self._ui_element_registry is not Nonereturn self._ui_element_registry+ @property+ def interactive_mpl_registry(self) -> InteractiveMplRegistry:+ assert self._interactive_mpl_registry+ return self._interactive_mpl_registry+@propertydef stream(self) -> Stream:assert self._stream is not None@@ -114,6 +122,7 @@ _RUNTIME_CONTEXT = RuntimeContext()def initialize_context(kernel: Kernel,ui_element_registry: UIElementRegistry,+ interactive_mpl_registry: InteractiveMplRegistry,stream: Stream,stdout: Optional[Stdout],stderr: Optional[Stderr],@@ -122,7 +131,12 @@ def initialize_context(if _RUNTIME_CONTEXT._initialized:raise RuntimeError("RuntimeContext was already initialized.")_RUNTIME_CONTEXT.initialize(- kernel, ui_element_registry, stream, stdout, stderr+ kernel=kernel,+ ui_element_registry=ui_element_registry,+ interactive_mpl_registry=interactive_mpl_registry,+ stream=stream,+ stdout=stdout,+ stderr=stderr,)diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 3df115b274..1fe97f3534 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -39,6 +39,7 @@ from marimo._messaging.ops import ()from marimo._messaging.streams import Stderr, Stdout, Stream, redirect_streamsfrom marimo._output.rich_help import mddoc+from marimo._plugins.stateless.mpl._mpl import InteractiveMplRegistryfrom marimo._plugins.ui._core.registry import UIElementRegistryfrom marimo._plugins.ui._core.ui_element import MarimoConvertValueExceptionfrom marimo._runtime import cell_runner, dataflow@@ -285,6 +286,7 @@ class Kernel:self._delete_names(defs_to_delete, exclude_defs if exclude_defs is not None else set())+ get_context().interactive_mpl_registry.cleanup(cell_id)RemoveUIElements(cell_id=cell_id).broadcast()def _deactivate_cell(self, cell_id: CellId_t) -> set[CellId_t]:@@ -932,10 +934,10 @@ def launch_kernel(stderr = Stderr(stream) if is_edit_mode else Nonekernel = Kernel()- registry = UIElementRegistry()initialize_context(kernel=kernel,- ui_element_registry=registry,+ ui_element_registry=UIElementRegistry(),+ interactive_mpl_registry=InteractiveMplRegistry(),stream=stream,stdout=stdout,stderr=stderr,diff --git a/marimo/_smoke_tests/iplot.py b/marimo/_smoke_tests/iplot.pynew file mode 100644index 0000000000..efe5994d1f--- /dev/null+++ b/marimo/_smoke_tests/iplot.py@@ -0,0 +1,65 @@+# Copyright 2023 Marimo. All rights reserved.+import marimo++__generated_with = "0.1.18"+app = marimo.App()+++def __():+ import marimo as mo+ import numpy as np+ import matplotlib.pyplot as plt+ return mo, np, plt+++def __(mo, np, plt):+ def interactive_plot(seed = 42, size=100):+ # Generating random data+ np.random.seed(seed)+ x = np.random.randint(0, 100, size=size)+ y = np.random.randint(0, 100, size=size)+ z = np.random.randint(0, 100, size=size)++ # Creating a 3D scatter plot+ fig = plt.figure()+ ax = fig.add_subplot(111, projection='3d')+ ax.scatter(x, y, z, c='r', marker='o')++ ax.set_xlabel('X Label')+ ax.set_ylabel('Y Label')+ ax.set_zlabel('Z Label')++ return mo.mpl.interactive(fig)+ return interactive_plot,+++def __(interactive_plot):+ interactive_plot(size=10)+ return+++def __(interactive_plot):+ b = interactive_plot(size=20)+ b+ return b,+++def __(mo, plt):+ plt.plot([1, 2])+ mo.mpl.interactive(plt.gca())+ return+++def __(plt):+ plt.plot([3, 4])+ return+++if __name__ == "__main__":+ app.run()