Reputation: 1053
I am using networkX to generate a tree structure as follows (I am following the answer of this question).
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_node("ROOT")
for i in range(5):
G.add_node("Child_%i" % i)
G.add_node("Grandchild_%i" % i)
G.add_node("Greatgrandchild_%i" % i)
G.add_edge("ROOT", "Child_%i" % i)
G.add_edge("Child_%i" % i, "Grandchild_%i" % i)
G.add_edge("Grandchild_%i" % i, "Greatgrandchild_%i" % i)
# write dot file to use with graphviz
# run "dot -Tpng test.dot >test.png"
nx.write_dot(G,'test.dot')
# same layout using matplotlib with no labels
plt.title('draw_networkx')
pos=nx.graphviz_layout(G, prog='dot')
nx.draw(G, pos, with_labels=False, arrows=False)
plt.savefig('nx_test.png')
I want to draw a tree as in the following figure.
However, I am getting an error saying AttributeError: module 'networkx' has no attribute 'write_dot'
. My networkx version is 1.11 (using conda). I tried different hacks, but none of them worked.
So, I am interested in knowing if there is another way of drawing tree structures using networkx to get an output similar to the one mentioned in the figure. Please let me know.
Upvotes: 5
Views: 10537
Reputation: 11443
You can draw digraph entirely with pygraphviz
.
Following steps needs to be followed first as pygraphviz
does not work without graphviz
(as of now).
pygraphviz
wheel file from http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygraphvizpip install pygraphviz‑1.3.1‑cp34‑none‑win32.whl
dot.exe
to host path
e.g. on windows control-panel ->system -> edit environment variables -> Modify PATHAfter that dot
and png
files can be created as below.
Working Code
import pygraphviz as pgv
G=pgv.AGraph(directed=True)
#Attributes can be added when adding nodes or edge
G.add_node("ROOT", color='red')
for i in range(5):
G.add_node("Child_%i" % i, color='blue')
G.add_node("Grandchild_%i" % i, color='blue')
G.add_node("Greatgrandchild_%i" % i, color='blue')
G.add_edge("ROOT", "Child_%i" % i, color='blue')
G.add_edge("Child_%i" % i, "Grandchild_%i" % i, color='blue')
G.add_edge("Grandchild_%i" % i, "Greatgrandchild_%i" % i, color='blue')
# write to a dot file
G.write('test.dot')
#create a png file
G.layout(prog='dot') # use dot
G.draw('file.png')
Upvotes: 2
Reputation: 704
I think this issue was solved on networkx 2.x, but before that you should be explicit import of the function like this.
from networkx.drawing.nx_agraph import write_dot
or
from networkx.drawing.nx_pydot import write_dot
I hope this works.
Upvotes: 2