基于权重值的 Networkx 颜色图边缘

Networkx color graph edges based on weight value

我有一个包含一些列的数据框。我创建了一个 Networkx 无向图,我想绘制相应的网络。我还需要根据这些边的权重更改边的颜色,因此我使用了 LinearColorMap。这是代码:

#my other stuff

cmap = LinearSegmentedColormap.from_list('RwG',['red','white','green'])
nx.draw(G, poss, node_size=1500, node_color='lightgrey', edgelist=edges,edge_color=weights,
width=list(map(lambda number: number * 16 / m, x)), edge_cmap=cmap)

但是,我需要标准化我的颜色图,使白色以特定值(例如 -76)为中心。权重在 [-60,-100] 范围内。 我怎样才能做到这一点? 视觉上:

如果您将 matplotlib 颜色图传递给 networkx,networkx 将 normalize your numerical color argument linearly between the minimum and maximum value。 就我个人而言,我认为这是一个有点短视的设计决定,但它就是这样:你的 non-linear 权重到颜色的映射根本不可能。 但是,您可以 pre-compute 颜色并传递这些颜色(类似于预先计算边缘宽度的方式):

#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx

def weight_to_color(w, threshold):
    if w < threshold:
        return 'green'
    elif np.isclose(w , threshold):
        return 'white'
    else: # x > threshold
        return 'red'

weight_matrix = 40 * np.random.rand(10, 10) - 100
g = nx.from_numpy_array(weight_matrix)
weights = [g.edges[edge]['weight'] for edge in g.edges]
nx.draw(g, node_color='lightgray', edgelist=g.edges, edge_color=[weight_to_color(w, -76) for w in weights])
plt.show()