I am trying to display a tree graph of my class hierarchy using networkx.
I have it all graphed correctly, and it displays fine. But as a circular graph with crossing edges, it is a pure hierarchy, and it seems I ought to be able to display it as a tree.
I have googled this extensively, and every solution offered involves using pygraphviz
... but PyGraphviz does not work with Python 3 (documentation from the pygraphviz site).
Has anyone been able to get a tree graph display in Python 3?
Here is a solution for large trees. It is a modification of Joel's recursive approach that evenly spaces nodes at each level.
Joel's example will look like this:
And this is a more complex graph (rendered using plotly):
I modified slightly so that it would not infinitely recurse.
edit (27 Aug 2018) If you want to create a plot with the nodes appearing as rings around the root node, the code right at the bottom shows a simple modification to do this
edit (17 Sept 2017) I believe the trouble with pygraphviz that OP was having should be fixed by now. So pygraphviz is likely to be a better solution that what I've got below.
Here is a simple recursive program to define the positions:
and an example usage:
Ideally this should rescale the horizontal separation based on how wide things will be beneath it. I'm not attempting that now.
Radial expansion
Let's say you want the plot to look like:
Here's the code for that:
edit - thanks to Deepak Saini for noting an error that arises in directed graphs (comments in the example code now show how to fix that)
The simplest way to get a nice-looking tree graph display in Python 2 or 3 without PyGraphviz is to use PyDot (https://pypi.python.org/pypi/pydot). Whereas PyGraphviz provides an interface to the whole of Graphviz, PyDot only provides an interface to Graphviz's Dot tool, which is the only one you need if what you're after is a hierarchical graph / a tree. If you want to create your graph in NetworkX rather than PyDot, you can use NetworkX to export a PyDot graph, as in the following:
Note that Graphviz and PyDot need to be installed for the above to work correctly.
Warning: I have experienced problems when using PyDot to draw graphs with node attribute dictionaries exported from NetworkX - sometimes the dictionaries seem to be exported with quotation marks missing from strings, which causes the
write
method to crash. This can be avoided by leaving out the dictionaries.For a directed graph, Since neighbors(x) include only the succesors(x), so you have to remove the lines:
Also, a better option would be this: