我在这里只找到了与我想要的类似的东西:
Coloring networkx edges based on weight
但是我似乎无法将其应用于我的问题。我有一个带加权边的图,但权重不是唯一的(所以有 15 个边,权重为 1)。我想根据边缘的重量为边缘着色,重量越小,颜色越浅。
我尝试应用上述问题中建议的方法,但据我了解,这要求每条边上的权重都是唯一的?
到目前为止,我已经生成了一个按不同边权重升序排列的列表,并想用它来对可能的边颜色进行分类。我试图避免按权重绘制边,因为将来我可能需要绘制一个非常大的图,边上的权重范围很大。
如果不清楚,请在评论中告诉我,我会提供更具体的信息。
谢谢!
编辑: def draw_graph(目标): nlist = [目标]+G.neighbors(目标) H=nx.subgraph(G, nlist) n=H.number_of_edges() 颜色 = 范围(n) 标签,权重 = colour_and_label_edges(H)
pos = nx.spring_layout(H)
nx.draw(H, pos, node_color='#A0CBE2',edge_color=colours, node_size=100, edge_cmap=plt.cm.Blues, width=0.5, with_labels=False)
nx.draw_networkx_edge_labels(H, pos, edge_labels=labels)
plt.savefig("Graphs/edge_colormap_%s.png" % target) # save as png
plt.show() # display
pass
def colour_and_label_edges(graph):
d={}
for (u,v) in graph.edges():
d[u,v]=graph[u][v]['weight']
temp=[]
for val in d.values():
if val not in temp:
temp.append(val)
weights = sorted(temp,key=int)
return d, weights
上面的代码是不完整的,但是这个函数给我一个权重列表,如下所示:
[1, 2, 3, 4, 5, 6, 9, 10, 16, 21, 47, 89, 124, 134, 224]
然后我想使用此列表为每个权重分配一种颜色,权重越高,颜色越深。 (相对于数据集,我在此示例中使用了一个非常小的子图)。希望能稍微澄清一下 :S
最佳答案
您可以使用边权重和颜色图来绘制它们。您可能需要与下面不同的颜色图。
import matplotlib.pyplot as plt
import networkx as nx
import random
G = nx.gnp_random_graph(10,0.3)
for u,v,d in G.edges(data=True):
d['weight'] = random.random()
edges,weights = zip(*nx.get_edge_attributes(G,'weight').items())
pos = nx.spring_layout(G)
nx.draw(G, pos, node_color='b', edgelist=edges, edge_color=weights, width=10.0, edge_cmap=plt.cm.Blues)
plt.savefig('edges.png')
关于python - 在 networkx 中按权重着色边缘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22967086/