gpt4 book ai didi

python - 在 NetworkX 图表中打印权重时出现问题

转载 作者:行者123 更新时间:2023-12-01 04:36:46 28 4
gpt4 key购买 nike

我正在使用 networkX 读取边缘列表。边缘列表包含以下形式的条目:

1; 2; 3

2; 3; 5

3; 1; 4

其中第三列是重量。当我绘制此图时,它将权重 3 显示为:

{'weight': 3}

而不只是 3。最终我希望能够使用权重执行操作(例如计算出的最高权重,仅显示具有权重的边缘:

'x', etc.,

这是最小的工作代码:

import networkx as nx
import pylab as plt

G=nx.Graph()
G=nx.read_edgelist('sample_with_weights.edges', data= (('weight',int),))
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos=pos)
nx.draw_networkx_edge_labels(G, pos=pos)
nx.draw_networkx_edges(G,pos,width=4, edge_color='g', edge_labels = 'weight', arrows=False)
plt.show()

最佳答案

关于现有代码的一些观察:

  1. 那个read_edgelist不能很好地处理该边缘列表文件,因为“特殊”分隔符 ;尚未指定。

  2. 边缘标签应在 draw_networkx_edge_labels 中指定函数调用,而不是draw_networkx_edges ;还有

  3. edge_labels是由文本标签的边缘二元组键控的字典(默认=无)。仅绘制字典中键的标签。(来自 the documentation)

所以,总体思路是使用 edge_labels有选择地打印边缘权重。请参阅下面的内嵌评论:

import networkx as nx
import pylab as plt

G=nx.Graph()
#Please note the use of the delimiter parameter below
G=nx.read_edgelist('test.edges', data= (('weight',int),), delimiter=";")
pos = nx.spring_layout(G)

#Here we go, essentially, build a dictionary where the key is tuple
#denoting an edge between two nodes and the value of it is the label for
#that edge. While constructing the dictionary, do some simple processing
#as well. In this case, just print the labels that have a weight less
#than or equal to 3. Variations to the way new_labels is constructed
#produce different results.
new_labels = dict(map(lambda x:((x[0],x[1]), str(x[2]['weight'] if x[2]['weight']<=3 else "") ), G.edges(data = True)))

nx.draw_networkx(G, pos=pos)

#Please note use of edge_labels below.
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels = new_labels)
nx.draw_networkx_edges(G,pos,width=4, edge_color='g', arrows=False)

plt.show()

给定一个数据文件test.edges看起来像...

1;2;3
2;3;3
3;4;3
2;4;4
4;6;5
1;6;5

...上面的代码片段将产生类似于以下内容的结果:

Conditional printing of edge weights

希望这有帮助。

关于python - 在 NetworkX 图表中打印权重时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31575634/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com