NetworkX二分色混合顺序

NetworkX bipartite color mixes up order

我已经使用 NetworkX 创建了一个二分图,并想分别为两组着色。我使用来自 networkX 二分模块的 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}

这导致图表的颜色不正确,如下所示:

代码如下:

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()

有什么我遗漏的吗?

谢谢。

您绘制图形时,您的 color_list 和节点列表 (B.nodes) 的顺序不同。

color_list
['r', 'b', 'b', 'r', 'b', 'r', 'r']

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

我创建了一个 color_list using B.nodes order using a dictionary and mapping bipartite sets from nodelist in B.

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()

输出: