the*_*lim 3 python matplotlib networkx
我正在使用 networkx 绘制一个简单的无向图,但无法根据特定属性为节点着色。我创建了一个字典,在这种情况下,键引用包含该属性的节点列表。它看起来像这样:
{
1 : [1, 2, 3, 4],
3 : [9, 11, 10, 8],
2 : [7, 5, 6]
}
Run Code Online (Sandbox Code Playgroud)
我想渲染图形,以便每组节点的颜色都不同。这些键用于访问特定颜色。我像这样绘制图形:
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)
Run Code Online (Sandbox Code Playgroud)
这几乎有效,但会产生如下图像:

所以看起来前两组渲染正确,但最后一组没有。知道为什么吗?我查看了文档,但我不明白为什么它失败了。
此外,颜色列表通常会这样结束(当我的意思是通常我的意思是生成的颜色有些随机)
[(0.982864745272968, 0.038693538759121182, 0.03869353875912118), (0.12848750206109338, 0.9956534627440381, 0.12848750206109338), (0.050388282183359334, 0.050388282183359334, 0.9916284269963801)]
Run Code Online (Sandbox Code Playgroud)
您似乎发现了一个有趣的广播问题。
len(v) == len(nc)根据文档,此问题的触发器是 when :
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.
Run Code Online (Sandbox Code Playgroud)
因此 whenlen(v) != 3 nc被解释为 RGB 三元组, when len(v) == 3,浮点数nc通过默认颜色映射(即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)
Run Code Online (Sandbox Code Playgroud)
它变成nc了一个 RGBA 元组,不会触发颜色图的使用。

如果你想跟踪下来,主要工作draw_network_nodes是做在这里通过一个呼叫scatter。scatter函数(此处)中有一条注释,将其标记为已知问题,并说明如何打破歧义。如果您对此感到非常强烈,您可以在 github 上创建一个问题,但我认为它不会受到关注,因为这是一个明确的设计决策。
| 归档时间: |
|
| 查看次数: |
1702 次 |
| 最近记录: |