HexxCube
HexxCube2mo ago

Show matplotlib inline plot as svg instead of png

The inline matplotlib plots are shown as png and look blurry on my 4k monitor. Increasing the plots dpi only scales it up. Is it possible to display them as a svg instead? I already tried locally changing: marimo/_output/mpl.py
def _internal_show(canvas: FigureCanvasBase) -> None:
buf = io.BytesIO()
buf.seek(0)
canvas.figure.savefig(buf, format="png", bbox_inches="tight")
plt.close(canvas.figure)
mimetype: KnownMimeType = "image/png"
plot_bytes = base64.b64encode(buf.getvalue())
CellOp.broadcast_console_output(
channel=CellChannel.MEDIA,
mimetype=mimetype,
data=build_data_url(mimetype=mimetype, data=plot_bytes),
cell_id=None,
status=None,
)
def _internal_show(canvas: FigureCanvasBase) -> None:
buf = io.BytesIO()
buf.seek(0)
canvas.figure.savefig(buf, format="png", bbox_inches="tight")
plt.close(canvas.figure)
mimetype: KnownMimeType = "image/png"
plot_bytes = base64.b64encode(buf.getvalue())
CellOp.broadcast_console_output(
channel=CellChannel.MEDIA,
mimetype=mimetype,
data=build_data_url(mimetype=mimetype, data=plot_bytes),
cell_id=None,
status=None,
)
to
def _internal_show(canvas: FigureCanvasBase) -> None:
buf = io.BytesIO()
buf.seek(0)
canvas.figure.savefig(buf, format="svg", bbox_inches="tight")
plt.close(canvas.figure)
mimetype: KnownMimeType = "image/svg+xml"
plot_bytes = base64.b64encode(buf.getvalue())
CellOp.broadcast_console_output(
channel=CellChannel.MEDIA,
mimetype=mimetype,
data=build_data_url(mimetype=mimetype, data=plot_bytes),
cell_id=None,
status=None,
)
def _internal_show(canvas: FigureCanvasBase) -> None:
buf = io.BytesIO()
buf.seek(0)
canvas.figure.savefig(buf, format="svg", bbox_inches="tight")
plt.close(canvas.figure)
mimetype: KnownMimeType = "image/svg+xml"
plot_bytes = base64.b64encode(buf.getvalue())
CellOp.broadcast_console_output(
channel=CellChannel.MEDIA,
mimetype=mimetype,
data=build_data_url(mimetype=mimetype, data=plot_bytes),
cell_id=None,
status=None,
)
but it still shows up as a png.
GitHub
marimo/marimo/_output/mpl.py at main · marimo-team/marimo
A reactive notebook for Python — run reproducible experiments, execute as a script, deploy as an app, and version with git. - marimo-team/marimo
2 Replies
Myles Scolnick
Myles Scolnick2mo ago
You can do this without needing to update marimo:
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)
and of course, you can create a function to reuse this across multiple plots
HexxCube
HexxCubeOP2mo ago
Many thanks for putting this together!