Graphviz setup on a Mac to be used with Python/Jupyter
Graphviz is a powertful software for visualization of graphs. Back in the days, particularly during my time as a PhD candidate, I used Graphviz pretty actively, often in combination with Jupyter notebooks. Back then, I had a custom Conda environment, which contained all the necessary packages. One of those was nxpd, which is not actively maintained. I got curious what might be a today’s solution, without requiring Conda and with minimal selection of dependencies. This post contains my notes on that.
The Graphviz software can be installed using Brew:
$ brew install graphviz
This gives access to dot rendering program in your terminal.
Furthermore, there are several Graphviz-related packages you can install from PyPI:
- graphviz: simple tool that invokes
dot. - pygraphviz: full-blown library containing Graphviz.
- graphviz-python: Graphviz’s official Python bindings.
- pydot: tool for reading and constructing files in DOT language.
I decided to follow this blog post, and went along with the first option:
$ pip install graphviz
As such, the setup comprises Graphviz’s dot on your $PATH together with the graphviz Python library.
You can, for instance, convert networkx.DiGraph to graphviz.Digraph:
import graphviz
import networkx
def to_graphviz(nxg: networkx.DiGraph) -> graphviz.Digraph:
graph = graphviz.Digraph()
for node_name in nxg.nodes:
graph.node(node_name)
graph.edges(tuple(nxg.edges))
return graph
When working in a Jupyter notebook, and having an object named graph of type graphviz.Digraph, the simple expression
graph
will render the graph inline in the notebook. The rendered result will be in SVG, which is pretty neat, given the advantages of vector graphics.