NetworkX 根据权重设置边宽

NetoworkX set edge widths according to weights

我有一个 numpy 数组:

[[12,  1,  5,  2,  2,  2,  1,  3,  1,  2],
   [ 1, 10,  3,  2,  1,  7,  2,  6,  1,  0],
   [ 5,  3, 26,  5,  1,  5,  2, 11,  3,  5],
   [ 2,  2,  5, 11,  1,  2,  1,  7,  2,  4],
   [ 2,  1,  1,  1, 17,  2,  1,  6,  2,  2],
   [ 2,  7,  5,  2,  2, 22, 12,  8,  1,  0],
   [ 1,  2,  2,  1,  1, 12, 21,  7,  0,  1],
   [ 3,  6, 11,  7,  6,  8,  7, 23,  0,  5],
   [ 1,  1,  3,  2,  2,  1,  0,  0,  3,  1],
   [ 2,  0,  5,  4,  2,  0,  1,  5,  1,  4]]

我正在尝试创建一个 2D 网络图,例如 this - 在页面底部(只是 2D)。
我找到了一个名为 networkx 的库,它有一个非常简单的函数来从 numpy 数组创建二维图形:

import networkx as nx
G = nx.from_numpy_matrix(array)
nx.draw(G, with_labels=1)

但它不是交互式的。
我还试图用数组的实际标签替换图表上的标签(它们是字符串,比如 'one'、'two'...'ten')。 最后,目标是让图形具有边缘,其中边缘的宽度是数组中的数字。

通过nx.draw you can customise the visualisation to fit most of the mentioned requirements. Though in some cases you might need to use other options available in Drawing such as nx. draw_networkx_nodes等进一步定制。

在这种情况下,假设您有一个包含要设置的标签名称的数组,您可以使用 nx.draw_networkx_labels 并指定标签与字典的映射,您可以将其定义为:

G = nx.from_numpy_matrix(a)

nodelist = G.nodes()
num_words = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
d_labels = dict(zip(nodelist, num_words))

注意,使用nx.from_numpy_matrix数组中的实际值设置为边weights,所以可以使用nx.get_edge_attributes获取对应的边宽。

widths = nx.get_edge_attributes(G, 'weight')

稍后可以在 nx.draw_networkx_edges through the width parameter. Finally, in regards to making the graph interactive, you may look into node_picking 中设置宽度。

将它们放在一起,我们可以将图形绘制为:

plt.figure(figsize=(18,13))

pos = nx.spring_layout(G, scale=0.2)
nx.draw_networkx_nodes(G,pos,
                       nodelist=nodelist,
                       with_labels=True,
                       node_size=1500,
                       node_color='black',
                       font_color='white',
                       alpha=0.7)
nx.draw_networkx_edges(G,pos,
                       edgelist = widths.keys(),
                       width=list(widths.values()),
                       edge_color='orange',
                       alpha=0.6)
nx.draw_networkx_labels(G, pos=pos,
                        labels=d_labels,
                        font_color='white')
plt.box(False)
plt.show()