在NetworkX中遍历路径上的节点编号

时间:2019-04-21 19:57:07

标签: networkx

以下代码显示了在网格图中通过网络遍历图的示例。

# A “ladder graph” of length 5.
import networkx as nx
import matplotlib.pyplot as plt

G = nx.grid_2d_graph(4, 5)
pos = nx.spring_layout(G, iterations=100)
# nx.draw(G, pos)
# plt.show()

nx.draw(G, pos, )
starting = choice(list(G.nodes))
# print("starting")
path = list(nx.dfs_edges(g, source = starting)) # shows path
# print(path) #
j = [i[0] for i in path]


print(j)
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_edges(G, pos, edgelist=path, edge_color='r', width=6)

plt.title('Using Depth-First Search')
plt.show()

但是,如果我能看到图形以哪个节点开始作为图形本身上的标签(例如0、1、2,....)以及节点的确切顺序,我觉得这将更加有用。沿着这条路。我了解到,对于某些节点(可能会被多次访问)而言,这可能有些笨拙。

有人可以帮我吗?

enter image description here

1 个答案:

答案 0 :(得分:0)

花点时间。比我想象的要难。

G = nx.grid_2d_graph(4, 5)
pos = dict( (n, n) for n in G.nodes() ) 

path = list(nx.dfs_edges(G, source = choice(list(G.nodes)))) # shows path

# create old_dict from an enumeration of the path
old_dict, new_dict = {v: k for v, k in enumerate([path[0][0]] + [i[1] for i in path] )}, {}

# invert old_dict to get new_dict, which returns order in the path of given node
for key, value in old_dict.items(): new_dict[value] = new_dict[value] + [key] if value in new_dict else [key]

# format new_dict into readable format
for key, value in new_dict.items(): new_dict[key] = value[0] if len(value) == 1 else tuple(value)


nx.draw(G, pos)
nx.draw(G, pos, edgelist = path, edge_color = 'r', width = 6, labels = new_dict)
plt.title('Using Depth-First Search')
plt.show()

Output

相关问题