如何使用python networkX包显示二分图?

时间:2016-02-18 03:41:43

标签: python networkx bipartite

如何在python networkX包中显示二分图,左边一列中的节点和右边另一个类中的节点?

我可以创建图表并像这样显示

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')])
nx.draw(B)
plt.show()

但我希望列中左侧的节点1,2,3,4和节点' a'''' c'在右边的一列中,边缘在它们之间。

3 个答案:

答案 0 :(得分:2)

您需要自己设置每个节点的位置:

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')])

# Separate by group
l, r = nx.bipartite.sets(B)
pos = {}

# Update position for node from each group
pos.update((node, (1, index)) for index, node in enumerate(l))
pos.update((node, (2, index)) for index, node in enumerate(r))

nx.draw(B, pos=pos)
plt.show()

enter image description here

答案 1 :(得分:1)

以下是在@Rikka的答案和NetworkX的较新版本的基础上,以下内容可自动(并改善)双向网络的定位。我还为网络的不同分区添加了标签和不同的颜色。

TableA

Bipartite network

答案 2 :(得分:0)

回答我自己的问题,基于上面的@Rikka - 这里是代码,用于确定任意多部分图中节点的位置,给出部件的名称。

def position_MultiPartiteGraph( Graph, Parts ):
  # Graph is a networkX Graph object, where the nodes have attribute 'agentType' with part name as a value
  # Parts is a list of names for the parts (to be shown as columns)
  # returns list of dictionaries with keys being networkX Nodes, values being x,y coordinates for plottingxPos = {}
  xPos = {}
  yPos = {}
  for index1, agentType in enumerate(Parts):
     xPos[agentType] = index1
     yPos[agentType] = 0

  pos = {}
  for node, attrDict in Graph.nodes(data=True):
     agentType = attrDict['agentType']
     # print ('node: %s\tagentType: %s' % (node, agentType))
     # print ('\t(x,y): (%d,%d)' % (xPos[agentType], yPos[agentType]))
     pos[node] = (xPos[agentType], yPos[agentType])
     yPos[agentType] += 1

  return pos

现在,假设我定义了一个这样的三方图(权重与此示例无关):

TG = nx.Graph()
TG.add_nodes_from([1,2,3,4], agentType='world') # Add the node attribute   "bipartite"
TG.add_nodes_from(['a','b','c'], agentType='sender')
TG.add_nodes_from(['A','B','C'], agentType='receiver')

# This is just an easier way to add (and to automatically generate) weighted edges
myEdges = [(1,'a',0.75),
       (1,'b',0.25),
       (2,'b',0.5),
       (2,'c',0.5),
       (3,'c',1.0),
       (4,'a',1.0),
       ('a','C',0.10),
       ('a','A',0.80),
       ('c','A',1.0),
       ('b','C',1.0)]

[TG.add_edge(x,y,weight=z) for x,y, z in myEdges]

然后是如何使用它:

nx.draw(TG,pos=position_MultiPartiteGraph(TG, ['world', 'sender', 'receiver']))
plt.show()

我不确定如何显示输出,但它对我有用!欢呼!谢谢@Rikka!