根据权重为networkx中的边着色

18 投票
1 回答
21745 浏览
提问于 2025-04-18 02:03

我在这里找到了一些类似我想要的内容:

根据权重给networkx的边上色

不过我似乎无法将这个方法应用到我的问题上。我有一个带权重的图,但这些权重并不唯一(比如有15条边的权重都是1)。我想根据边的权重给它们上色,权重越低颜色越浅。

我尝试使用上面问题中建议的方法,但我理解这需要每条边的权重都是唯一的,对吗?

到目前为止,我已经生成了一个不同边权重的升序列表,想用这个来分类可能的边颜色。我想避免根据权重来绘制边,因为将来我可能需要绘制一个非常大的图,边的权重范围也会很大。

如果不清楚,请在评论中告诉我,我会提供更具体的信息。

谢谢!

编辑: def draw_graph(target): nlist = [target]+G.neighbors(target) H=nx.subgraph(G, nlist) n=H.number_of_edges() colours = range(n) labels,weights = 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

1 个回答

36

你可以使用边的权重和颜色图来绘制它们。你可能想要使用不同于下面这个的颜色图。

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')

在这里输入图片描述

撰写回答