Create, analyze, and visualize complex networks and graphs in Python with NetworkX. Use when working with network/graph data structures, computing graph algorithms (shortest paths, centrality, clustering), detecting communities, generating synthetic networks (random, scale-free,
Installs just this skill. Get the whole plugin for auto-invocation.
⚡ How it fires
How this skill gets triggered: by you, by Claude, or both.
Fires itselfClaude auto-loads it when your prompt matches the work.
You can call itInvoke it directly when you want it.
Slash command/networkx
👁️ Context preview
The summary Claude sees to decide when to auto-load this skill.
Create, analyze, and visualize complex networks and graphs in Python with NetworkX. Use when working with network/graph data structures, computing graph algorithms (shortest paths, centrality, clustering), detecting communities, generating synthetic networks (random, scale-free,
📊 Stats
Stars31,542
Forks3,146
LanguagePython
LicenseMIT
📦 Ships with scientific-agent-skills
</> SKILL.md
networkx.SKILL.md
---name: networkx
description: Create, analyze, and visualize complex networks and graphs in Python with NetworkX. Use when working with network/graph data structures, computing graph algorithms (shortest paths, centrality, clustering), detecting communities, generating synthetic networks (random, scale-free, small-world), reading/writing graph file formats, or drawing network topologies. Common applications include social, biological, transportation, and citation networks.
license: 3-clause BSD license
metadata: {"version": "1.1", "skill-author": "K-Dense Inc."}
---# NetworkX
## Overview
NetworkX is a Python package for creating, manipulating, and analyzing complex networks and graphs. Use this skill when working with network or graph data structures, including social networks, biological networks, transportation systems, citation networks, knowledge graphs, or any system involving relationships between entities.
This skill targets NetworkX 3.x (current stable: 3.6, which requires Python >= 3.11). Several pre-3.0 APIs (`nx.info`, `nx.write_gpickle`, `nx.read_shp`) and the 3.4-era `nx.random_tree` no longer exist — current replacements are used throughout this skill.
## When to Use This Skill
Invoke this skill when tasks involve:
- **Creating graphs**: Building network structures from data, adding nodes and edges with attributes
- **Graph analysis**: Computing centrality measures, finding shortest paths, detecting communities, measuring clustering
- **Graph algorithms**: Running standard algorithms like Dijkstra's, PageRank, minimum spanning trees, maximum flow
**Reference**: See `references/graph-basics.md` for comprehensive guidance on creating, modifying, examining, and managing graph structures, including working with attributes and subgraphs.
### 2. Graph Algorithms
NetworkX provides extensive algorithms for network analysis:
**Reference**: See `references/algorithms.md` for detailed documentation on all available algorithms including shortest paths, centrality measures, clustering, community detection, flows, matching, tree algorithms, and graph traversal.
### 3. Graph Generators
Create synthetic networks for testing, simulation, or modeling:
**Classic Graphs**:
```python
# Complete graph
G = nx.complete_graph(n=10)
# Cycle graph
G = nx.cycle_graph(n=20)
# Known graphs
G = nx.karate_club_graph()
G = nx.petersen_graph()
```
**Random Networks**:
```python
# Erdős-Rényi random graph
G = nx.erdos_renyi_graph(n=100, p=0.1, seed=42)
# Barabási-Albert scale-free network
G = nx.barabasi_albert_graph(n=100, m=3, seed=42)
# Watts-Strogatz small-world network
G = nx.watts_strogatz_graph(n=100, k=6, p=0.1, seed=42)
```
**Structured Networks**:
```python
# Grid graph
G = nx.grid_2d_graph(m=5, n=7)
# Random tree (random_tree was removed in NetworkX 3.4)
G = nx.random_labeled_tree(100, seed=42)
```
**Reference**: See `references/generators.md` for comprehensive coverage of all graph generators including classic, random, lattice, bipartite, and specialized network models with detailed parameters and use cases.
### 4. Reading and Writing Graphs
NetworkX supports numerous file formats and data sources:
**File Formats**:
```python
# Edge list
G = nx.read_edgelist('graph.edgelist')
nx.write_edgelist(G, 'graph.edgelist')
# GraphML (preserves attributes)
G = nx.read_graphml('graph.graphml')
nx.write_graphml(G, 'graph.graphml')
# GML
G = nx.read_gml('graph.gml')
nx.write_gml(G, 'graph.gml')
# JSON (node-link format; edge list is stored under the "edges" key
# since NetworkX 3.6 — older files may use "links", see references/io.md)
G = nx.from_pandas_edgelist(df, 'source', 'target', edge_attr='weight')
# To DataFrame
df = nx.to_pandas_edgelist(G)
```
**Matrix Formats**:
```python
import numpy as np
# Adjacency matrix
A = nx.to_numpy_array(G)
G = nx.from_numpy_array(A)
# Sparse matrix
A = nx.to_scipy_sparse_array(G)
G = nx.from_scipy_sparse_array(A)
```
**Reference**: See `references/io.md` for complete documentation on all I/O formats including CSV, SQL databases, Cytoscape, DOT, and guidance on format selection for different use cases.
### 5. Visualization
Create clear and informative network visualizations:
plt.savefig('network.pdf', bbox_inches='tight') # Vector format
```
**Reference**: See `references/visualization.md` for extensive documentation on visualization techniques including layout algorithms, customization options, interactive visualizations with Plotly and PyVis, 3D networks, and publication-quality figure creation.
## Working with NetworkX
### Installation
Ensure NetworkX is installed:
```python
# Check if installed
import networkx as nx
print(nx.__version__)
# Install if needed (via bash)
# uv pip install networkx
# uv pip install networkx[default] # With optional dependencies
**Floating Point Precision**: When graphs contain floating-point numbers, all results are inherently approximate due to precision limitations. This can affect algorithm outcomes, particularly in minimum/maximum computations.
**Memory and Performance**: Each time a script runs, graph data must be loaded into memory. For large networks:
- Use appropriate data structures (sparse matrices for large sparse graphs)
- Consider loading only necessary subgraphs
- Use efficient file formats (pickle for Python objects, compressed formats)
- Leverage approximate algorithms for very large networks (e.g., `k` parameter in centrality calculations)
- For heavy workloads, NetworkX 3.x supports drop-in accelerated backends via the `backend=` keyword or `nx.config.backend_priority` — e.g. `nx-cugraph` (GPU), `nx-parallel` (multicore), `graphblas-algorithms` (sparse linear algebra). Install the backend package and pass `backend="cugraph"` (or similar) to supported functions; no algorithm code changes needed.
**Node and Edge Types**:
- Nodes can be any hashable Python object (numbers, strings, tuples, custom objects)
- Use meaningful identifiers for clarity
- When removing nodes, all incident edges are automatically removed
**Random Seeds**: Always set random seeds for reproducibility in random graph generation and force-directed layouts:
```python
G = nx.erdos_renyi_graph(n=100, p=0.1, seed=42)
pos = nx.spring_layout(G, seed=42)
```
## Quick Reference
### Basic Operations
```python
# Create
G = nx.Graph()
G.add_edge(1, 2)
# Query
G.number_of_nodes()
G.number_of_edges()
G.degree(1)
list(G.neighbors(1))
# Check
G.has_node(1)
G.has_edge(1, 2)
nx.is_connected(G)
# Modify
G.remove_node(1)
G.remove_edge(1, 2)
G.clear()
```
### Essential Algorithms
```python
# Paths
nx.shortest_path(G, source, target)
nx.all_pairs_shortest_path(G)
# Centrality
nx.degree_centrality(G)
nx.betweenness_centrality(G)
nx.closeness_centrality(G)
nx.pagerank(G)
# Clustering
nx.clustering(G)
nx.average_clustering(G)
# Components
nx.connected_components(G)
nx.strongly_connected_components(G) # Directed
# Community
community.greedy_modularity_communities(G)
```
### File I/O Quick Reference
```python
# Read
nx.read_edgelist('file.txt')
nx.read_graphml('file.graphml')
nx.read_gml('file.gml')
# Write
nx.write_edgelist(G, 'file.txt')
nx.write_graphml(G, 'file.graphml')
nx.write_gml(G, 'file.gml')
# Pandas
nx.from_pandas_edgelist(df, 'source', 'target')
nx.to_pandas_edgelist(G)
```
## Resources
This skill includes comprehensive reference documentation:
### references/graph-basics.md
Detailed guide on graph types, creating and modifying graphs, adding nodes and edges, managing attributes, examining structure, and working with subgraphs.
### references/algorithms.md
Complete coverage of NetworkX algorithms including shortest paths, centrality measures, connectivity, clustering, community detection, flow algorithms, tree algorithms, matching, coloring, isomorphism, and graph traversal.
### references/generators.md
Comprehensive documentation on graph generators including classic graphs, random models (Erdős-Rényi, Barabási-Albert, Watts-Strogatz), lattices, trees, social network models, and specialized generators.
### references/io.md
Complete guide to reading and writing graphs in various formats: edge lists, adjacency lists, GraphML, GML, JSON, CSV, Pandas DataFrames, NumPy arrays, SciPy sparse matrices, database integration, and format selection guidelines.
### references/visualization.md
Extensive documentation on visualization techniques including layout algorithms, customizing node and edge appearance, labels, interactive visualizations with Plotly and PyVis, 3D networks, bipartite layouts, and creating publication-quality figures.