NetworkX双部图颜色混乱顺序

3
我使用NetworkX创建了一个二分图,并希望分别为两个集合着色。我使用了networkX bipartite模块中的color()函数。但是,节点在颜色字典中的顺序与B.nodes中的顺序不同,例如:

B.nodes = ['a', 1, 2, 3, 4, 'c', 'b']

bipartite.color(B) = {'a': 1, 1: 0, 2: 0, 'b': 1, 4: 0, 'c': 1, 3: 0}

这将导致图像被错误地着色如下:

incorrectly colour graph

代码如下:
B = nx.Graph()
B.add_nodes_from([1,2,3,4], bipartite=0) # Add the node attribute "bipartite"
B.add_nodes_from(['a','b','c'], bipartite=1)
B.add_edges_from([(1,'a'), (1,'b'), (2,'b'), (2,'c'), (3,'c'), (4,'a')])
bottom_nodes, top_nodes = bipartite.sets(B)

color = bipartite.color(B)
color_list = []

for c in color.values():
    if c == 0:
        color_list.append('b')
    else:
        color_list.append('r')

# Draw bipartite graph
pos = dict()
color = []
pos.update( (n, (1, i)) for i, n in enumerate(bottom_nodes) ) # put nodes from X at x=1
pos.update( (n, (2, i)) for i, n in enumerate(top_nodes) ) # put nodes from Y at x=2

nx.draw(B, pos=pos, with_labels=True, node_color = color_list)
plt.show()

我是否漏了什么?谢谢。
1个回答

3
您的颜色列表和节点列表(B.nodes)在绘制图形时顺序不同。最初的回答。
color_list
['r', 'b', 'b', 'r', 'b', 'r', 'r']

B.nodes
NodeView((1, 2, 3, 4, 'a', 'b', 'c'))

我使用字典和从B中的nodelist映射二分集,按照B节点顺序创建了一个color_list。"Original Answer"翻译成"最初的回答"。
B = nx.Graph()
B.add_nodes_from([1,2,3,4], bipartite=0) # Add the node attribute "bipartite"
B.add_nodes_from(['a','b','c'], bipartite=1)
B.add_edges_from([(1,'a'), (1,'b'), (2,'b'), (2,'c'), (3,'c'), (4,'a')])
bottom_nodes, top_nodes = bipartite.sets(B)

color = bipartite.color(B)

color_dict = {0:'b',1:'r'}

color_list = [color_dict[i[1]] for i in B.nodes.data('bipartite')]

# Draw bipartite graph
pos = dict()
color = []
pos.update( (n, (1, i)) for i, n in enumerate(bottom_nodes) ) # put nodes from X at x=1
pos.update( (n, (2, i)) for i, n in enumerate(top_nodes) ) # put nodes from Y at x=2

nx.draw(B, pos=pos, with_labels=True, node_color = color_list)
plt.show()

输出结果:

在此输入图片描述

注:Original Answer翻译成“最初的回答”。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接