import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
B=nx.Graph()
B.add_nodes_from(range(1,6,1),color='k')
B.add_nodes_from(['A','B','C','D'],color='w')
B.add_edges_from([(1,'A'),(2,'B'),(2,'D'),(3,'A'),(3,'B'),(3,'D'),(4,'C'),(4,'D'),(5,'D')])
pos = dict((chr(i+65),(0.5+i,0)) for i in range(4))
for i in range(5): pos[i+1] = (i,1)
#draw the bipartite network
plt.figure(figsize=(6,3))
#plt.title('a bipartite network\n')
nx.draw_networkx_labels(B, pos, font_color='k',labels=dict((chr(i),chr(i)) for i in range(65,69)))#反过来的。。。
nx.draw_networkx_labels(B, pos, font_color='w',labels=dict((i,i) for i in range(1,6,1)))#反过来的。。。
nx.draw(B,pos,edgecolors='k',node_color=[c for n,c in B.nodes.data('color')])
plt.show()
plt.close()
#show the bipartite sets
B1,B2 = nx.algorithms.bipartite.sets(B)
print('The first group is {}.'.format(B1))
print('The second group is {}.'.format(B2))
#adjacency matrix for B-B1 & B-B2
array=nx.algorithms.bipartite.biadjacency_matrix(B, B1).toarray()
print(array)
array1=nx.algorithms.bipartite.biadjacency_matrix(B, B2).toarray()
print(array1)
#Then draw the one-mode projections of the bipartite network.
BonB1 = nx.algorithms.bipartite.projected_graph(B, B1)
BonB2 = nx.algorithms.bipartite.projected_graph(B, B2)
plt.figure(figsize=(8,3))
plt.subplot(121)
plt.title('projection on the black nodes\n',fontsize=13)
nx.draw_kamada_kawai(BonB1, with_labels=True, font_color='w', edgecolors='k',
node_color=[c for n,c in BonB1.nodes.data('color')])
plt.subplot(122)
plt.title('projection on the white nodes\n',fontsize=13)
BonB2=nx.relabel_nodes(BonB2,dict((n,ord(n)-64 ) for n in BonB2))# 用数字替代字母label
nx.draw_kamada_kawai(BonB2, with_labels=True, font_color='k', edgecolors='k',
node_color=[c for n,c in BonB2.nodes.data('color')])
plt.show()