使用Python中的networkx绘制二分图

4

我有一个二部图的n1行n2列的双重邻接矩阵A,矩阵A是一个scipy.sparse csc矩阵。我想使用A在networkx中绘制这个二部图。假设节点按照它们的类别标签node_class着色。我可以执行以下操作:

import networkx as nx
G = nx.from_numpy_matrix(A)
graph_pos = nx.fruchterman_reingold_layout(G)
degree = nx.degree(G)
nx.draw(G, node_color = node_class, with_labels = False, node_size = [v * 35 for v in degree.values()])

上述代码适用于正方形的密集邻接矩阵。但对于非正方形的双向邻接矩阵 A,则无法使用该代码。错误信息如下:

'Adjacency matrix is not square.'

此外,我拥有的矩阵A是一个scipy.sparse矩阵,因为它非常大且有很多零。因此,我希望避免通过堆叠A并添加零来创建一个(n1+n2)-by-(n1+n2)邻接矩阵。
我查看了NetworkX关于二分图的文档,它没有提到如何使用双向邻接矩阵绘制二分图或创建一个使用双向稀疏矩阵的图。如果有人能告诉我如何绘制二分图,那就太好了!
2个回答

4
我不相信有一个NetworkX函数可以从二分邻接矩阵创建图形,所以你需要自己编写代码。(但是,他们有一个bipartite module你应该查看。)
下面是定义一个函数的一种方法,该函数接受稀疏二分邻接矩阵并将其转换为NetworkX图形(请参见注释以获取说明)。
# Input: M scipy.sparse.csc_matrix
# Output: NetworkX Graph
def nx_graph_from_biadjacency_matrix(M):
    # Give names to the nodes in the two node sets
    U = [ "u{}".format(i) for i in range(M.shape[0]) ]
    V = [ "v{}".format(i) for i in range(M.shape[1]) ]

    # Create the graph and add each set of nodes
    G = nx.Graph()
    G.add_nodes_from(U, bipartite=0)
    G.add_nodes_from(V, bipartite=1)

    # Find the non-zero indices in the biadjacency matrix to connect 
    # those nodes
    G.add_edges_from([ (U[i], V[j]) for i, j in zip(*M.nonzero()) ])

    return G

以下是一个示例用例,我使用 nx.complete_bipartite_graph 生成一个完全图:

import networkx as nx, numpy as np
from networkx.algorithms import bipartite
from scipy.sparse import csc_matrix
import matplotlib.pyplot as plt
RB = nx.complete_bipartite_graph(3, 2)
A  = csc_matrix(bipartite.biadjacency_matrix(RB, row_order=bipartite.sets(RB)[0]))
G = nx_graph_from_biadjacency_matrix(A)
nx.draw_circular(G, node_color = "red", with_labels = True)
plt.show()

这是输出的图形: example-bipartite-graph


0

这里是一个简单的示例:

import networkx as nx
import matplotlib.pyplot as plt
from networkx.algorithms import matching
%matplotlib inline

ls=[
[0,0,0,1,1],
[1,0,0,0,0],
[1,0,1,0,0],
[0,1,1,0,0],
[1,0,0,0,0]
]
g = nx.Graph()
a=['a'+str(i) for i in range(len(ls))]
b=['b'+str(j) for j in range(len(ls[0]))]
g.add_nodes_from(a,bipartite=0)
g.add_nodes_from(b,bipartite=1)

for i in range(len(ls)):
    for j in range(len(ls[i])):
        if ls[i][j] != 0:
            g.add_edge(a[i], b[j])
pos_a={}
x=0.100
const=0.100
y=1.0
for i in range(len(a)):
    pos_a[a[i]]=[x,y-i*const]

xb=0.500
pos_b={}
for i in range(len(b)):
    pos_b[b[i]]=[xb,y-i*const]

nx.draw_networkx_nodes(g,pos_a,nodelist=a,node_color='r',node_size=300,alpha=0.8)
nx.draw_networkx_nodes(g,pos_b,nodelist=b,node_color='b',node_size=300,alpha=0.8)

# edges
pos={}
pos.update(pos_a)
pos.update(pos_b)
#nx.draw_networkx_edges(g,pos,edgelist=nx.edges(g),width=1,alpha=0.8,edge_color='g')
nx.draw_networkx_labels(g,pos,font_size=10,font_family='sans-serif')
m=matching.maximal_matching(g)
nx.draw_networkx_edges(g,pos,edgelist=m,width=1,alpha=0.8,edge_color='k')

plt.show()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接