| name | networkx-social |
| description | Social network and graph analysis via NetworkX. Use when: graph analysis, community detection, centrality measures, network visualization, knowledge graphs, bipartite networks, graph I/O. NOT for: large-scale graph processing (>1M nodes), GPU graph analytics (use cuGraph). |
| metadata | {"openclaw":{"emoji":"🕸️","requires":{"bins":["python3"]},"install":[{"id":"uv-networkx","kind":"uv","package":"networkx matplotlib"}]}} |
NetworkX Graph Analysis
Graph analysis, community detection, centrality measures, knowledge graphs, bipartite networks, and visualization.
Graph Creation
import networkx as nx
G = nx.Graph()
G.add_edge('Alice', 'Bob', weight=3)
G.add_edges_from([('Bob', 'Carol'), ('Carol', 'Dave'), ('Alice', 'Dave')])
D = nx.DiGraph()
G = nx.read_edgelist('network.txt')
G = nx.from_pandas_edgelist(df, 'source', 'target')
Knowledge Graph Construction
KG = nx.DiGraph()
triples = [
("Python", "is_a", "Language"), ("Pandas", "depends_on", "Python"),
("NumPy", "depends_on", "Python"), ("Pandas", "depends_on", "NumPy"),
]
for subj, pred, obj in triples:
KG.add_edge(subj, obj, relation=pred)
deps = list(nx.descendants(KG, "Pandas"))
ego = nx.ego_graph(KG, "Python", radius=2, undirected=True)
Centrality Measures
dc = nx.degree_centrality(G)
bc = nx.betweenness_centrality(G)
cc = nx.closeness_centrality(G)
ec = nx.eigenvector_centrality(G, max_iter=1000)
pr = nx.pagerank(D, alpha=0.85)
for node, score in sorted(bc.items(), key=lambda x: -x[1])[:5]:
print(f"{node}: {score:.4f}")
Community Detection
from networkx.algorithms.community import louvain_communities, modularity
from networkx.algorithms.community import label_propagation_communities, greedy_modularity_communities
communities = louvain_communities(G, seed=42)
communities = list(label_propagation_communities(G))
greedy = list(greedy_modularity_communities(G))
mod = modularity(G, communities)
print(f"Modularity: {mod:.4f}")
Shortest Paths and Distances
path = nx.shortest_path(G, source='Alice', target='Dave')
length = nx.shortest_path_length(G, source='Alice', target='Dave')
if nx.is_connected(G):
diameter = nx.diameter(G)
avg_path = nx.average_shortest_path_length(G)
Clustering and Connectivity
avg_cc = nx.average_clustering(G)
transitivity = nx.transitivity(G)
components = list(nx.connected_components(G))
largest_cc = G.subgraph(max(components, key=len)).copy()
core_numbers = nx.core_number(G)
Bipartite Graphs and Projections
from networkx.algorithms import bipartite
B = nx.Graph()
B.add_nodes_from(["u1", "u2", "u3"], bipartite=0)
B.add_nodes_from(["p1", "p2"], bipartite=1)
B.add_edges_from([("u1", "p1"), ("u2", "p1"), ("u2", "p2"), ("u3", "p2")])
users = {n for n, d in B.nodes(data=True) if d["bipartite"] == 0}
user_graph = bipartite.projected_graph(B, users)
weighted_proj = bipartite.weighted_projected_graph(B, users)
Network Visualization
import matplotlib.pyplot as plt
pos = nx.spring_layout(G, seed=42, k=1.5)
node_sizes = [3000 * dc[n] for n in G.nodes()]
color_map = {n: i for i, comm in enumerate(communities) for n in comm}
nx.draw_networkx(G, pos, node_size=node_sizes,
node_color=[color_map.get(n, 0) for n in G.nodes()],
cmap=plt.cm.Set3, edge_color='gray', alpha=0.8, font_size=9)
plt.tight_layout()
plt.savefig('network.png', dpi=150)
plt.close()
Graph I/O
nx.write_graphml(G, 'graph.graphml')
G = nx.read_graphml('graph.graphml')
nx.write_gexf(G, 'graph.gexf')
G = nx.read_gexf('graph.gexf')
from networkx.readwrite import json_graph
import json
data = json_graph.node_link_data(G)
json.dump(data, open('graph.json', 'w'))
G = json_graph.node_link_graph(json.load(open('graph.json')))
Best Practices
- Use
G.copy() before destructive operations (node/edge removal).
- For large graphs, prefer
louvain_communities over girvan_newman.
- Set
seed in layout functions for reproducible visualizations.
- Check
nx.is_connected(G) before computing diameter or avg path length.
- For weighted networks, pass
weight='weight' to centrality functions.
- For knowledge graphs, use
DiGraph and store relation types as edge attributes.
- Export to GraphML or GEXF for interoperability with Gephi and other tools.