For*_*ner 2 python tree graph networkx pygraphviz
我正在尝试使用 python 中的networkx 库打印二叉树。
\n\n可是,我却无法保住左右两个孩子。有没有办法告诉图表先打印左孩子,然后打印右孩子?
\n\nimport networkx as nx\nG = nx.Graph()\nG.add_edges_from([(10,20), (11,20)])\nnx.draw_networkx(G)\nRun Code Online (Sandbox Code Playgroud)\n\n\n\n编辑1:使用 pygraphwiz 时,它至少会产生一个有向图。所以,我对根节点有了更好的了解。
\n\n下面是我正在使用的代码:
\n\nimport pygraphviz as pgv\nG = pgv.AGraph()\nG.add_node(\'20\')\nG.add_node(\'10\')\nG.add_node(\'11\')\nG.add_edge(\'20\',\'10\')\nG.add_edge(\'20\',\'11\')\nG.add_edge(\'10\',\'7\')\nG.add_edge(\'10\',\'12\')\n\nG.layout()\nG.draw(\'file1.png\')\nfrom IPython.display import Image\nImage(\'file1.png\')\nRun Code Online (Sandbox Code Playgroud)\n\n但是,这距离结构化格式还很远。接下来我将发布我发现的内容。新图如下所示(至少我们知道根):
\n\n\n\n编辑2:对于那些遇到安装问题的人,请参阅这篇文章。 答案是——如果你想在 Windows 64 位上安装 pygraphviz,它非常有帮助。
\n我相信 Networkx 不适合二叉树,但您可以自己设置节点位置。我编写了以下算法来设置节点位置,但它对于关键节点排序为 [0,1,...] 的完整或完整二叉树效果很好。
def full_tree_pos(G):
n = G.number_of_nodes()
if n == 0 : return {}
# Set position of root
pos = {0:(0.5,0.9)}
if n == 1:
return pos
# Calculate height of tree
i = 1
while(True):
if n >= 2**i and n<2**(i+1):
height = i
break
i+=1
# compute positions for children in a breadth first manner
p_key = 0
p_y = 0.9
p_x = 0.5
l_child = True # To indicate the next child to be drawn is a left one, if false it is the right child
for i in xrange(height):
for j in xrange(2**(i+1)):
if 2**(i+1)+j-1 < n:
print 2**(i+1)+j-1
if l_child == True:
pos[2**(i+1)+j-1] = (p_x - 0.2/(i*i+1) ,p_y - 0.1)
G.add_edge(2**(i+1)+j-1,p_key)
l_child = False
else:
pos[2**(i+1)+j-1] = (p_x + 0.2/(i*i+1) ,p_y - 0.1)
l_child = True
G.add_edge(2**(i+1)+j-1,p_key)
p_key += 1
(p_x,p_y) = pos[p_key]
return pos
G = nx.Graph()
G.add_nodes_from(xrange(25))
pos = full_tree_pos(G)
nx.draw(G, pos=pos, with_labels=True)
plt.show()
Run Code Online (Sandbox Code Playgroud)