Directed Tree Visualization using Python Programming

Directed tree visualization

Hello Python coder! Today, in this tutorial we will be learning how to visualize the popular directed tree structures that we encounter in our daily graphical world.

We wish to do the same thing i.e. convert the set of edges and nodes into a graphical format using the power of Python libraries. Before any delay let’s begin with the implementation.

Also Read: Graphs in Python using NetworkX

Code Implementation

We will start by creating a set of nodes and the corresponding nodes which will later form an edge to the nodes. To achieve the same, we will make use of Python dictionaries where the keys will be the start node and the values will represent the list of connecting nodes. Let’s focus on creating the tree-graph which we mentioned above.

graph = {
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F', 'G'],
    'D': [],
    'E': [],
    'F': [],
    'G': [],
}

Here we have kept the values for the nodes : D, E, F, and G as empty lists because the nodes are leaf nodes. Now to implement the graph, we will make use of a combination of libraries namely, networkx and graphviz. Each library has its purpose for the implementation of the visualization.

Creating the Directed Tree Graph using graphviz and networkx Library

The graphviz library allows us to easily create and visualize the structure of graphs. The library makes use of the definition of graphs in various formats (in our case its dictionary) and then converts it into a graph.  To keep it simple, for now, we will make use of the Digraph which is ‘directed graph’ where each edge can move from one node to another but not the opposite. As depth-limited search doesn’t support backtracking and hence we will make use of a directed graph.

Have a look at the code snippet below.

import networkx as nx
from graphviz import Digraph

G = nx.DiGraph(graph)

The code seems pretty simple till now.

Visualization of Directed Tree Graph using Digraph Class

Now to visualize the graph we need to use more functionalities of the Digraph class. First, we will create an object for graph visualization using the code snippet below. Here the comment is an option but to make the code more understandable we will add it as a comment for the directed graph.

GViz = Digraph(comment='The Directed Graph-Tree')

Now, we will add nodes and edges to the visualization using the code snippet below. First, we will iterate over the nodes of the graph using nodes function and add nodes to the GViz visualization using the node function. Then iterate over the edges of the graph using the edges function and then add the edge to the visualization using the edge function. For each edge, we need to add an edge connecting the two nodes specified by e[0] (source node) and e[1] (destination node).

for n in G.nodes():
    GViz.node(n)
for e in G.edges():
    GViz.edge(e[0], e[1])

Our visualization is saved inside GViz variable but to display it on the screen we will first save the graph using the render function in png form using the code snippet below. We add a few parameters, such as the name of the file, the format of the file, and the cleanup parameter which is responsible for cleaning up any additional file generated in the process.

GViz.render('DirectedGraph', format='png', cleanup=True)

Lastly, we will make use of the functionality of the IPython.display library to display the resulting graph on the screen. Have a look at the code snippet below which is pretty much self-explanatory i.e. simply displaying the graph in an image format.

from IPython.display import Image
Image(filename='DirectedGraph.png')

The resulting plot looks like shown below:

Directed Tree Visualization using Python Programming

Complete Code with More Complex Graph

import networkx as nx
from graphviz import Digraph
from IPython.display import Image

graph = {
    'A': ['B', 'C'],
    'B': ['D', 'E', 'F'],
    'C': ['G', 'H'],
    'D': ['I'],
    'E': ['J'],
    'F': ['K', 'L'],
    'G': ['M'],
    'H': ['N', 'O'],
    'I': [],
    'J': [],
    'K': [],
    'L': [],
    'M': [],
    'N': [],
    'O': [],
}

G = nx.DiGraph(graph)
GViz = Digraph(comment='The Directed Graph-Tree')

for n in G.nodes():
    GViz.node(n)
for e in G.edges():
    GViz.edge(e[0], e[1])

GViz.render('DirectedGraph', format='png', cleanup=True)
Image(filename='DirectedGraph.png')

The output of the code is as follows:

Directed Tree Visualization in Python

Also Read:

  1. Graph Plot of X and Y-Axis for given values as input in Python3
  2. Network Graphs: Creating Interactive Visualizations using Pyvis
  3. Graphs in Python using NetworkX

Happy Learning!

Leave a Reply

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