networkx节点着色中的异常行为

时间:2013-03-30 20:47:48

标签: python matplotlib networkx

我正在绘制一个带有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)]

1 个答案:

答案 0 :(得分:4)

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

此问题的触发器是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中的浮点数会通过默认颜色映射(jet映射到RGB 1}})。

可能的解决办法是

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的主要工作是通过致电scatter完成herescatter函数(here)中有一条注释将此标记为已知问题,并说明模糊性是如何被破坏的。如果您对此非常非常,那么您可以在github上创建一个问题,但我认为它不会引起关注,因为这是一个明确的设计决策。