DAGVIZ examples using Dagre-D3¶

This notebook demonstrates drawing DAG's using dagre-d3.

Simple DAG¶

This example is taken from D3-DAG's example section. We start by importing DAGVIZ and constructing the DAG object. The DAG object is a simple wrapper around networkx's DiGraph.

In [1]:
import networkx as nx
from dagviz import Dagre
In [2]:
g = nx.DiGraph()

Next we start adding nodes and edges.

In [3]:
for i in range(21):
    g.add_node(f"n{i}")
In [4]:
g.add_edge("n1", "n14")
g.add_edge("n8", "n14")
g.add_edge("n8", "n0")
g.add_edge("n0", "n16")
g.add_edge("n16", "n10")
g.add_edge("n21", "n10")
g.add_edge("n21", "n12")
g.add_edge("n21", "n7")
g.add_edge("n12", "n4")
g.add_edge("n12", "n13")
g.add_edge("n4", "n9")
g.add_edge("n4", "n13")
g.add_edge("n13", "n20")
g.add_edge("n9", "n18")
g.add_edge("n9", "n6")
g.add_edge("n18", "n5")
g.add_edge("n15", "n6")
g.add_edge("n19", "n17")
g.add_edge("n17", "n6")
g.add_edge("n17", "n7")
g.add_edge("n2", "n11")
g.add_edge("n11", "n3")
g.add_edge("n3", "n7")

Rendering the graph is as simple as you would expect it to be in Jupyter.

In [5]:
Dagre(g)
Out[5]:

Linux kernel commit history¶

Let's try something a bit more challenging: the last thousand commits of the Linux kernel git repository (dated June 20th, 2021). I generated a git log for the linux kernel using

git log --oneline --parents > linux-git-log.txt

This gives a long list of lines like:

cba5e97280f5 9df7f15ee922 a7b359fc6a37 Merge tag 'sched_urgent_for_v5.13_rc6' of git://git.kernel.org/pub/scm/linux/kernel/git/tip/tip

Where the first token is this commit hash, the subsequent hashes are parents, and the text is the summary.

The script below parses this log and turns it into a networkx graph:

In [6]:
H = nx.DiGraph()
hashlen = None
with open("../linux-git-log.txt", "rt") as fs:
    for i, l in enumerate(fs):
        if i==1000:
            break
        tokens = l.rstrip().split(" ")
        if hashlen is None:
            hashlen = len(tokens[0])
        commits = []
        for j, t in enumerate(tokens):
            if len(t)!=hashlen:
                break;
            try:
                commits.append(int(t,16))
            except ValueError:
                break
        H.add_node(commits[0], label=" ".join(tokens[j:]))
        for p in commits[1:]:
            H.add_edge(commits[0], p)
        

As this graph is rather big, the rendering will take some time, and you will need to zoom and pan around a bit to find it, but the process is very simple:

In [7]:
Dagre(H)
Out[7]:

Dagre features¶

The dagre visualization support non-string nodes...

In [8]:
g = nx.DiGraph()
g.add_edge(0,1)
Dagre(g)
Out[8]:

and nodes and edges with labels:

In [9]:
h = nx.DiGraph()
h.add_node(0, label="I'm a long label")
h.add_edge(0,1, label="I'm a label too")
Dagre(h)
Out[9]:
In [ ]: