networkx

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

NetworkX

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.
NetworkX是一个用于创建、操作和分析复杂网络与图的Python包。当你处理网络或图数据结构(包括社交网络、生物网络、交通系统、引文网络、知识图谱或任何涉及实体间关系的系统)时,可以使用这个工具。

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
  • Network generation: Creating synthetic networks (random, scale-free, small-world models) for testing or simulation
  • Graph I/O: Reading from or writing to various formats (edge lists, GraphML, JSON, CSV, adjacency matrices)
  • Visualization: Drawing and customizing network visualizations with matplotlib or interactive libraries
  • Network comparison: Checking isomorphism, computing graph metrics, analyzing structural properties
在以下任务场景中使用该工具:
  • 创建图:从数据构建网络结构,添加带有属性的节点和边
  • 图分析:计算中心性指标、寻找最短路径、检测社区、衡量聚类程度
  • 图算法:运行标准算法如Dijkstra算法、PageRank、最小生成树、最大流
  • 网络生成:创建合成网络(随机、无标度、小世界模型)用于测试或模拟
  • 图的输入输出:读取或写入多种格式(边列表、GraphML、JSON、CSV、邻接矩阵)
  • 可视化:使用matplotlib或交互式库绘制和自定义网络可视化图
  • 网络比较:检查同构性、计算图指标、分析结构特性

Core Capabilities

核心功能

1. Graph Creation and Manipulation

1. 图的创建与操作

NetworkX supports four main graph types:
  • Graph: Undirected graphs with single edges
  • DiGraph: Directed graphs with one-way connections
  • MultiGraph: Undirected graphs allowing multiple edges between nodes
  • MultiDiGraph: Directed graphs with multiple edges
Create graphs by:
python
import networkx as nx
NetworkX支持四种主要图类型:
  • Graph:无向图,边为单向连接
  • DiGraph:有向图,边为单向连接
  • MultiGraph:允许多条边连接同一对节点的无向图
  • MultiDiGraph:允许多条边连接同一对节点的有向图
创建图的方式:
python
import networkx as nx

Create empty graph

Create empty graph

G = nx.Graph()
G = nx.Graph()

Add nodes (can be any hashable type)

Add nodes (can be any hashable type)

G.add_node(1) G.add_nodes_from([2, 3, 4]) G.add_node("protein_A", type='enzyme', weight=1.5)
G.add_node(1) G.add_nodes_from([2, 3, 4]) G.add_node("protein_A", type='enzyme', weight=1.5)

Add edges

Add edges

G.add_edge(1, 2) G.add_edges_from([(1, 3), (2, 4)]) G.add_edge(1, 4, weight=0.8, relation='interacts')

**Reference**: See `references/graph-basics.md` for comprehensive guidance on creating, modifying, examining, and managing graph structures, including working with attributes and subgraphs.
G.add_edge(1, 2) G.add_edges_from([(1, 3), (2, 4)]) G.add_edge(1, 4, weight=0.8, relation='interacts')

**参考**:详见`references/graph-basics.md`,其中包含关于创建、修改、检查和管理图结构(包括属性和子图操作)的全面指导。

2. Graph Algorithms

2. 图算法

NetworkX provides extensive algorithms for network analysis:
Shortest Paths:
python
undefined
NetworkX提供了丰富的网络分析算法:
最短路径:
python
undefined

Find shortest path

Find shortest path

path = nx.shortest_path(G, source=1, target=5) length = nx.shortest_path_length(G, source=1, target=5, weight='weight')

**Centrality Measures**:
```python
path = nx.shortest_path(G, source=1, target=5) length = nx.shortest_path_length(G, source=1, target=5, weight='weight')

**中心性指标**:
```python

Degree centrality

Degree centrality

degree_cent = nx.degree_centrality(G)
degree_cent = nx.degree_centrality(G)

Betweenness centrality

Betweenness centrality

betweenness = nx.betweenness_centrality(G)
betweenness = nx.betweenness_centrality(G)

PageRank

PageRank

pagerank = nx.pagerank(G)

**Community Detection**:
```python
from networkx.algorithms import community
pagerank = nx.pagerank(G)

**社区检测**:
```python
from networkx.algorithms import community

Detect communities

Detect communities

communities = community.greedy_modularity_communities(G)

**Connectivity**:
```python
communities = community.greedy_modularity_communities(G)

**连通性**:
```python

Check connectivity

Check connectivity

is_connected = nx.is_connected(G)
is_connected = nx.is_connected(G)

Find connected components

Find connected components

components = list(nx.connected_components(G))

**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.
components = list(nx.connected_components(G))

**参考**:详见`references/algorithms.md`,其中包含所有可用算法的详细文档,包括最短路径、中心性指标、聚类、社区检测、流、匹配、树算法和图遍历。

3. Graph Generators

3. 图生成器

Create synthetic networks for testing, simulation, or modeling:
Classic Graphs:
python
undefined
创建用于测试、模拟或建模的合成网络:
经典图:
python
undefined

Complete graph

Complete graph

G = nx.complete_graph(n=10)
G = nx.complete_graph(n=10)

Cycle graph

Cycle graph

G = nx.cycle_graph(n=20)
G = nx.cycle_graph(n=20)

Known graphs

Known graphs

G = nx.karate_club_graph() G = nx.petersen_graph()

**Random Networks**:
```python
G = nx.karate_club_graph() G = nx.petersen_graph()

**随机网络**:
```python

Erdős-Rényi random graph

Erdős-Rényi random graph

G = nx.erdos_renyi_graph(n=100, p=0.1, seed=42)
G = nx.erdos_renyi_graph(n=100, p=0.1, seed=42)

Barabási-Albert scale-free network

Barabási-Albert scale-free network

G = nx.barabasi_albert_graph(n=100, m=3, seed=42)
G = nx.barabasi_albert_graph(n=100, m=3, seed=42)

Watts-Strogatz small-world network

Watts-Strogatz small-world network

G = nx.watts_strogatz_graph(n=100, k=6, p=0.1, seed=42)

**Structured Networks**:
```python
G = nx.watts_strogatz_graph(n=100, k=6, p=0.1, seed=42)

**结构化网络**:
```python

Grid graph

Grid graph

G = nx.grid_2d_graph(m=5, n=7)
G = nx.grid_2d_graph(m=5, n=7)

Random tree

Random tree

G = nx.random_tree(n=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.
G = nx.random_tree(n=100, seed=42)

**参考**:详见`references/generators.md`,其中包含所有图生成器的全面介绍,包括经典图、随机图、格图、二分图和专用网络模型,以及详细的参数和用例。

4. Reading and Writing Graphs

4. 图的读取与写入

NetworkX supports numerous file formats and data sources:
File Formats:
python
undefined
NetworkX支持多种文件格式和数据源:
文件格式:
python
undefined

Edge list

Edge list

G = nx.read_edgelist('graph.edgelist') nx.write_edgelist(G, 'graph.edgelist')
G = nx.read_edgelist('graph.edgelist') nx.write_edgelist(G, 'graph.edgelist')

GraphML (preserves attributes)

GraphML (preserves attributes)

G = nx.read_graphml('graph.graphml') nx.write_graphml(G, 'graph.graphml')
G = nx.read_graphml('graph.graphml') nx.write_graphml(G, 'graph.graphml')

GML

GML

G = nx.read_gml('graph.gml') nx.write_gml(G, 'graph.gml')
G = nx.read_gml('graph.gml') nx.write_gml(G, 'graph.gml')

JSON

JSON

data = nx.node_link_data(G) G = nx.node_link_graph(data)

**Pandas Integration**:
```python
import pandas as pd
data = nx.node_link_data(G) G = nx.node_link_graph(data)

**与Pandas集成**:
```python
import pandas as pd

From DataFrame

From DataFrame

df = pd.DataFrame({'source': [1, 2, 3], 'target': [2, 3, 4], 'weight': [0.5, 1.0, 0.75]}) G = nx.from_pandas_edgelist(df, 'source', 'target', edge_attr='weight')
df = pd.DataFrame({'source': [1, 2, 3], 'target': [2, 3, 4], 'weight': [0.5, 1.0, 0.75]}) G = nx.from_pandas_edgelist(df, 'source', 'target', edge_attr='weight')

To DataFrame

To DataFrame

df = nx.to_pandas_edgelist(G)

**Matrix Formats**:
```python
import numpy as np
df = nx.to_pandas_edgelist(G)

**矩阵格式**:
```python
import numpy as np

Adjacency matrix

Adjacency matrix

A = nx.to_numpy_array(G) G = nx.from_numpy_array(A)
A = nx.to_numpy_array(G) G = nx.from_numpy_array(A)

Sparse matrix

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.
A = nx.to_scipy_sparse_array(G) G = nx.from_scipy_sparse_array(A)

**参考**:详见`references/io.md`,其中包含所有输入输出格式的完整文档,包括CSV、SQL数据库、Cytoscape、DOT,以及不同用例下的格式选择指导。

5. Visualization

5. 可视化

Create clear and informative network visualizations:
Basic Visualization:
python
import matplotlib.pyplot as plt
创建清晰且信息丰富的网络可视化图:
基础可视化:
python
import matplotlib.pyplot as plt

Simple draw

Simple draw

nx.draw(G, with_labels=True) plt.show()
nx.draw(G, with_labels=True) plt.show()

With layout

With layout

pos = nx.spring_layout(G, seed=42) nx.draw(G, pos=pos, with_labels=True, node_color='lightblue', node_size=500) plt.show()

**Customization**:
```python
pos = nx.spring_layout(G, seed=42) nx.draw(G, pos=pos, with_labels=True, node_color='lightblue', node_size=500) plt.show()

**自定义设置**:
```python

Color by degree

Color by degree

node_colors = [G.degree(n) for n in G.nodes()] nx.draw(G, node_color=node_colors, cmap=plt.cm.viridis)
node_colors = [G.degree(n) for n in G.nodes()] nx.draw(G, node_color=node_colors, cmap=plt.cm.viridis)

Size by centrality

Size by centrality

centrality = nx.betweenness_centrality(G) node_sizes = [3000 * centrality[n] for n in G.nodes()] nx.draw(G, node_size=node_sizes)
centrality = nx.betweenness_centrality(G) node_sizes = [3000 * centrality[n] for n in G.nodes()] nx.draw(G, node_size=node_sizes)

Edge weights

Edge weights

edge_widths = [3 * G[u][v].get('weight', 1) for u, v in G.edges()] nx.draw(G, width=edge_widths)

**Layout Algorithms**:
```python
edge_widths = [3 * G[u][v].get('weight', 1) for u, v in G.edges()] nx.draw(G, width=edge_widths)

**布局算法**:
```python

Spring layout (force-directed)

Spring layout (force-directed)

pos = nx.spring_layout(G, seed=42)
pos = nx.spring_layout(G, seed=42)

Circular layout

Circular layout

pos = nx.circular_layout(G)
pos = nx.circular_layout(G)

Kamada-Kawai layout

Kamada-Kawai layout

pos = nx.kamada_kawai_layout(G)
pos = nx.kamada_kawai_layout(G)

Spectral layout

Spectral layout

pos = nx.spectral_layout(G)

**Publication Quality**:
```python
plt.figure(figsize=(12, 8))
pos = nx.spring_layout(G, seed=42)
nx.draw(G, pos=pos, node_color='lightblue', node_size=500,
        edge_color='gray', with_labels=True, font_size=10)
plt.title('Network Visualization', fontsize=16)
plt.axis('off')
plt.tight_layout()
plt.savefig('network.png', dpi=300, bbox_inches='tight')
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.
pos = nx.spectral_layout(G)

**出版级质量**:
```python
plt.figure(figsize=(12, 8))
pos = nx.spring_layout(G, seed=42)
nx.draw(G, pos=pos, node_color='lightblue', node_size=500,
        edge_color='gray', with_labels=True, font_size=10)
plt.title('Network Visualization', fontsize=16)
plt.axis('off')
plt.tight_layout()
plt.savefig('network.png', dpi=300, bbox_inches='tight')
plt.savefig('network.pdf', bbox_inches='tight')  # Vector format
参考:详见
references/visualization.md
,其中包含丰富的可视化技术文档,包括布局算法、节点和边的自定义选项、标签、使用Plotly和PyVis的交互式可视化、3D网络以及出版级图形的创建方法。

Working with NetworkX

使用NetworkX

Installation

安装

Ensure NetworkX is installed:
python
undefined
确保已安装NetworkX:
python
undefined

Check if installed

Check if installed

import networkx as nx print(nx.version)
import networkx as nx print(nx.version)

Install if needed (via bash)

Install if needed (via bash)

uv pip install networkx

uv pip install networkx

uv pip install networkx[default] # With optional dependencies

uv pip install networkx[default] # With optional dependencies

undefined
undefined

Common Workflow Pattern

常见工作流模式

Most NetworkX tasks follow this pattern:
  1. Create or Load Graph:
    python
    # From scratch
    G = nx.Graph()
    G.add_edges_from([(1, 2), (2, 3), (3, 4)])
    
    # Or load from file/data
    G = nx.read_edgelist('data.txt')
  2. Examine Structure:
    python
    print(f"Nodes: {G.number_of_nodes()}")
    print(f"Edges: {G.number_of_edges()}")
    print(f"Density: {nx.density(G)}")
    print(f"Connected: {nx.is_connected(G)}")
  3. Analyze:
    python
    # Compute metrics
    degree_cent = nx.degree_centrality(G)
    avg_clustering = nx.average_clustering(G)
    
    # Find paths
    path = nx.shortest_path(G, source=1, target=4)
    
    # Detect communities
    communities = community.greedy_modularity_communities(G)
  4. Visualize:
    python
    pos = nx.spring_layout(G, seed=42)
    nx.draw(G, pos=pos, with_labels=True)
    plt.show()
  5. Export Results:
    python
    # Save graph
    nx.write_graphml(G, 'analyzed_network.graphml')
    
    # Save metrics
    df = pd.DataFrame({
        'node': list(degree_cent.keys()),
        'centrality': list(degree_cent.values())
    })
    df.to_csv('centrality_results.csv', index=False)
大多数NetworkX任务遵循以下模式:
  1. 创建或加载图:
    python
    # From scratch
    G = nx.Graph()
    G.add_edges_from([(1, 2), (2, 3), (3, 4)])
    
    # Or load from file/data
    G = nx.read_edgelist('data.txt')
  2. 检查结构:
    python
    print(f"Nodes: {G.number_of_nodes()}")
    print(f"Edges: {G.number_of_edges()}")
    print(f"Density: {nx.density(G)}")
    print(f"Connected: {nx.is_connected(G)}")
  3. 分析:
    python
    # Compute metrics
    degree_cent = nx.degree_centrality(G)
    avg_clustering = nx.average_clustering(G)
    
    # Find paths
    path = nx.shortest_path(G, source=1, target=4)
    
    # Detect communities
    communities = community.greedy_modularity_communities(G)
  4. 可视化:
    python
    pos = nx.spring_layout(G, seed=42)
    nx.draw(G, pos=pos, with_labels=True)
    plt.show()
  5. 导出结果:
    python
    # Save graph
    nx.write_graphml(G, 'analyzed_network.graphml')
    
    # Save metrics
    df = pd.DataFrame({
        'node': list(degree_cent.keys()),
        'centrality': list(degree_cent.values())
    })
    df.to_csv('centrality_results.csv', index=False)

Important Considerations

重要注意事项

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)
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)
浮点数精度:当图中包含浮点数时,由于精度限制,所有结果本质上都是近似值。这可能会影响算法的输出,尤其是在最小值/最大值计算中。
内存与性能:每次运行脚本时,图数据都需要加载到内存中。对于大型网络:
  • 使用合适的数据结构(大型稀疏图使用稀疏矩阵)
  • 考虑仅加载必要的子图
  • 使用高效的文件格式(Python对象使用pickle,压缩格式)
  • 对超大型网络使用近似算法(例如中心性计算中的
    k
    参数)
节点与边类型:
  • 节点可以是任何可哈希的Python对象(数字、字符串、元组、自定义对象)
  • 使用有意义的标识符以提高清晰度
  • 删除节点时,所有关联的边会自动被删除
随机种子:在生成随机图和力导向布局时,始终设置随机种子以保证结果可复现:
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
undefined
python
undefined

Create

Create

G = nx.Graph() G.add_edge(1, 2)
G = nx.Graph() G.add_edge(1, 2)

Query

Query

G.number_of_nodes() G.number_of_edges() G.degree(1) list(G.neighbors(1))
G.number_of_nodes() G.number_of_edges() G.degree(1) list(G.neighbors(1))

Check

Check

G.has_node(1) G.has_edge(1, 2) nx.is_connected(G)
G.has_node(1) G.has_edge(1, 2) nx.is_connected(G)

Modify

Modify

G.remove_node(1) G.remove_edge(1, 2) G.clear()
undefined
G.remove_node(1) G.remove_edge(1, 2) G.clear()
undefined

Essential Algorithms

核心算法

python
undefined
python
undefined

Paths

Paths

nx.shortest_path(G, source, target) nx.all_pairs_shortest_path(G)
nx.shortest_path(G, source, target) nx.all_pairs_shortest_path(G)

Centrality

Centrality

nx.degree_centrality(G) nx.betweenness_centrality(G) nx.closeness_centrality(G) nx.pagerank(G)
nx.degree_centrality(G) nx.betweenness_centrality(G) nx.closeness_centrality(G) nx.pagerank(G)

Clustering

Clustering

nx.clustering(G) nx.average_clustering(G)
nx.clustering(G) nx.average_clustering(G)

Components

Components

nx.connected_components(G) nx.strongly_connected_components(G) # Directed
nx.connected_components(G) nx.strongly_connected_components(G) # Directed

Community

Community

community.greedy_modularity_communities(G)
undefined
community.greedy_modularity_communities(G)
undefined

File I/O Quick Reference

文件输入输出快速参考

python
undefined
python
undefined

Read

Read

nx.read_edgelist('file.txt') nx.read_graphml('file.graphml') nx.read_gml('file.gml')
nx.read_edgelist('file.txt') nx.read_graphml('file.graphml') nx.read_gml('file.gml')

Write

Write

nx.write_edgelist(G, 'file.txt') nx.write_graphml(G, 'file.graphml') nx.write_gml(G, 'file.gml')
nx.write_edgelist(G, 'file.txt') nx.write_graphml(G, 'file.graphml') nx.write_gml(G, 'file.gml')

Pandas

Pandas

nx.from_pandas_edgelist(df, 'source', 'target') nx.to_pandas_edgelist(G)
undefined
nx.from_pandas_edgelist(df, 'source', 'target') nx.to_pandas_edgelist(G)
undefined

Resources

额外资源

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.

Additional Resources