Visualizing Networks with Graphviz

In this post I’ll look at building graphs in Python using the graphviz module. This assumes that you’ve installed graphviz itself, which is easy enough on a Mac using homebrew. (Simply run: brew install graphviz.) I had two requirements for my graphs: I needed them to be directed, and I wanted to use the edge thickness to illustrate the strength of a connection. The first part was dead simple, but the second part required a little hunting.

The set up is pretty simple: we create a graph object, add some nodes, and then add some edges using the nodes. The engine argument defines how the nodes are arranged. The penwidth argument expects a string (not a digit) and adjusts the thickness of the arrow connecting the nodes.

from graphviz import Digraph

# define a graph object
g = Digraph( engine='sfdp' )

# define some nodes
g.node('A')
g.node('B')
g.node('C')

# define some edges between the nodes
g.edge('A','B')
g.edge('A','C')
g.edge('B','C',penwidth='3')

# render a pdf and graph file
g.render('graph.gv')

For reference, the available engines are as follows:

  1. dot – filter for drawing directed graphs
  2. neato – filter for drawing undirected graphs
  3. twopi – filter for radial layouts of graphs
  4. circo – filter for circular layout of graphs
  5. fdp – filter for drawing undirected graphs
  6. sfdp – filter for drawing large undirected graphs
  7. patchwork – filter for squarified tree maps
  8. osage – filter for array-based layouts

This and other information can be found on the found on the graphviz man page.

Leave a Reply

Your email address will not be published. Required fields are marked *