networkx by davila7/claude-code-templates
npx skills add https://github.com/davila7/claude-code-templates --skill networkxNetworkX 是一个用于创建、操作和分析复杂网络与图的 Python 包。当处理网络或图数据结构时,请使用此技能,包括社交网络、生物网络、交通系统、引文网络、知识图谱,或任何涉及实体间关系的系统。
当任务涉及以下内容时,请调用此技能:
NetworkX 支持四种主要的图类型:
通过以下方式创建图:
import networkx as nx
# 创建空图
G = nx.Graph()
# 添加节点(可以是任何可哈希类型)
G.add_node(1)
G.add_nodes_from([2, 3, 4])
G.add_node("protein_A", type='enzyme', weight=1.5)
# 添加边
G.add_edge(1, 2)
G.add_edges_from([(1, 3), (2, 4)])
G.add_edge(1, 4, weight=0.8, relation='interacts')
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
参考:有关创建、修改、检查和图管理结构的全面指导,包括处理属性和子图,请参阅 references/graph-basics.md。
NetworkX 提供了广泛的网络分析算法:
最短路径:
# 查找最短路径
path = nx.shortest_path(G, source=1, target=5)
length = nx.shortest_path_length(G, source=1, target=5, weight='weight')
中心性度量:
# 度中心性
degree_cent = nx.degree_centrality(G)
# 中介中心性
betweenness = nx.betweenness_centrality(G)
# PageRank
pagerank = nx.pagerank(G)
社区检测:
from networkx.algorithms import community
# 检测社区
communities = community.greedy_modularity_communities(G)
连通性:
# 检查连通性
is_connected = nx.is_connected(G)
# 查找连通分量
components = list(nx.connected_components(G))
参考:有关所有可用算法的详细文档,包括最短路径、中心性度量、聚类、社区检测、流、匹配、树算法和图遍历,请参阅 references/algorithms.md。
为测试、模拟或建模创建合成网络:
经典图:
# 完全图
G = nx.complete_graph(n=10)
# 环图
G = nx.cycle_graph(n=20)
# 已知图
G = nx.karate_club_graph()
G = nx.petersen_graph()
随机网络:
# Erdős-Rényi 随机图
G = nx.erdos_renyi_graph(n=100, p=0.1, seed=42)
# Barabási-Albert 无标度网络
G = nx.barabasi_albert_graph(n=100, m=3, seed=42)
# Watts-Strogatz 小世界网络
G = nx.watts_strogatz_graph(n=100, k=6, p=0.1, seed=42)
结构化网络:
# 网格图
G = nx.grid_2d_graph(m=5, n=7)
# 随机树
G = nx.random_tree(n=100, seed=42)
参考:有关所有图生成器的全面覆盖,包括经典图、随机模型(Erdős-Rényi、Barabási-Albert、Watts-Strogatz)、格点图、二分图和专用网络模型,以及详细的参数和用例,请参阅 references/generators.md。
NetworkX 支持多种文件格式和数据源:
文件格式:
# 边列表
G = nx.read_edgelist('graph.edgelist')
nx.write_edgelist(G, 'graph.edgelist')
# GraphML(保留属性)
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
data = nx.node_link_data(G)
G = nx.node_link_graph(data)
Pandas 集成:
import pandas as pd
# 从 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')
# 转换为 DataFrame
df = nx.to_pandas_edgelist(G)
矩阵格式:
import numpy as np
# 邻接矩阵
A = nx.to_numpy_array(G)
G = nx.from_numpy_array(A)
# 稀疏矩阵
A = nx.to_scipy_sparse_array(G)
G = nx.from_scipy_sparse_array(A)
参考:有关所有 I/O 格式的完整文档,包括 CSV、SQL 数据库、Cytoscape、DOT,以及针对不同用例的格式选择指导,请参阅 references/io.md。
创建清晰且信息丰富的网络可视化:
基础可视化:
import matplotlib.pyplot as plt
# 简单绘制
nx.draw(G, with_labels=True)
plt.show()
# 使用布局
pos = nx.spring_layout(G, seed=42)
nx.draw(G, pos=pos, with_labels=True, node_color='lightblue', node_size=500)
plt.show()
自定义:
# 按度着色
node_colors = [G.degree(n) for n in G.nodes()]
nx.draw(G, node_color=node_colors, cmap=plt.cm.viridis)
# 按中心性调整大小
centrality = nx.betweenness_centrality(G)
node_sizes = [3000 * centrality[n] for n in G.nodes()]
nx.draw(G, node_size=node_sizes)
# 边权重
edge_widths = [3 * G[u][v].get('weight', 1) for u, v in G.edges()]
nx.draw(G, width=edge_widths)
布局算法:
# Spring 布局(力导向)
pos = nx.spring_layout(G, seed=42)
# 环形布局
pos = nx.circular_layout(G)
# Kamada-Kawai 布局
pos = nx.kamada_kawai_layout(G)
# 谱布局
pos = nx.spectral_layout(G)
出版质量:
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') # 矢量格式
参考:有关可视化技术的广泛文档,包括布局算法、自定义选项、使用 Plotly 和 PyVis 的交互式可视化、3D 网络以及创建出版质量图形,请参阅 references/visualization.md。
确保已安装 NetworkX:
# 检查是否已安装
import networkx as nx
print(nx.__version__)
# 如果需要则安装(通过 bash)
# uv pip install networkx
# uv pip install networkx[default] # 包含可选依赖项
大多数 NetworkX 任务遵循以下模式:
创建或加载图:
# 从头开始
G = nx.Graph()
G.add_edges_from([(1, 2), (2, 3), (3, 4)])
# 或从文件/数据加载
G = nx.read_edgelist('data.txt')
检查结构:
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)}")
分析:
# 计算度量
degree_cent = nx.degree_centrality(G)
avg_clustering = nx.average_clustering(G)
# 查找路径
path = nx.shortest_path(G, source=1, target=4)
# 检测社区
communities = community.greedy_modularity_communities(G)
可视化:
pos = nx.spring_layout(G, seed=42)
nx.draw(G, pos=pos, with_labels=True)
plt.show()
导出结果:
# 保存图
nx.write_graphml(G, 'analyzed_network.graphml')
# 保存度量
df = pd.DataFrame({
'node': list(degree_cent.keys()),
'centrality': list(degree_cent.values())
})
df.to_csv('centrality_results.csv', index=False)
浮点精度:当图中包含浮点数时,由于精度限制,所有结果本质上都是近似的。这可能会影响算法结果,特别是在最小/最大计算中。
内存与性能:每次脚本运行时,图数据都必须加载到内存中。对于大型网络:
k 参数)节点和边类型:
随机种子:在随机图生成和力导向布局中,始终设置随机种子以确保可重现性:
G = nx.erdos_renyi_graph(n=100, p=0.1, seed=42)
pos = nx.spring_layout(G, seed=42)
# 创建
G = nx.Graph()
G.add_edge(1, 2)
# 查询
G.number_of_nodes()
G.number_of_edges()
G.degree(1)
list(G.neighbors(1))
# 检查
G.has_node(1)
G.has_edge(1, 2)
nx.is_connected(G)
# 修改
G.remove_node(1)
G.remove_edge(1, 2)
G.clear()
# 路径
nx.shortest_path(G, source, target)
nx.all_pairs_shortest_path(G)
# 中心性
nx.degree_centrality(G)
nx.betweenness_centrality(G)
nx.closeness_centrality(G)
nx.pagerank(G)
# 聚类
nx.clustering(G)
nx.average_clustering(G)
# 分量
nx.connected_components(G)
nx.strongly_connected_components(G) # 有向图
# 社区
community.greedy_modularity_communities(G)
# 读取
nx.read_edgelist('file.txt')
nx.read_graphml('file.graphml')
nx.read_gml('file.gml')
# 写入
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)
此技能包含全面的参考文档:
关于图类型、创建和修改图、添加节点和边、管理属性、检查结构以及处理子图的详细指南。
NetworkX 算法的完整覆盖,包括最短路径、中心性度量、连通性、聚类、社区检测、流算法、树算法、匹配、着色、同构和图遍历。
图生成器的全面文档,包括经典图、随机模型(Erdős-Rényi、Barabási-Albert、Watts-Strogatz)、格点图、树、社交网络模型和专用生成器。
以各种格式读写图的完整指南:边列表、邻接列表、GraphML、GML、JSON、CSV、Pandas DataFrames、NumPy 数组、SciPy 稀疏矩阵、数据库集成和格式选择指南。
关于可视化技术的广泛文档,包括布局算法、自定义节点和边外观、标签、使用 Plotly 和 PyVis 的交互式可视化、3D 网络、二分图布局以及创建出版质量图形。
每周安装次数
151
代码仓库
GitHub 星标数
22.6K
首次出现
2026年1月21日
安全审计
安装于
claude-code122
opencode120
gemini-cli114
cursor112
codex102
antigravity99
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.
Invoke this skill when tasks involve:
NetworkX supports four main graph types:
Create graphs by:
import networkx as nx
# Create empty graph
G = nx.Graph()
# 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)
# 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.
NetworkX provides extensive algorithms for network analysis:
Shortest Paths :
# 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 :
# Degree centrality
degree_cent = nx.degree_centrality(G)
# Betweenness centrality
betweenness = nx.betweenness_centrality(G)
# PageRank
pagerank = nx.pagerank(G)
Community Detection :
from networkx.algorithms import community
# Detect communities
communities = community.greedy_modularity_communities(G)
Connectivity :
# Check connectivity
is_connected = nx.is_connected(G)
# 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.
Create synthetic networks for testing, simulation, or modeling:
Classic Graphs :
# 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 :
# 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 :
# Grid graph
G = nx.grid_2d_graph(m=5, n=7)
# 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.
NetworkX supports numerous file formats and data sources:
File Formats :
# 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
data = nx.node_link_data(G)
G = nx.node_link_graph(data)
Pandas Integration :
import pandas as pd
# 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')
# To DataFrame
df = nx.to_pandas_edgelist(G)
Matrix Formats :
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.
Create clear and informative network visualizations:
Basic Visualization :
import matplotlib.pyplot as plt
# Simple draw
nx.draw(G, with_labels=True)
plt.show()
# 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 :
# Color by degree
node_colors = [G.degree(n) for n in G.nodes()]
nx.draw(G, node_color=node_colors, cmap=plt.cm.viridis)
# 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)
# 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 :
# Spring layout (force-directed)
pos = nx.spring_layout(G, seed=42)
# Circular layout
pos = nx.circular_layout(G)
# Kamada-Kawai layout
pos = nx.kamada_kawai_layout(G)
# Spectral layout
pos = nx.spectral_layout(G)
Publication Quality :
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.
Ensure NetworkX is installed:
# 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
Most NetworkX tasks follow this pattern:
Create or Load Graph :
# 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')
Examine Structure :
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)}")
Analyze :
# 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)
Visualize :
pos = nx.spring_layout(G, seed=42)
nx.draw(G, pos=pos, with_labels=True)
plt.show()
Export Results :
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:
k parameter in centrality calculations)Node and Edge Types :
Random Seeds : Always set random seeds for reproducibility in random graph generation and force-directed layouts:
G = nx.erdos_renyi_graph(n=100, p=0.1, seed=42)
pos = nx.spring_layout(G, seed=42)
# 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()
# 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)
# 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)
This skill includes comprehensive reference documentation:
Detailed guide on graph types, creating and modifying graphs, adding nodes and edges, managing attributes, examining structure, and working with subgraphs.
Complete coverage of NetworkX algorithms including shortest paths, centrality measures, connectivity, clustering, community detection, flow algorithms, tree algorithms, matching, coloring, isomorphism, and graph traversal.
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.
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.
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.
Weekly Installs
151
Repository
GitHub Stars
22.6K
First Seen
Jan 21, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
claude-code122
opencode120
gemini-cli114
cursor112
codex102
antigravity99
DOCX文件创建、编辑与分析完整指南 - 使用docx-js、Pandoc和Python脚本
51,800 周安装
AI引导抗体工程优化:从先导物到临床候选物的全流程解决方案
158 周安装
iOS Core Location 问题诊断指南 - 位置更新、后台定位、授权问题排查
159 周安装
Tone.js 教程:使用 Web Audio API 在浏览器中构建交互式音乐应用
160 周安装
sciomc:AI驱动的并行研究代理,自动化分解与验证复杂研究目标
168 周安装
Playwright CLI:无需编码的浏览器自动化测试工具 - 快速上手与安全指南
161 周安装
Spec测试套件生成工具 - 自动化编排smoke/regression/targeted测试用例,提升软件质量
70 周安装
# 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)