Graph Analysis Skill
Analyze graphs and networks using Python and NetworkX. Supports building graphs from data, running graph algorithms, and generating visualizations.
Setup
Before first use, install dependencies:
CODEBLOCK0
Capabilities
1. Build a Graph
Create graphs from edge lists, adjacency matrices, CSV files, or JSON data.
From an edge list (CSV or inline):
CODEBLOCK1
From inline data:
CODEBLOCK2
Directed graph:
CODEBLOCK3
2. Graph Metrics
Run these to answer questions about graph structure:
CODEBLOCK4
3. Shortest Paths
CODEBLOCK5
4. Community Detection
CODEBLOCK6
5. Visualization
Save graph visualizations as PNG images:
CODEBLOCK7
Color by community:
CODEBLOCK8
6. Graph Generators (for testing or simulation)
CODEBLOCK9
When to Use This Skill
Use this skill when the user asks to:
- - Analyze relationships, connections, or networks in data
- Find important/central/influential nodes in a network
- Detect communities or clusters in a graph
- Find shortest paths between entities
- Visualize a network or relationship diagram
- Build a graph from CSV, JSON, or other structured data
- Run graph algorithms (PageRank, centrality, clustering coefficient, etc.)
Notes
- - For large graphs (>10,000 nodes), prefer
louvain_communities over INLINECODE1 - Always use
matplotlib.use("Agg") before importing pyplot (no display server) - Save visualizations as PNG files and show them to the user
- When reading user data, infer source/target columns from context — common patterns include: from/to, source/target, node1/node2, parent/child
图分析技能
使用Python和NetworkX分析图与网络。支持从数据构建图、运行图算法以及生成可视化结果。
环境配置
首次使用前,请安装依赖项:
bash
pip install networkx matplotlib numpy --break-system-packages
功能说明
1. 构建图
通过边列表、邻接矩阵、CSV文件或JSON数据创建图。
从边列表(CSV或内联数据):
python
import networkx as nx
从包含列:source, target, weight(可选)的CSV文件读取
import csv
G = nx.Graph()
with open(edges.csv) as f:
reader = csv.DictReader(f)
for row in reader:
weight = float(row.get(weight, 1.0))
G.add_edge(row[source], row[target], weight=weight)
从内联数据:
python
import networkx as nx
G = nx.Graph()
G.addedgesfrom([(A, B), (B, C), (A, C), (C, D)])
有向图:
python
G = nx.DiGraph()
G.addedgesfrom([(A, B), (B, C)])
2. 图度量指标
运行以下代码以回答关于图结构的问题:
python
import networkx as nx
基本统计信息
print(f节点数:{G.number
ofnodes()})
print(f边数:{G.number
ofedges()})
print(f密度:{nx.density(G):.4f})
print(f连通性:{nx.is_connected(G)})
中心性度量
degree
cent = nx.degreecentrality(G)
betweenness = nx.betweenness_centrality(G)
closeness = nx.closeness_centrality(G)
pagerank = nx.pagerank(G)
查找最重要的节点
top
bydegree = sorted(degree_cent.items(), key=lambda x: x[1], reverse=True)[:10]
top
bybetweenness = sorted(betweenness.items(), key=lambda x: x[1], reverse=True)[:10]
top
bypagerank = sorted(pagerank.items(), key=lambda x: x[1], reverse=True)[:10]
print(按度中心性排名前10的节点:, topbydegree)
print(按介数中心性排名前10的节点:, topbybetweenness)
print(按PageRank排名前10的节点:, topbypagerank)
3. 最短路径
python
两个节点之间的最短路径
path = nx.shortest_path(G, source=A, target=D)
length = nx.shortest
pathlength(G, source=A, target=D)
print(f路径:{ -> .join(path)}(长度:{length}))
加权最短路径
path
w = nx.shortestpath(G, source=A, target=D, weight=weight)
所有节点对的最短路径长度
all
lengths = dict(nx.allpairs
shortestpath_length(G))
4. 社区检测
python
from networkx.algorithms.community import greedymodularitycommunities, louvain_communities
贪心模块度
communities
greedy = list(greedymodularity_communities(G))
print(f发现 {len(communities_greedy)} 个社区(贪心算法))
Louvain算法(适用于大型图)
communities
louvain = list(louvaincommunities(G))
print(f发现 {len(communities_louvain)} 个社区(Louvain算法))
打印社区成员
for i, comm in enumerate(communities_louvain):
print(f 社区 {i}:{sorted(comm)})
5. 可视化
将图的可视化结果保存为PNG图片:
python
import matplotlib
matplotlib.use(Agg)
import matplotlib.pyplot as plt
import networkx as nx
fig, ax = plt.subplots(figsize=(12, 8))
布局选项:springlayout, circularlayout, kamadakawailayout, shell_layout
pos = nx.spring_layout(G, seed=42)
根据度数设置节点大小
node_sizes = [300 * G.degree(n) for n in G.nodes()]
根据社区设置节点颜色(如果已计算社区)
nx.draw(
G, pos, ax=ax,
with_labels=True,
node
size=nodesizes,
node_color=steelblue,
edge_color=#cccccc,
font_size=8,
font_weight=bold,
width=0.8,
)
ax.set_title(图可视化)
plt.tight_layout()
plt.savefig(graph.png, dpi=150)
plt.close()
print(已保存 graph.png)
按社区着色:
python
import matplotlib
matplotlib.use(Agg)
import matplotlib.pyplot as plt
import networkx as nx
from networkx.algorithms.community import louvain_communities
communities = list(louvain_communities(G))
color_map = {}
for i, comm in enumerate(communities):
for node in comm:
color_map[node] = i
nodecolors = [colormap[n] for n in G.nodes()]
pos = nx.spring_layout(G, seed=42)
fig, ax = plt.subplots(figsize=(12, 8))
nx.draw(
G, pos, ax=ax,
with_labels=True,
nodecolor=nodecolors,
cmap=plt.cm.Set3,
node_size=500,
edge_color=#cccccc,
font_size=8,
)
ax.set_title(社区分布)
plt.tight_layout()
plt.savefig(communities.png, dpi=150)
plt.close()
print(已保存 communities.png)
6. 图生成器(用于测试或模拟)
python
import networkx as nx
常用测试图
G = nx.karate
clubgraph() # 经典社交网络(34个节点)
G = nx.barabasi
albertgraph(100, 3) # 无标度网络
G = nx.erdos
renyigraph(50, 0.1) # 随机图
G = nx.watts
strogatzgraph(30, 4, 0.3) # 小世界网络
使用场景
当用户提出以下需求时使用此技能:
- - 分析数据中的关系、连接或网络结构
- 查找网络中重要/核心/有影响力的节点
- 检测图中的社区或聚类
- 查找实体之间的最短路径
- 可视化网络或关系图
- 从CSV、JSON或其他结构化数据构建图
- 运行图算法(PageRank、中心性、聚类系数等)
注意事项
- - 对于大型图(超过10,000个节点),优先使用louvaincommunities而非greedymodularity_communities
- 在导入pyplot之前始终使用matplotlib.use(Agg)(无显示服务器环境)
- 将可视化结果保存为PNG文件并展示给用户
- 读取用户数据时,根据上下文推断源/目标列——常见模式包括:from/to、source/target、node1/node2、parent/child