我有一个图,其中我的节点在两个方向上可以在它们之间有多个边,我想根据它们之间所有边的总和来设置节点之间的宽度。
import networkx as nx
nodes = [0,1]
edges = [(0,1),(1,0)]
G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
weights = [2,3]
nx.draw(G, width = weights)
我希望将0到1之间的宽度设置为5,因为这是总重量。
答案 0 :(得分:1)
首先,您需要创建一个MultiDiGraph
并添加所有可能的边。这是因为它支持包括自循环在内的同一组节点之间的多个有向egdes。
import networkx as nx
nodes = [0, 1, 2, 3, 4, 5]
edges = [(0,1), (1,0), (1, 0),(0, 1), (2, 3), (2, 3), (2, 3), (2, 3),
(4, 1), (4, 1), (4, 1), (4, 1), (4, 1), (4, 1), (4, 5), (5, 0)]
G = nx.MultiDiGraph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
接下来,创建一个包含每个边缘计数的字典
from collections import Counter
width_dict = Counter(G.edges())
edge_width = [ (u, v, {'width': value})
for ((u, v), value) in width_dict.items()]
现在从上面创建的DiGraph
字典中创建一个新的edge_width
G_new = nx.DiGraph()
G_new.add_edges_from(edge_width)
使用加厚边缘进行绘制
这是对here提到的答案的扩展。
edges = G_new.edges()
weights = [G_new[u][v]['width'] for u,v in edges]
nx.draw(G_new, edges=edges, width=weights)
添加边缘标签
有关更多信息,请参见this answer。
pos = nx.spring_layout(G_new)
nx.draw(G_new, pos)
edge_labels=dict([((u,v,),d['width'])
for u,v,d in G_new.edges(data=True)])
nx.draw_networkx_edges(G_new, pos=pos)
nx.draw_networkx_edge_labels(G_new, pos, edge_labels=edge_labels,
label_pos=0.25, font_size=10)
您还可以使用工作代码查看this Google Colab Notebook。
参考