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: matplotlib with legends outside of bbox (#1512)

Myles Scolnicka90b7a4e44f5
diff --git a/marimo/_output/formatters/matplotlib_formatters.py b/marimo/_output/formatters/matplotlib_formatters.py
index 3ec54a59a6..f6d58f45c3 100644
--- a/marimo/_output/formatters/matplotlib_formatters.py
+++ b/marimo/_output/formatters/matplotlib_formatters.py
@@ -35,7 +35,7 @@ class MatplotlibFormatter(FormatterFactory):
def mime_data_artist(artist: Artist) -> tuple[KnownMimeType, str]:
buf = io.BytesIO()
- artist.figure.savefig(buf, format="png") # type: ignore
+ artist.figure.savefig(buf, format="png", bbox_inches="tight") # type: ignore
mimetype: KnownMimeType = "image/png"
plot_bytes = base64.b64encode(buf.getvalue())
return (
diff --git a/marimo/_output/mpl.py b/marimo/_output/mpl.py
index bb140252c9..f382e9ce8b 100644
--- a/marimo/_output/mpl.py
+++ b/marimo/_output/mpl.py
@@ -40,7 +40,7 @@ def close_figures() -> None:
def _internal_show(canvas: FigureCanvasBase) -> None:
buf = io.BytesIO()
buf.seek(0)
- canvas.figure.savefig(buf, format="png")
+ canvas.figure.savefig(buf, format="png", bbox_inches="tight")
plt.close(canvas.figure)
mimetype: KnownMimeType = "image/png"
plot_bytes = base64.b64encode(buf.getvalue())
diff --git a/marimo/_plugins/stateless/mpl/_mpl.py b/marimo/_plugins/stateless/mpl/_mpl.py
index 0cb6306845..0ab2e538c1 100644
--- a/marimo/_plugins/stateless/mpl/_mpl.py
+++ b/marimo/_plugins/stateless/mpl/_mpl.py
@@ -106,7 +106,9 @@ def create_application(
mime_type = mimetypes.types_map.get(fmt, "binary")
buff = io.BytesIO()
figure_manager = figure_managers.get(figure_id)
- figure_manager.canvas.figure.savefig(buff, format=fmt)
+ figure_manager.canvas.figure.savefig(
+ buff, format=fmt, bbox_inches="tight"
+ )
return Response(content=buff.getvalue(), media_type=mime_type)
async def websocket_endpoint(websocket: WebSocket) -> None:
diff --git a/marimo/_smoke_tests/bugs/1510.py b/marimo/_smoke_tests/bugs/1510.py
new file mode 100644
index 0000000000..e2cedb8c07
--- /dev/null
+++ b/marimo/_smoke_tests/bugs/1510.py
@@ -0,0 +1,32 @@
+import marimo
+
+__generated_with = "0.6.11"
+app = marimo.App()
+
+
+def __():
+ import matplotlib.pyplot as plt
+ plt.plot([1, 2])
+ plt.legend(["asdf"], bbox_to_anchor=(1.2, 0.5))
+ return plt,
+
+
+def __(plt):
+ plt.plot([1, 2])
+ plt.legend(["asdf"], bbox_to_anchor=(1.2, 0.5))
+ plt.show()
+ return
+
+
+def __():
+ import matplotlib
+ backend = matplotlib.get_backend()
+ backend
+ return backend, matplotlib
+
+
+if __name__ == "__main__":
+ app.run()