Code:[ZachxPKU/NetworkSciencewithPythonandNetworkXQuickStartGuide]
《Network Science with Python and NetworkX Quick Start Guide》
Chapter 4 Affiliation Networks
Nodes and affliations
Affiliation networks in NetworkX
import networkx as nx
from networkx.algorithms import bipartite
from networkx import NetworkXError
G = nx.karate_club_graph()
try:
left, right = bipartite.sets(G)
print("Left nodes\n", left)
print("\nRight nodes\n", right)
except NetworkXError as e:
print(e)
```
```python
B = nx.Graph()
B.add_edges_from([(v, (v, w)) for v, w in G.edges])
B.add_edges_from([(w, (v, w)) for v, w in G.edges])
try:
left, right = bipartite.sets(B)
print("Left nodes\n", left)
print("\nRight nodes\n", right)
except NetworkXError as e:
print(e)
```
```python
bipartite.is_bipartite(B)
import networkx as nx
from pathlib import Path
data_dir = Path('..') / 'data'
B = nx.Graph()
with open(data_dir / 'bartomeus2008' / 'Bartomeus_Ntw_nceas.txt') as f:
next(f)
for row in f:
cells = row.strip().split('\t')
plant = cells[4].replace('_', '\n')
pollinator = cells[8].replace('_', '\n')
B.add_edge(pollinator, plant)
B.nodes[pollinator]["bipartite"] = 0
B.nodes[plant]['bipartite'] = 1
B = B.subgraph(list(nx.connected_components(B))[0])
pollinators = [v for v in B.nodes if B.nodes[v]['bipartite'] == 0]
plants = [v for v in B.nodes if B.nodes[v]['bipartite'] == 1]
import matplotlib.pyplot as plt
plt.figure(figsize=(30,30))
pos = nx.spring_layout(B, k=0.9)
nx.draw_networkx_edges(B, pos, width=3, alpha=0.2)
nx.draw_networkx_nodes(B, pos, nodelist=plants, node_color="#bfbf7f", node_shape="h", node_size=3000)
nx.draw_networkx_nodes(B, pos, nodelist=pollinators, node_color="#9f9fff", node_size=3000)
nx.draw_networkx_labels(B, pos)
Projections
G = bipartite.projected_graph(B, plants)
plt.figure(figsize=(24, 24))
pos = nx.spring_layout(G, k=0.5)
nx.draw_networkx_edges(G, pos, width=3, alpha=0.2)
nx.draw_networkx_nodes(G, pos, node_color="#bfbf7f", node_shape="h", node_size=10000)
nx.draw_networkx_labels(G, pos)
G = bipartite.projected_graph(B, pollinators)
plt.figure(figsize=(30, 30))
pos = nx.spring_layout(G, k=0.5)
nx.draw_networkx_edges(G, pos, width=3, alpha=0.2)
nx.draw_networkx_nodes(G, pos, node_color="#9f9fff", node_size=6000)
nx.draw_networkx_labels(G, pos)
G = bipartite.weighted_projected_graph(B, plants)
list(G.edges(data=True))[0]
G = bipartite.overlap_weighted_projected_graph(B, pollinators)
weight = [G.edges[e]['weight'] for e in G.edges]
plt.figure(figsize=(30,30))
pos = nx.spring_layout(G, weight='weight', k=0.5)
nx.draw_networkx_edges(G, pos, edge_color=weight, edge_cmap=plt.cm.Blues,
width=6, alpha=0.5)
nx.draw_networkx_nodes(G, pos, node_color="#9f9fff", node_size=6000)
nx.draw_networkx_labels(G,pos)