Skip to content

Instantly share code, notes, and snippets.

@goerz
Created March 28, 2017 17:55
Show Gist options
  • Save goerz/178811cece8e96ae5378be71b8ea904a to your computer and use it in GitHub Desktop.
Save goerz/178811cece8e96ae5378be71b8ea904a to your computer and use it in GitHub Desktop.
Render Sympy Expression as graphical tree inside IPython notebook
def render_sympy_tree(expr):
"""Render the given Sympy Expression as a graphical tree, inside an IPython notebook"""
from sympy.printing.dot import dotprint
import tempfile
import subprocess
import os
from IPython.display import SVG
with tempfile.NamedTemporaryFile(mode='w', delete=False) as out_fh:
out_fh.write(dotprint(expr))
subprocess.run(['/usr/bin/dot', '-Tsvg', out_fh.name, '-o', out_fh.name + ".svg"])
svg = SVG(filename=(out_fh.name + ".svg"))
os.unlink(out_fh.name)
os.unlink(out_fh.name + ".svg")
return svg
@goerz
Copy link
Author

goerz commented Mar 28, 2017

I'm having problems with dot inside a conda environment (due to #1357), which also breaks the graphviz package. The above code solves the problem of rendering the graphviz tree representation of Sympy expressions in Python 3.5, via a temporary file. Note the use of the system /usr/bin/dot instead of just dot (which would refer to the broken binary that's installed by conda).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment