根据属性设置节点颜色

时间:2020-06-03 23:20:25

标签: python python-3.x graph networkx graph-theory

我用默认的蓝色节点构建了一个直接图,如下图所示。

每个节点都是从“节点”类创建的对象,每个节点都具有“状态”属性,该属性可以具有以下值之一:{-1, 0, 1}

我想在下图中根据其各自的状态值显示不同的节点颜色,例如-1:红色,0:黑色和1:蓝色。

我应该怎么做?

Linked nodes

1 个答案:

答案 0 :(得分:0)

我们以下面的随机图为例:

G = nx.barabasi_albert_graph(20, 1)

plt.figure(figsize=(12, 8))
pos = nx.spring_layout(G, scale=20, k=3/np.sqrt(G.order()))
nx.draw(G, pos=pos, with_labels=True, k=13.8, node_color='lightgreen', node_size=800)

enter image description here

假设我们将以下字典映射状态映射为color,并将一组状态设置为节点属性:

color_state_map = {-1: 'red', 0: 'black', 1: 'blue'}

states = np.random.choice([-1,0,1], size=20)
nx.set_node_attributes(G, dict(zip(G.nodes(), states)), 'state')

为了根据状态设置节点颜色,可以使用node_color中的nx.draw参数为图形的G.nodes()设置相应的节点颜色。

plt.figure(figsize=(12, 8))
nx.draw(G, pos=pos, 
        with_labels=True, 
        k=13.8, 
        node_color=[color_state_map[node[1]['state']] 
                    for node in G.nodes(data=True)], 
        node_size=800,
       font_color='white')
plt.show()

enter image description here

相关问题