我想使用networkx库绘制无向,加权和完整的图形。我的目的是以边缘权重代表节点之间的距离的方式绘制此图。
例如,考虑以下节点和边的集合:
A,B,体重= 5.0
A,C,体重= 50.0
B,C,重量= 0.5
在这种情况下,A-C之间的距离最小,而B-C之间的距离最大。
(在将边缘和节点添加到G之后),我能够使用
nx.draw(G, pos=None)
但是,随着节点数量的增加(大于6),会出现不一致的情况。我的意思是,尽管连接它们的边缘的权重很小,但有些节点却变得更近。
我认为某些节点的位置在某个时间点后不会更新,但是我不确定。
有什么建议吗?
答案 0 :(得分:1)
您可以生成图形的布局,并根据该布局计算距离。然后,您可以将1 /距离指定为边缘权重。紧密的边缘将具有更牢固的连接,距离较远的边缘将具有较弱的连接。
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
G = nx.complete_graph(15)
# generate positions
pos = nx.spring_layout(G)
# calculate distances and store as weights
from scipy.spatial.distance import euclidean
edge_updates = {}
edge_widths = []
for (a,b,_) in G.edges(data=True):
distance = euclidean(pos[a], pos[b])
edge_updates[a,b] = {'distance': distance}
edge_widths.append(1/distance)
nx.set_edge_attributes(G, edge_updates)
nx.draw_networkx_nodes(G, pos=pos)
a = nx.draw_networkx_edges(G, pos=pos, edge_cmap=plt.cm.magma, width=edge_widths)