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.

fix: SVG data URL rendering in layout elements (#9043)

Daizue66299a9a1ee
diff --git a/marimo/_output/formatting.py b/marimo/_output/formatting.py
index 78451ed901..cac161002a 100644
--- a/marimo/_output/formatting.py
+++ b/marimo/_output/formatting.py
@@ -343,6 +343,8 @@ def mime_to_html(mimetype: KnownMimeType, data: Any) -> Html:
# when interpolating into markdown/a multiline string
return Html(flatten_string(f"<span>{escape(data)}</span>"))
elif mimetype == "image/svg+xml":
+ if isinstance(data, str) and data.startswith("data:image/svg+xml;"):
+ return Html(flatten_string(f'<img src="{data}" alt="" />'))
return Html(data)
elif mimetype.startswith("image"):
return Html(flatten_string(f'<img src="{data}" alt="" />'))
diff --git a/tests/_output/formatters/test_matplotlib.py b/tests/_output/formatters/test_matplotlib.py
index fe2849092a..7ac5f0464d 100644
--- a/tests/_output/formatters/test_matplotlib.py
+++ b/tests/_output/formatters/test_matplotlib.py
@@ -280,3 +280,42 @@ async def test_matplotlib_svg_rendering(
assert mime_type == "image/svg+xml"
assert isinstance(data, str)
assert data.startswith("data:image/svg+xml;base64,PD94")
+
+
[email protected](not HAS_MPL, reason="optional dependencies not installed")
+async def test_matplotlib_svg_rendering_in_layout(
+ executing_kernel: Kernel, exec_req: ExecReqProvider
+) -> None:
+ """Test that the SVG output can be used in a layout."""
+ from marimo._output.formatters.formatters import register_formatters
+
+ register_formatters(theme="light")
+
+ await executing_kernel.run(
+ [
+ exec_req.get(
+ """
+ import marimo as mo
+ import matplotlib.pyplot as plt
+
+ fmt = plt.rcParams["savefig.format"]
+ plt.rcParams["savefig.format"] = "svg"
+
+ # Create a simple figure
+ fig, ax = plt.subplots(figsize=(4, 3))
+ ax.plot([1, 2, 3], [1, 2, 3])
+ result = mo.hstack([fig])._mime_()
+
+ plt.rcParams["savefig.format"] = fmt
+ """
+ )
+ ]
+ )
+
+ # Get the formatted result from kernel globals
+ mime_type, data = executing_kernel.globals["result"]
+
+ assert mime_type == "text/html"
+ assert isinstance(data, str)
+ assert data.startswith("<div")
+ assert '<img src="data:image/svg+xml;base64,' in data