gpt4 book ai didi

python - networkx 节点着色中的异常行为

转载 作者:太空宇宙 更新时间:2023-11-03 15:20:34 25 4
gpt4 key购买 nike

我正在绘图以使用 networkx 绘制一个简单的无向图,但我无法根据特定属性为节点着色。我创建了一个字典,在这种情况下,键引用包含该属性的节点列表。看起来像这样:

{ 
1 : [1, 2, 3, 4],
3 : [9, 11, 10, 8],
2 : [7, 5, 6]
}

我想渲染图形,使每组节点的颜色不同。这些键用于访问特定颜色。我这样画图:

colors = [(random.random(), random.random(), random.random()) for i in xrange(0, 3)]
pos = nx.circular_layout(G)
for k,v in node_list_dict.iteritems():
nc = colors[int(k)-1]
nx.draw_networkx_nodes(G, pos, nodelist=v, node_color=nc)
nx.draw_networkx_edges(G, pos)
nx.draw_networkx_labels(G, pos)

这几乎可以工作,但会产生如下图像:

Almost correct graph

因此看起来前两组渲染正确,但最后一组渲染不正确。知道为什么吗?我查看了文档,但不明白为什么会失败。

此外,颜色列表通常以这样的方式结束(当我的意思是通常我的意思是生成的颜色有些随机)

[(0.982864745272968, 0.038693538759121182, 0.03869353875912118), (0.12848750206109338,    0.9956534627440381, 0.12848750206109338), (0.050388282183359334, 0.050388282183359334, 0.9916284269963801)]

最佳答案

你似乎发现了一个有趣的广播问题。

根据文档,此问题的触发点是 len(v) == len(nc):

node_color : color string, or array of floats
Node color. Can be a single color format string (default='r'),
or a sequence of colors with the same length as nodelist.
If numeric values are specified they will be mapped to
colors using the cmap and vmin,vmax parameters. See
matplotlib.scatter for more details.

所以当 len(v) != 3 nc 被解释为 RGB 三元组时,当 len(v) == 3 时, nc 中的 float 通过默认颜色映射(即 jet)映射到 RGB。

一个可能的解决方法是

for k,v in node_list_dict.iteritems():
nc = colors[int(k)-1]
if len(v) == 3:
nc = nc + (1,)
nx.draw_networkx_nodes(G, pos, nodelist=v, node_color=nc)

nc 转换为 RGBA 元组,不会触发颜色映射的使用。 enter image description here

如果你想追踪这个,draw_network_nodes的主要工作已经完成here通过调用 scatterscatter 函数 (here) 中有一条注释,将此标记为已知问题并说明如何消除歧义。如果您真的对此有强烈的感觉,您可以在 github 上创建一个问题,但我认为它不会受到关注,因为这是一个明确的设计决策。

关于python - networkx 节点着色中的异常行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15723324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com