gpt4 book ai didi

python - 使用networkx打印python图表时保留左右 child

转载 作者:行者123 更新时间:2023-11-30 23:04:55 30 4
gpt4 key购买 nike

我正在尝试使用 python 中的 networkx 库打印二叉树。

但是,我无法保留左右 child 。有没有办法告诉图表先打印左 child ,然后打印右 child ?

import networkx as nx
G = nx.Graph()
G.add_edges_from([(10,20), (11,20)])
nx.draw_networkx(G)

enter image description here

编辑1:使用 pygraphwiz 时,它至少会产生一个有向图。所以,我对根节点有了更好的了解。

下面是我正在使用的代码:

import pygraphviz as pgv
G = pgv.AGraph()
G.add_node('20')
G.add_node('10')
G.add_node('11')
G.add_edge('20','10')
G.add_edge('20','11')
G.add_edge('10','7')
G.add_edge('10','12')

G.layout()
G.draw('file1.png')
from IPython.display import Image
Image('file1.png')

但是,这距离结构化格式还很远。接下来我将发布我发现的内容。新图表如下所示(至少我们知道根源):

Root to Leaf Binary tree

编辑2:对于那些遇到安装问题的人,请refer to this post. The answer to this - 如果您想在 Windows 64 位上安装 pygraphviz,它非常有帮助。

最佳答案

我相信 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()

给出了下图。 enter image description here

关于python - 使用networkx打印python图表时保留左右 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33439810/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com