You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NetworkX图中根据节点度数对应的颜色设置边颜色?

解决方案:基于CSV构建有向图并实现节点/边颜色匹配

问题分析

原代码的核心错误:

  • edgecol未初始化就直接赋值,触发数组越界
  • 使用nx.dfs_edges遍历会重复处理无向边,导致边数统计错误
  • 函数返回值逻辑错误(返回函数自身而非颜色列表)

完整实现步骤

1. 读取CSV构建有向图

假设CSV格式为source,target,weight,用pandas读取后批量添加到有向图中。

2. 节点颜色按度数生成

基于节点总度数(有向图可选择入度/出度)生成颜色值,配合颜色映射让可视化更直观。

3. 边颜色匹配对应节点

通过节点-颜色映射字典,快速匹配每条边的起点(或终点)颜色,避免重复计算。

4. 高效获取节点索引与对应边

用字典映射节点到索引,直接通过G.edges()获取全量边,或通过G.adj[node]获取单个节点的邻边。

完整代码

import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd

# 1. 读取CSV构建有向图(实际场景替换为pd.read_csv("你的文件路径.csv"))
csv_data = pd.DataFrame({
    'source': [1, 1, 2, 2, 2, 3, 3, 4, 4, 6],
    'target': [2, 6, 3, 4, 6, 4, 5, 8, 9, 7],
    'weight': [10, 15, 20, 10, 20, 30, 15, 20, 10, 30]
})

G = nx.DiGraph()
for _, row in csv_data.iterrows():
    G.add_edge(row['source'], row['target'], weight=row['weight'])

# 2. 生成节点颜色(按总度数)
def get_node_colors(g):
    return [g.degree(node) for node in g.nodes()]

node_colors = get_node_colors(G)

# 3. 生成边颜色:匹配每条边的起点颜色
def get_edge_colors(g, node_colors):
    node_color_map = dict(zip(g.nodes(), node_colors))
    return [node_color_map[edge[0]] for edge in g.edges()]

edge_colors = get_edge_colors(G, node_colors)

# 4. 高效获取节点索引与对应边
node_to_index = {node: idx for idx, node in enumerate(G.nodes())}
# 示例:获取节点2的索引和所有出边
target_node = 2
print(f"节点{target_node}的索引: {node_to_index[target_node]}")
print(f"节点{target_node}的出边: {list(G.adj[target_node].items())}")

# 可视化
plt.figure(figsize=(10, 8))
cmap = plt.cm.viridis
nx.draw(G, 
        node_color=node_colors, 
        edge_color=edge_colors,
        with_labels=True,
        cmap=cmap,
        edge_cmap=cmap,
        node_size=1500,
        font_size=12)
plt.colorbar(plt.cm.ScalarMappable(cmap=cmap), label='节点度数')
plt.title("有向图:节点颜色按度数,边颜色匹配起点")
plt.show()

关键改进点

  • 修复越界问题:直接遍历G.edges()生成边颜色列表,确保长度与实际边数一致
  • 高效映射:用字典node_color_map实现O(1)时间复杂度的颜色查找
  • 有向图适配:替换nx.Graph为nx.DiGraph满足需求
  • 可视化优化:添加颜色映射条,明确度数与颜色的对应关系
  • 快速查询:通过字典映射节点到索引,G.adj直接获取节点邻边,性能更优

内容的提问来源于stack exchange,提问作者bonCodigo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 11:05:43