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: fallback to png for matplotlib when in a non-interactive environment (#7924)
Myles Scolnickd5499a176ec1
diff --git a/marimo/_plugins/stateless/mpl/_mpl.py b/marimo/_plugins/stateless/mpl/_mpl.pyindex e6ac2d58d6..89d10ca447 100644--- a/marimo/_plugins/stateless/mpl/_mpl.py+++ b/marimo/_plugins/stateless/mpl/_mpl.py@@ -18,6 +18,7 @@ from pathlib import Pathfrom typing import TYPE_CHECKING, Any, Optional, Unionfrom marimo import _loggers+from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.builder import hfrom marimo._output.formatting import as_htmlfrom marimo._output.hypertext import Html@@ -444,6 +445,33 @@ def new_figure_manager_given_figure(return manager+def png_bytes(figure: Union[Figure, SubFigure, Axes]) -> bytes:+ """Convert a matplotlib figure to base64-encoded PNG bytes.++ The Html._mime_ method expects _repr_png_ to return bytes that+ can be decoded to a UTF-8 string, so we return base64-encoded data.+ """+ import base64++ from matplotlib.figure import Figure++ buf = io.BytesIO()+ if isinstance(figure, Figure):+ figure.savefig(buf, format="png", bbox_inches="tight")+ else:+ figure.figure.canvas.print_figure(buf, format="png")+ return base64.b64encode(buf.getvalue())+++class NonInteractiveMplHtml(Html):+ def __init__(self, figure: Union[Figure, SubFigure, Axes]) -> None:+ self._figure = figure+ super().__init__(as_html(figure).text)++ def _mime_(self) -> tuple[KnownMimeType, str]:+ return ("image/png", png_bytes(self._figure).decode())++class InteractiveMplHtml(Html):"""Html subclass that provides PNG fallback for ipynb export."""@@ -452,21 +480,8 @@ class InteractiveMplHtml(Html):super().__init__(text)def _repr_png_(self) -> bytes:- """Return base64-encoded PNG bytes for ipynb export fallback.-- The Html._mime_ method expects _repr_png_ to return bytes that- can be decoded to a UTF-8 string, so we return base64-encoded data.- """- import base64-- from matplotlib.figure import Figure-- buf = io.BytesIO()- if isinstance(self._figure, Figure):- self._figure.savefig(buf, format="png", bbox_inches="tight")- else:- self._figure.figure.canvas.print_figure(buf, format="png")- return base64.b64encode(buf.getvalue())+ """Return base64-encoded PNG bytes for ipynb export fallback."""+ return png_bytes(self._figure)@mddoc@@ -489,14 +504,6 @@ def interactive(figure: Union[Figure, SubFigure, Axes]) -> Html:Returns:Html: An interactive matplotlib figure as an `Html` object."""- # We can't support interactive plots in Pyodide- # since they require a WebSocket connection- if is_pyodide():- LOGGER.error(- "Interactive plots are not supported in Pyodide/WebAssembly"- )- return as_html(figure)-# No top-level imports of matplotlib, since it isn't a required# dependencyfrom matplotlib.axes import Axes@@ -506,9 +513,22 @@ def interactive(figure: Union[Figure, SubFigure, Axes]) -> Html:assert maybe_figure is not None, "Axes object does not have a Figure"figure = maybe_figure+ # We can't support interactive plots in Pyodide+ # since they require a WebSocket connection+ if is_pyodide():+ LOGGER.warning(+ "Interactive plots are not supported in Pyodide/WebAssembly"+ )+ return NonInteractiveMplHtml(figure)+ctx = get_context()if not isinstance(ctx, KernelRuntimeContext):- return as_html(figure)+ return NonInteractiveMplHtml(figure)++ # When virtual files are not supported (e.g., during HTML export),+ # fall back to static PNG instead of interactive plot+ if not ctx.virtual_files_supported:+ return NonInteractiveMplHtml(figure)# Figure Manager, Any type because matplotlib doesn't have typingsfigure_manager = new_figure_manager_given_figure(id(figure), figure)diff --git a/tests/_plugins/stateless/test_mpl.py b/tests/_plugins/stateless/test_mpl.pyindex 4f91120ffc..8094895789 100644--- a/tests/_plugins/stateless/test_mpl.py+++ b/tests/_plugins/stateless/test_mpl.py@@ -4,7 +4,6 @@ from unittest.mock import MagicMock, patchimport pytest-from marimo._dependencies.dependencies import DependencyManagerfrom marimo._output.hypertext import Htmlfrom marimo._plugins.stateless.mpl._mpl import (_convert_scheme_to_ws,@@ -15,10 +14,8 @@ from marimo._runtime.commands import DeleteCellCommandfrom marimo._runtime.runtime import Kernelfrom tests.conftest import ExecReqProvider-HAS_DEPS = DependencyManager.matplotlib.has()-[email protected](not HAS_DEPS, reason="matplotlib is not installed")[email protected]("matplotlib")def test_mpl_interactive_repr_png() -> None:"""Test that mpl.interactive provides PNG fallback for ipynb export."""import base64@@ -46,7 +43,7 @@ def test_mpl_interactive_repr_png() -> None:plt.close(fig)[email protected](not HAS_DEPS, reason="matplotlib is not installed")[email protected]("matplotlib")def test_mpl_interactive_mime_no_js() -> None:"""Test that _mime_ returns PNG when in no-JS mode (ipynb export)."""import matplotlib.pyplot as plt@@ -74,7 +71,7 @@ def test_mpl_interactive_mime_no_js() -> None:plt.close(fig)[email protected](not HAS_DEPS, reason="matplotlib is not installed")[email protected]("matplotlib")async def test_mpl_interactive(k: Kernel, exec_req: ExecReqProvider) -> None:from threading import Thread@@ -108,7 +105,7 @@ async def test_mpl_interactive(k: Kernel, exec_req: ExecReqProvider) -> None:await k.delete_cell(DeleteCellCommand(cell_id=cell.cell_id))[email protected](not HAS_DEPS, reason="matplotlib is not installed")[email protected]("matplotlib")async def test_mpl_show(k: Kernel, exec_req: ExecReqProvider) -> None:await k.run([@@ -123,7 +120,7 @@ async def test_mpl_show(k: Kernel, exec_req: ExecReqProvider) -> None:)[email protected](not HAS_DEPS, reason="matplotlib is not installed")[email protected]("matplotlib")def test_patch_javascript() -> None:from matplotlib.backends.backend_webagg_core import FigureManagerWebAgg@@ -340,3 +337,35 @@ def test_get_or_create_application_with_restart() -> None:# Should have started two threads (original + restart)assert mock_thread_class.call_count == 2++[email protected]("matplotlib")+def test_mpl_interactive_fallback_when_virtual_files_not_supported() -> None:+ """Test that mpl.interactive falls back to PNG when virtual_files_supported=False."""+ import matplotlib.pyplot as plt++ from marimo._plugins.stateless.mpl._mpl import interactive+ from marimo._runtime.context.kernel_context import KernelRuntimeContext++ # Create a simple figure+ fig, ax = plt.subplots()+ ax.plot([1, 2, 3], [1, 2, 3])++ # Mock the context to have virtual_files_supported=False (simulating HTML export)+ mock_ctx = MagicMock(spec=KernelRuntimeContext)+ mock_ctx.virtual_files_supported = False++ with patch(+ "marimo._plugins.stateless.mpl._mpl.get_context", return_value=mock_ctx+ ):+ # Call interactive - should fallback to static PNG+ result = interactive(fig)++ # Should return Html object+ assert isinstance(result, Html)+ # Should NOT contain iframe (interactive mode)+ assert "iframe" not in result.text.lower()+ # Should contain a PNG mimetype+ assert result._mime_()[0] == "image/png"++ plt.close(fig)