Skip to content

Commit

Permalink
feat: matplotlib support for display(figure)
Browse files Browse the repository at this point in the history
This makes it behave more like the Jupyter notebook environment.
  • Loading branch information
maartenbreddels committed Mar 6, 2024
1 parent b83b3e3 commit 21d8443
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions solara/server/shell.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import io
import sys
from binascii import b2a_base64
from threading import local
from unittest.mock import Mock

Expand Down Expand Up @@ -184,8 +186,23 @@ def init_history(self):

def init_display_formatter(self):
super().init_display_formatter()
assert self.display_formatter is not None
self.display_formatter.ipython_display_formatter = reacton.patch_display.ReactonDisplayFormatter()

# matplotlib support for display(figure)
# IPython.core.pylabtools has support for this, but it requires importing matplotlib
# which would slow down startup, so we do it here using for_type using a string as argument.
def encode_png(figure, **kwargs):
f = io.BytesIO()
format = "png"
figure.savefig(f, format=format, **kwargs)
bytes_data = f.getvalue()
base64_data = b2a_base64(bytes_data, newline=False).decode("ascii")
return base64_data

formatter = self.display_formatter.formatters["image/png"]
formatter.for_type("matplotlib.figure.Figure", encode_png)

def init_display_pub(self):
super().init_display_pub()
self.display_pub.register_hook(self.display_in_reacton_hook)
Expand Down

0 comments on commit 21d8443

Please sign in to comment.