当使用nx.draw 为图表着色时,关键是保持colors 的顺序与节点顺序相同。
所以使用集合是行不通的,因为它们是无序的并且不允许重复值。
你想要的是,来自nx.draw_networkx documentation:
node_color(颜色或颜色数组(默认='#1f78b4'))- 节点颜色。可以是单一颜色或与节点列表长度相同的颜色序列。颜色可以是字符串,也可以是 0-1 的浮点数的 rgb(或 rgba)元组。如果指定了数值,它们将使用 cmap 和 vmin,vmax 参数映射到颜色。有关详细信息,请参阅 matplotlib.scatter。
所以如果我们考虑一个列表,我们可以像这样获得colors:
colors = [u[1] for u in G.nodes(data="nodetype")]
这是一个例子:
G=nx.Graph()
G.add_node(1, nodetype="red")
G.add_node(2, nodetype="blue")
G.add_node(3, nodetype="green")
G.add_node(4, nodetype="red")
G.add_edge(1, 3)
G.add_edge(2, 4)
G.add_edge(2, 3)
colors = [u[1] for u in G.nodes(data="nodetype")]
nx.draw(G, with_labels =True, node_color = colors)
抽奖:
编辑:
可能导致您遇到问题的一件事:
使用nodetype="not_a_color"添加节点:
G.add_node(4, nodetype="not_a_color")
colors = [u[1] for u in G.nodes(data="nodetype")]
nx.draw(G, with_labels =True, node_color = colors)
这给出了与您得到的相同的错误:
ValueError: 'c' argument must be a color, a sequence of colours, or a sequence of numbers, not ['red', 'blue', 'green', 'not_a_color']
当然,如果您的清单很长,则更难检查。
尝试运行以下命令,检查是否有既不是"red"、"green" 也不是"blue" 的颜色
colors = [u[1] for u in G.nodes(data="nodetype")]
not_colors = [c for c in colors if c not in ("red", "green", "blue")]
if not_colors:
print("TEST FAILED:", not_colors)
如果您的任何节点的node_type 属性中有None,这会将这些节点打印为黑色:
#(change *colors* to):
colors = []
for u in G.nodes(data="nodetype"):
if u[1] in ("red", "green", "blue"):
colors.append(u[1])
elif u[1] == None:
colors.append("black")
else:
#do something?
print("ERROR: Should be red, green, blue or None")