19 Jul

NetworkX visualization with Graphviz (Example)

NetworkX visualization with Graphviz (Example)

If you are trying to visualize a nice graph with NetworkX, you should be exhausted by now. After all, NetworkX only provides basic functionality for graph visualization. The main goal of NetworkX is to enable graph analysis. For everything other than basic visualization, it’s advisable to use a separate specialized library. In my case, I choose Graphviz. It’s simplistic to get an attractive visualization of a NetworkX graph with Graphviz. I’m taking a gradual start, but you may skip to “NetworkX with Graphviz” directly.

NetworkX with Matplotlib

Let’s start small, so we can see the issue here. I’m trying to plot a simple directed graph (more like a tree).

The main issue I had here was the layout. When the number of nodes increases, the layout becomes messy. And the none of the limited set of layouts seems to be working. So the first option is to use a graphviz layout without much change.

Using Graphviz layout with the existing plot

Here we are just trying to get a better layout without any change to the graph look and feel. Note that you need to install the Graphviz before going to next step. (download). With Windows, you can download the setup from the above page. For Ubuntu, you can easily install that with below command (Graphviz and some needed libraries)

Then we use the Graphviz layout (I use the default one here) to generate the positions of the nodes. Here I have exported it as a png, rather than showing it.

As you can see the layout already looks better. However if you want to take the full advantage/power of Graphviz, you need to convert this to a Graphviz graph.

NetworkX with Graphviz

We can directly convert to a Graphviz graph. First, install pygraphviz. Then run the code.

You can use an intermediate dot file, if you are working with 2 applications or if you want to store the graph structure.

Both of these will generate the following graph. You can do any modification as you wish (Documentation).

Last updated by .

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.