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:

- dot – filter for drawing directed graphs
- neato – filter for drawing undirected graphs
- twopi – filter for radial layouts of graphs
- circo – filter for circular layout of graphs
- fdp – filter for drawing undirected graphs
- sfdp – filter for drawing large undirected graphs
- patchwork – filter for squarified tree maps
- osage – filter for array-based layouts

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