如何从 networkx 生成父子关系数据以使用 d3.js?
How to generate parent child relation data from networkx to work with d3.js?
我想从 python networkx 生成父子关系数据。我正在使用多重图。我想使用下面的 javascript 以 html 格式生成我的图表:
https://bl.ocks.org/mbostock/4339184。
数据需要采用某种格式,如上面 link 中提到的 flare.csv 文件中的格式。
所以,我的问题是如何从 networkx 生成像上面那样的数据 parent.child 关系数据?
首先,让我们根据您的描述创建一个图表(从技术上讲,是一棵树):
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)
你应该先得到图的根,然后从根遍历到每一个节点。
根节点是唯一一个 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)
我想从 python networkx 生成父子关系数据。我正在使用多重图。我想使用下面的 javascript 以 html 格式生成我的图表:
https://bl.ocks.org/mbostock/4339184。
数据需要采用某种格式,如上面 link 中提到的 flare.csv 文件中的格式。
所以,我的问题是如何从 networkx 生成像上面那样的数据 parent.child 关系数据?
首先,让我们根据您的描述创建一个图表(从技术上讲,是一棵树):
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)
你应该先得到图的根,然后从根遍历到每一个节点。
根节点是唯一一个 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)