29

If I make a tree using networkx and draw it, the nodes overlap. Is there a way to draw it so there is no overlap?

import matplotlib.pyplot as plt
import networkx as nx
T = nx.generators.balanced_tree(2, 5)
nx.draw(T)
plt.show()

enter image description here

Simd
  • 19,447
  • 42
  • 136
  • 271

3 Answers3

78

I am no expert in this, but here is code that uses the pydot library and its graph_viz dependency. These libraries come with Anaconda Python but are not installed by default, so first do this from the command prompt:

conda install pydot

Then here is code adapted from Circular Tree.

import matplotlib.pyplot as plt
import networkx as nx
import pydot
from networkx.drawing.nx_pydot import graphviz_layout

T = nx.balanced_tree(2, 5)

pos = graphviz_layout(T, prog="twopi")
nx.draw(T, pos)
plt.show()

If you adjust the window to make it square, the result is

enter image description here

Or, if you prefer a top-down tree, you could replace the string "twopi" in that code with "dot", and if you make the resulting window wider you get

enter image description here

Also, if you use the string "circo" instead and make the window wider, you get

enter image description here

Rory Daulton
  • 21,934
  • 6
  • 42
  • 50
15

If you want to do this without additional libraries, look at this answer, which shows a way to get a hierarchical tree layout or a circular layout purely in networkx:

https://stackoverflow.com/a/29597209/2966723

I'm planning to add a slightly modified version of this to networkx sometime soon.

Joel
  • 22,598
  • 6
  • 69
  • 93
1

Using pygraphviz AGraph(Dot) class.

python -m pip install --global-option=build_ext `
    --global-option="-IC:\Program Files\Graphviz\include" `
    --global-option="-LC:\Program Files\Graphviz\lib" `
    pygraphviz
import matplotlib.pyplot as plt
import networkx as nx

T = nx.balanced_tree(2, 5)

pos = nx.nx_agraph.graphviz_layout(T, prog="twopi")
nx.draw(T, pos)
plt.show()

nx.nx_pydot.graphviz_layout depends on the pydot package, which has known issues and is not actively maintained. Consider using nx.nx_agraph.graphviz_layout instead. See https://github.com/networkx/networkx/issues/5723

Honghe.Wu
  • 5,899
  • 6
  • 36
  • 47