Created
January 4, 2020 21:18
-
-
Save tdhopper/1b41e04b121c988361dfc2582057f5b4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from io import BytesIO | |
def render_altair(chart): | |
b = BytesIO() | |
chart.save(b, scale_factor=2.0, format='png', webdriver='firefox') | |
b.seek(0) | |
return b.read() | |
import ast | |
def exec_then_eval(code, shell): | |
block = ast.parse(code, mode='exec') | |
# assumes last node is an expression | |
last = ast.Expression(block.body.pop().value) | |
_globals, _locals = {}, {} | |
shell.ex(compile(block, '<string>', mode='exec')) | |
return shell.ev(compile(last, '<string>', mode='eval')) | |
@magics_class | |
class AltairMagic(Magics): | |
@cell_magic | |
def altair(self, line, cell): | |
return Image(render_altair(exec_then_eval(cell, self.shell))) | |
ip = get_ipython() | |
ip.register_magics(AltairMagic) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment