首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NetworkX二分色混合顺序

NetworkX二分色混合顺序
EN

Stack Overflow用户
提问于 2019-02-14 23:00:19
回答 1查看 600关注 0票数 2

我已经使用NetworkX创建了一个二分图,并希望分别为这两个集着色。我使用了networkX bipartite模块中的color()函数。但是,颜色dict中的节点顺序与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}

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

代码如下:

代码语言:javascript
复制
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()

我是不是漏掉了什么?

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-14 23:30:03

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

代码语言:javascript
复制
color_list
['r', 'b', 'b', 'r', 'b', 'r', 'r']

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

我使用字典和从B中的节点列表映射二分集创建了一个使用B.nodes order的color_list。

代码语言:javascript
复制
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()

输出:

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54693336

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档