NetworkX中的二部图

2024-10-03 22:35:40 发布

您现在位置:Python中文网/ 问答频道 /正文

B.add_nodes_from(a, bipartite=1)
B.add_nodes_from(b, bipartite=0)
nx.draw(B, with_labels = True)  
plt.savefig("graph.png")

我得到了下图。如何使它看起来像一个合适的二分图

My graph


Tags: fromaddtruelabelspngwithpltgraph
3条回答

另一个示例,将图与二部图相结合:

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

您可以这样做,在特定的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()

bipartite-graph

关键是为nx.draw{}参数创建dict,即:

A dictionary with nodes as keys and positions as values.

the docs

NetworkX已经有了一个功能来实现这一点

它被称为networkx.drawing.layout.bipartite_layout

您可以使用它生成字典,该字典通过pos参数提供给绘图函数,如nx.draw,如下所示:

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

强制性示例输出: enter image description here

相关问题 更多 >