Python NetworkX —根据值列表自动设置节点颜色 [英] Python NetworkX — set node color automatically based on a list of values
本文介绍了Python NetworkX —根据值列表自动设置节点颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用networkx
import netwokx as nx
s = 5
G = nx.grid_graph(dim=[s,s])
nodes = list(G.nodes)
edges = list(G.edges)
p = []
for i in range(0, s):
for j in range(0, s):
p.append([i,j])
for i in range(0, len(nodes)):
G.node[nodes[i]]['pos'] = p[i]
pos = {}
for i in range(0, len(nodes)):
pos[nodes[i]] = p[i]
nx.draw(G, pos)
现在,我想为0
和4
import random
val = []
for i in range(0, len(G.nodes()):
val.append(randint(0,4))
And I would like to assign the color to each node base on the val
list and plot something like shown here
推荐答案
要设置节点属性,可以使用:
To set a node property, you can use:
nx.set_node_attributes(G, val, 'val')
Networkx绘制调用到 draw_networkx_nodes ,它需要一个cmap和颜色列表,因此您要做的只是:
Networkx draw calls down to draw_networkx_nodes, this takes a cmap and color list, so all you would have to do would be something like:
nx.draw(G, pos, node_color = nx.get_node_attributes(G,'val'), vmin=0, vmax=4, cmap = plt.cm.get_cmap('rainbow'))
这篇关于Python NetworkX —根据值列表自动设置节点颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文