在grid_2d_graph networkx中更改节点标签时更改pos

时间:2016-05-08 21:26:38

标签: python graph grid networkx

我正在使用nx.convert_node_labels_to_integers更改grid_2d_graph中节点的标签,我希望节点在更改标签之前保持在相同的位置。显然,我必须转换pos,方法与之前转换节点标签的方式相同,并将新pos作为参数提供给nx.draw()。但是,我无法理解如何轻松地做到这一点。你能救我吗?

这是我的代码

import networkx as nx
import matplotlib.pyplot as plt

start = 0
end = 7

G = nx.grid_2d_graph(3,3)
pos = dict(zip(G,G)) # dictionary of node names->positions
G = nx.convert_node_labels_to_integers(G, ordering = 'sorted')

node_colors = ["lightblue" if n == start or n == end else "white" for n in G.nodes()]
edge_colors = ["blue" if n == (1, 2) else "gray" for n in G.edges()]
nx.draw(G, with_labels=True,  edge_color = edge_colors, node_color = node_colors, width = 3)

1 个答案:

答案 0 :(得分:0)

您可以将这些位置存储为节点属性,它们将通过重新标记保留。使用networkx.set_node_attributes()networkx.get_node_attributes()如下

import networkx as nx
import matplotlib.pyplot as plt

start = 0
end = 7

G = nx.grid_2d_graph(3,3)
pos = dict(zip(G,G)) # dictionary of node names->positions
nx.set_node_attributes(G,'pos',pos)
G = nx.convert_node_labels_to_integers(G, ordering = 'sorted',
                                       label_attribute = 'origin' )

node_colors = ["lightblue" if n == start or n == end else "white" for n in G.nodes()]
edge_colors = ["blue" if n == (1, 2) else "gray" for n in G.edges()]
pos = nx.get_node_attributes(G,'pos')
nx.draw(G, pos=pos, with_labels=True,  edge_color = edge_colors, node_color = node_colors, width = 3)

我还将label_attribute关键字设置为' origin'它将原始节点名称记录为属性' origin'。所以你可以查看结果

>>> list(G.nodes(data=True))
[(0, {'origin': (0, 0), 'pos': (0, 0)}),
 (1, {'origin': (0, 1), 'pos': (0, 1)}),
 (2, {'origin': (0, 2), 'pos': (0, 2)}),
 (3, {'origin': (1, 0), 'pos': (1, 0)}),
 (4, {'origin': (1, 1), 'pos': (1, 1)}),
 (5, {'origin': (1, 2), 'pos': (1, 2)}),
 (6, {'origin': (2, 0), 'pos': (2, 0)}),
 (7, {'origin': (2, 1), 'pos': (2, 1)}),
 (8, {'origin': (2, 2), 'pos': (2, 2)})]