我想从 python networkx 生成父子关系数据。我正在使用多向图。我想使用下面的 javascript 以 html 格式生成我的图形:
https://bl.ocks.org/mbostock/4339184。
数据需要采用某种格式,就像上面链接中提到的flare.csv 文件一样。
所以,我的问题是如何像上面的 parent.child 关系数据一样从 networkx 生成数据?
首先,让我们根据您的描述创建一个图形(从技术上讲,是一棵树):
G=nx.DiGraph()
nodes = ['n0', 'n1', 'n1_1', 'n1_2', 'n2', 'n2_1', 'n2_2', 'n2_1_1']
edges = [('n0', 'n1'), ('n0', 'n2'),
('n1', 'n1_1'), ('n1', 'n1_2'),
('n2', 'n2_1'), ('n2', 'n2_2'),
('n2_1', 'n2_1_1')]
G.add_edges_from(edges)
G.add_nodes_from(nodes)
您应该首先获取图的根,然后从根遍历到每个节点。
Root 是唯一一个 in_degree 为零的节点,所以:
root = [k for k, v in G.in_degree().items() if v == 0]
# ['n0']
接下来,计算从根到每个叶子的最短路径。我们需要有一个排除根的节点列表。
all_but_root = [i for i in nodes if i not in root]
res =[]
for i in all_but_root:
res.append(nx.shortest_path(G, root[0], i))
此外,如果您想以一种轻松的方式获得正确格式的输出,您可以使用以下代码:
for i in res:
txt = ""
for j in i:
if j != i[-1]:
txt += j + "."
else:
txt += j + ","
print (txt)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句