如何使用networkx按边的粗细绘制超过1000个节点的加权网络?如果我有一个包含源节点、目标节点和每条边权重的.csv列表,并且我打算使用以下方法:
for i in range(N)
G.add_edge(source[i],target[i], weight=weight[i])
nx.draw_networkx_edges(G)
但是,我需要给每条边都设置厚度吗?还是只需给相似厚度的一组边设置厚度?
你可以单独指定每条边,或者如果有一些函数来计算分组,则可以将它们定义为组(然后使用多个draw_network_edges
调用)。
这里有一个随机图的示例,它直接使用边权重作为边的粗细度,其次,使用数据作为颜色。
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
n = 15; m = 40
# select some edge destinations
L = np.random.choice(xrange(n), 2*m)
# and suppose that each edge has a weight
weights = 0.5 + 5 * np.random.rand(m)
# create a graph object, add n nodes to it, and the edges
G = nx.DiGraph()
G.add_nodes_from(xrange(n))
for i, (fr, to) in enumerate(zip(L[1::2], L[::2])):
G.add_edge(fr, to, weight=weights[i])
# use one of the edge properties to control line thickness
edgewidth = [ d['weight'] for (u,v,d) in G.edges(data=True)]
# layout
pos = nx.spring_layout(G, iterations=50)
#pos = nx.random_layout(G)
# rendering
plt.figure(1)
plt.subplot(211); plt.axis('off')
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_edges(G, pos, width=edgewidth,)
plt.subplot(212); plt.axis('off')
# rendering
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_edges(G, pos, edge_color=edgewidth)
plt.show()
这将使您得到类似于此的内容:
显然,您可以使用更复杂的函数来组装edgewidth值列表,以适合您的应用程序(例如分箱值或不同属性的乘积)。