在networkx中按重量着色边

2024-04-25 20:44:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这里只找到了与我想要的相似的东西:

Coloring networkx edges based on weight

不过,我似乎不能把这个应用到我的问题上。我有一个带加权边的图,但是权重不是唯一的(所以有15个权重为1的边)。我想根据它们的重量给边缘上色,重量越轻,颜色越浅。

我试图应用上述问题中建议的方法,但根据我的理解,这要求每个边上的权重是唯一的?

到目前为止,我已经按照不同边缘权重的升序生成了一个列表,并希望使用它来分类可能的边缘颜色。我尽量避免按权重绘制边,因为将来可能需要绘制一个非常大的图,边上的权重范围很大。

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

谢谢!

编辑: 定义绘制图(目标): nlist=[target]+G.neighbors(目标) H=nx.子图(G,nlist) n=H.边数() 颜色=范围(n) labels,weights=颜色和边缘(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]

然后我想用这个列表给每个权重分配一种颜色,权重越高颜色越暗。(在这个例子中,我使用了一个非常小的子图来表示数据集)。希望能澄清一点


Tags: inpos列表labels颜色pltvaltemp
1条回答
网友
1楼 · 发布于 2024-04-25 20:44:26

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

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

enter image description here

相关问题 更多 >