sswatson
sswatson11mo ago

Is there a way to get matplotlib plots to display as SVGs

Is there a way to get matplotlib plots to display in the notebook as SVGs rather than PNGs? The typical techniques for doing this are either Jupyter-specific or pertain to file-saving operations, from what I can tell.
3 Replies
Myles Scolnick
Myles Scolnick11mo ago
Yea it should be doable using the save file. I think we can save to a file buffer and then print it out Let me see if I can whip up an example actually looks like savefig is a file path and doesnt expose anything for in memory. still looking.. actually it does:
import marimo as mo
import matplotlib.pyplot as plt
import io

plt.plot([1, 2, 3], [4, 5, 6])
svg_buffer = io.StringIO()

plt.savefig(svg_buffer, format='svg')

svg_buffer.seek(0)
svg_data = svg_buffer.getvalue()
mo.Html(svg_data)
import marimo as mo
import matplotlib.pyplot as plt
import io

plt.plot([1, 2, 3], [4, 5, 6])
svg_buffer = io.StringIO()

plt.savefig(svg_buffer, format='svg')

svg_buffer.seek(0)
svg_data = svg_buffer.getvalue()
mo.Html(svg_data)
we could make this easier with a config flag - svg could be more performant / cleaner on the frontend in most cases than a PNG. curious, why do you want svg?
sswatson
sswatsonOP11mo ago
Thanks! This works fine. Re the reason, it's just aesthetic. I feel like vector graphics look sharper on the screen.
Myles Scolnick
Myles Scolnick11mo ago
Yeah I agree with that. We can consider a way to add a custom formatter to force this throughout the app