2014-07-18 4 views
3

나는 bipartite 그래프의 n1-by-n2 쌍 - 인접 행렬 A를가집니다. 행렬 A는 scipy.sparse csc 행렬입니다. 나는 networkx에서 A를 사용하여 bipartite graph를 plot하고자합니다. 노드가 node_class라는 클래스 레이블에 따라 색상이 지정되었다고 가정합니다. 다음 작업을 수행 할 수 있습니다.파이썬에서 networkx를 사용하여 2 차원 그래프를 플롯

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에 대한 오류 : 매우 큰 1과 0을 많이 가지고 있기 때문에

'Adjacency matrix is not square.' 

또한 내가 가지고있는 행렬 A가 scipy.sparse matrix`이다. 그래서 나는 A를 쌓고 0을 추가함으로써 (n1 + n2) - by- (n1 + n2) 인접 행렬을 만드는 것을 피하고자한다.

두 파트 그래프에 대한 NetworkX 설명서를 확인했으나, 양방향 인접 행렬을 사용하여 두 부분으로 구성된 그래프를 그리는 방법이나 양방향 인접 행렬을 사용하여 그래프를 만드는 방법은 언급하지 않았습니다. 누군가가 이분법 그래프를 그릴 수있는 방법을 말해 줄 수 있다면, 좋을 것입니다!

답변

3

Biadjacency 매트릭스에서 그래프를 만드는 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를 사용하여 아래의 예를 사용하는 경우, 참조 : 여기 example-bipartite-graph

0

간단한 예입니다 : 여기

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

그리고 출력 그래프입니다

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() 
관련 문제