3

我正在使用 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) 

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

几乎正确的图表

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

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

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

1 回答 1

5

You seem to have discovered an interesting broadcasting problem.

The trigger for this issue is when len(v) == len(nc), as according to the documentation:

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.

so when len(v) != 3 nc is interpreted as RGB triple, when len(v) == 3, the floats in nc are mapped to RGB via the default color map (which is jet).

A possible work-around for this is

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)

which turns nc into a RGBA tuple, which won't trigger the usage of the color map. 在此处输入图像描述

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

于 2013-03-31T01:57:32.900 回答