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: special case list formatter for matplotlib. (#1130)

Akshay Agrawal4c0edbd208ff
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index c8fa00baa8..fa851b6842 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -142,6 +142,11 @@ class DependencyManager:
"""Return True if plotly is installed."""
return importlib.util.find_spec("plotly") is not None
+ @staticmethod
+ def has_matplotlib() -> bool:
+ """Return True if plotly is installed."""
+ return importlib.util.find_spec("matplotlib") is not None
+
@staticmethod
def has_anywidget() -> bool:
"""Return True if anywidget is installed."""
diff --git a/marimo/_output/formatters/structures.py b/marimo/_output/formatters/structures.py
index 37991ee48c..0059e539b9 100644
--- a/marimo/_output/formatters/structures.py
+++ b/marimo/_output/formatters/structures.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import json
+import sys
from typing import Any, Union
from marimo._messaging.mimetypes import KnownMimeType
@@ -44,6 +45,23 @@ class StructuresFormatter(FormatterFactory):
def _format_structure(
t: Union[tuple[Any, ...], list[Any], dict[str, Any]],
) -> tuple[KnownMimeType, str]:
+ if t and "matplotlib" in sys.modules:
+ # Special case for matplotlib:
+ #
+ # plt.plot() returns a list of lines 2D objects, one for each
+ # line, which typically have identitical figures. Without this
+ # special case, if a plot had (say) 5 lines, it would be shown
+ # 5 times.
+ import matplotlib.artist # type: ignore
+
+ if all(isinstance(i, matplotlib.artist.Artist) for i in t):
+ figs = [getattr(i, "figure", None) for i in t]
+ if all(f is not None and f == figs[0] for f in figs):
+ matplotlib_formatter = formatting.get_formatter(
+ figs[0]
+ )
+ if matplotlib_formatter is not None:
+ return matplotlib_formatter(figs[0])
try:
formatted_structure = format_structure(t)
except CyclicStructureError:
diff --git a/tests/_output/formatters/test_structures.py b/tests/_output/formatters/test_structures.py
new file mode 100644
index 0000000000..48e6a8f6c6
--- /dev/null
+++ b/tests/_output/formatters/test_structures.py
@@ -0,0 +1,33 @@
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._runtime.runtime import Kernel
+from tests.conftest import ExecReqProvider
+
+
+async def test_matplotlib_special_case(
+ executing_kernel: Kernel, exec_req: ExecReqProvider
+) -> None:
+ if DependencyManager.has_matplotlib() and DependencyManager.has_numpy():
+ from marimo._output.formatters.formatters import register_formatters
+
+ register_formatters()
+
+ await executing_kernel.run(
+ [
+ exec_req.get(
+ """
+ import numpy as np
+ import matplotlib.pyplot as plt
+ from marimo._output.formatting import get_formatter
+
+ arr = np.random.randn(12, 5)
+ lines = plt.plot(arr)
+ formatter = get_formatter(lines)
+ """
+ )
+ ]
+ )
+
+ formatter = executing_kernel.globals["formatter"]
+ lines = executing_kernel.globals["lines"]
+ assert formatter is not None
+ assert formatter(lines)[0].startswith("image")