B.add_nodes_from(a, bipartite=1)
B.add_nodes_from(b, bipartite=0)
nx.draw(B, with_labels = True)
plt.savefig("graph.png")
我得到如下图所示。我怎样才能使它看起来像一个适当的二分图?
你可以做这样的事情,在特定x
坐标绘制从每个分区节点:
X, Y = bipartite.sets(B)
pos = dict()
pos.update( (n, (1, i)) for i, n in enumerate(X) ) # put nodes from X at x=1
pos.update( (n, (2, i)) for i, n in enumerate(Y) ) # put nodes from Y at x=2
nx.draw(B, pos=pos)
plt.show()
关键是创造了该dict
nx.draw
参数,这是pos
:
字典与作为键和位置作为值的节点。
见the docs。
NetworkX已经有一个函数来做到的正是这种。
其所谓的networkx.drawing.layout.bipartite_layout
您可以使用它来生成通过像这样的nx.draw
参数输送到像pos
绘图功能的词典:
nx.draw_networkx(
B,
pos = nx.drawing.layout.bipartite_layout(B, B_first_partition_nodes),
width = edge_widths*5) # Or whatever other display options you like
凡B
是完整的二分图(表示为普通networkx图),并B_first_partition_nodes
是要在第一个分区放置节点。
这将生成一个传递给绘图功能的pos
参数数值的位置的字典。您可以指定布局选项为好,看到main page。
另一实例中,结合了二分图图表:
G = nx.read_edgelist('file.txt', delimiter="\t")
aux = G.edges(data=True)
B = nx.Graph()
B.add_nodes_from(list(employees), bipartite=0)
B.add_nodes_from(list(movies), bipartite=1)
B.add_edges_from(aux)
%matplotlib notebook
import [matplotlib][1].pyplot as plt
plt.figure()
edges = B.edges()
print(edges)
X, Y = bipartite.sets(B)
pos = dict()
pos.update( (n, (1, i)) for i, n in enumerate(X) ) # put nodes from X at x=1
pos.update( (n, (2, i)) for i, n in enumerate(Y) ) # put nodes from Y at x=2
nx.draw_networkx(B, pos=pos, edges=edges)
plt.show()