为 networkx 图创建自己的颜色条

Create own colorbar for networkx plot

我有以下问题无法解决,尽管我现在花了几个小时解决它并且认为它会很容易。基本上我正在做的是绘制网络。每个节点都有一个介于 0 和 1 之间的值。现在我根据每个节点的值为其着色。 0 对应红色节点,1 对应绿色节点。我通过以下代码执行此操作:

for x in range(gn):
    G.add_node(x)
    cn = value[x]
    cn *= 100
    if cn == 100:
        cn = 99
    if cn < 50:
        # green to yellow
        cg = math.floor(255 * (cn / 50))
        cr = 255
    else:
        # yellow to red
        cg = 255
        cr = math.floor(255 * ((50 - cn % 50) / 50))
    cb = 0
    color_map.append('#%02x%02x%02x' % (cr, cg, cb))

然后在后面的代码中:

fig, ax = plt.subplots()
nx.draw(G, pos, width=weights, node_color=color_map, ax=ax)
plt.show()

现在我只想在网络旁边有一个颜色条,这样绘图的观察者就可以概览哪个颜色对应哪个值。我希望你能帮助我。提前致谢 :) (颜色条应该从 0 到 1 开始,即使在事件中也有值大于 0.5 左右的节点。)

编辑:最小工作示例:

import networkx as nx
import matplotlib.pyplot as plt
import numpy
import math

gn = 20
color_map = []
G = nx.Graph()
value = numpy.random.uniform(0, 1, gn)
for x in range(gn):
    G.add_node(x)
    cn = value[x]
    cn *= 100
    if cn == 100:
        cn = 99
    if cn < 50:
        # green to yellow
        cg = math.floor(255 * (cn / 50))
        cr = 255
    else:
        # yellow to red
        cg = 255
        cr = math.floor(255 * ((50 - cn % 50) / 50))
    cb = 0
    color_map.append('#%02x%02x%02x' % (cr, cg, cb))
pos = nx.spring_layout(G)

fig, ax = plt.subplots()

fig.subplots_adjust(bottom=0.2)
nx.draw(G, pos, node_color=color_map, ax=ax)
plt.show()

您可以使用 matplotlib 的自定义颜色图功能使这更容易一些。例如参见 [​​=11=].

以下是如何将其与 networkx 一起使用。

import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy

gn = 20
G = nx.Graph()
value = numpy.random.uniform(0, 1, gn)
G.add_nodes_from(range(gn))

# create colormap
cdict = {'red':   ((0.0, 1.0, 1.0),
                   (0.5, 1.0, 1.0),
                   (1.0, 0.0, 0.0)),

         'green':  ((0.0, 0.0, 0.0),
                   (0.5, 1.0, 1.0),
                   (1.0, 1.0, 1.0)),

         'blue': ((0.0, 0.0, 0.0),
                   (1.0, 0.0, 0.0))
        }
green_yellow_red = LinearSegmentedColormap('GYR', cdict)
pos = nx.spring_layout(G)
nodes = nx.draw_networkx_nodes(G, pos, node_color=value, cmap=green_yellow_red)
# edges = nx.draw_networkx_nodes(G, pos) # no edges in this graph
plt.colorbar(nodes)
plt.axis('off')
plt.show()