显示投影网络中边缘的权重

时间:2016-10-24 05:56:57

标签: python networkx

我投影了一个二分图并制作了一个新的加权图。我想绘制图形,并显示边缘权重。

这是我的尝试。

import networkx as nx
import matplotlib.pyplot as plt
from networkx.algorithms import bipartite
g=nx.Graph()
g.add_nodes_from(['s1','s2','s3','s4','s5'],bipartite=0)
g.add_nodes_from(['t1','t2','t3','t4'],bipartite=1)
g.add_edges_from([('s1','t1'),('s1','t4'),('s2','t1'),('s2','t2'),('s3','t1'),('s3','t4'),('s4','t3'),('s5','t2'),('s5','t3')])
l=bipartite.weighted_projected_graph(g,['s1','s2','s3','s4','s5'])
nx.draw(l, with_labels=True)
plt.show()

显示节点标签,但不显示边缘权重。如何显示边缘权重?

2 个答案:

答案 0 :(得分:3)

我已修改您的代码以包含nx.draw_networkx_edge_labels

import networkx as nx
import matplotlib.pyplot as plt
from networkx.algorithms import bipartite
g=nx.Graph()
g.add_nodes_from(['s1','s2','s3','s4','s5'],bipartite=0)
g.add_nodes_from(['t1','t2','t3','t4'],bipartite=1)
g.add_edges_from([('s1','t1'),('s1','t4'),('s2','t1'),('s2','t2'),('s3','t1'),('s3','t4'),('s4','t3'),('s5','t2'),('s5','t3')])
l=bipartite.weighted_projected_graph(g,['s1','s2','s3','s4','s5'])
pos = nx.spring_layout(l)
nx.draw(l, pos = pos, with_labels=True)
nx.draw_networkx_edge_labels(l, pos)

这可能会显示超出您想要的内容。我认为这是为边缘可能有某些任意属性的情况而设置的。我认为你想要的是做一切事情直到定义pos然后:

edge_weights = {(u,v,):d['weight'] for u,v,d in l.edges(data=True)}
nx.draw(l, pos = pos, with_labels=True)
nx.draw_networkx_edge_labels(l,pos,edge_labels=edge_weights)

答案 1 :(得分:0)

我用这句话来帮助我减肥:

l.edges(data=True)

输入:[('The Dark Knight', 'The Matrix', {'weight': 1}), ('The Dark Knight', 'The Shawshank Redemption', {'weight': 1}), ('The Social Network', 'The Matrix', {'weight': 1})] 输出:https://graph.microsoft.com/v1.0/me/mailfolders/inbox/childfolders