feat: add Matplotlib SVG output support#8312
feat: add Matplotlib SVG output support#8312daizutabi wants to merge 3 commits intomarimo-team:mainfrom
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
When Matplotlib figures are rendered as SVGs, some elements (texts, scatter points) do not appear in the rendered output within the marimo frontend. Root CauseThe marimo frontend performs sanitization of SVG content to mitigate XSS vulnerabilities. This sanitization process removes certain SVG elements that are essential for displaying these graphical components. For instance, Matplotlib generates SVGs where text glyphs are defined once in a Proposed Solutions:
Which solution would you prefer to proceed with? |
Proposed Solutions (Addendum):
Personal Opinion: Based on the balance of simplicity, direct problem solving, and preserving user experience (especially the drag-and-drop feature), Solution 4 (Base64 Encoded SVG Data URI via |
… frontend rendering.


📝 Summary
This PR introduces support for rendering Matplotlib figures as SVG output within marimo notebooks. Previously, Matplotlib figures were primarily rendered as PNGs, even when users might prefer SVG for its scalability.
The core change involves enhancing marimo's Matplotlib backend to respect user preferences for
rcParams["savefig.format"].Closes #6287
🔍 Description of Changes
marimo/_output/mpl.pyto add logic that allows Matplotlib figures to be rendered as SVG. Whenmatplotlib.rcParams["savefig.format"]is set to"svg", the_render_figure_mimebundlefunction now directly returns the figure as a SVG string. The existing PNG rendering path is used as a fallback._render_figure_mimebundleinmarimo/_output/mpl.pyhas been updated to accurately reflect the dual output capabilities (SVG or PNG) and their respective return types.test_matplotlib_svg_rendering, has been added totests/_output/formatters/test_matplotlib.py. This test verifies that Matplotlib figures are correctly output as SVG whensavefig.formatis configured appropriately.Limitation
This PR enhances Matplotlib SVG output handling by ensuring the MIME type is correctly set to
image/svg+xml. This is the expected standard for standalone SVG content, improving compatibility, particularly foripynbexports.However, a limitation has been identified regarding the display of text (such as ticks and labels) in SVGs generated with
matplotlib.rcParams["svg.fonttype"] = "path"(Matplotlib's default, which uses<defs>and<use>elements for text glyphs). The frontend currently skips or fails to render these<use>elements.Workaround
Users can mitigate this by setting
matplotlib.rcParams["svg.fonttype"] = "none"in their Python code. This instructs Matplotlib to embed text directly as<text>elements rather than<use>references to paths, which the frontend can then process correctly.Screenshots
PNG
SVG ('svg.fonttype' = 'none')
SVG ('svg.fonttype' = 'path')
📋 Checklist