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

networkx绘图因colormap缺失节点元素触发ValueError解决方案咨询

问题原因

报错的核心原因如下:

  • 你当前构建的color_map索引仅包含df2中存在的节点,不在df2中的节点(比如示例中的Z)根本不在color_map的索引范围内
  • 你调用的fillna('black')仅能处理索引存在、但值为NaN的情况,无法补全索引缺失的节点的颜色
  • 最终调用nx.get_node_attributes时,只会返回已经设置了colour属性的节点的颜色,数量少于图的总节点数,导致传入node_color的参数长度和节点总数不匹配

修复方案

你只需要在构建完图之后,将color_map的索引补全为图中所有的节点,缺失值统一填充为黑色即可,修改后的完整代码如下:

import networkx as nx
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt, colors as mcolor

# Sample DataFrames
df1 = pd.DataFrame({
    'Node': ['A', 'A', 'B', 'B', 'B', 'Z'],
    'Edge': ['B', 'D', 'N', 'A', 'X', 'C']
})
df2 = pd.DataFrame({
    'Nodes': ['A', 'B', 'C', 'D', 'N', 'S', 'X'],
    'Attribute': [-1, 0, -1.5, 1, 1, 9, 0]
})

# Simplified construction of `colour_map`
uni_val = df2['Attribute'].unique()
colors = plt.cm.jet(np.linspace(0, 1, len(uni_val)))
# Map colours to_hex then zip with
mapper = dict(zip(uni_val, map(mcolor.to_hex, colors)))
color_map = df2.set_index('Nodes')['Attribute'].map(mapper)


G = nx.from_pandas_edgelist(df1, source='Node', target='Edge')
# 补全所有节点的颜色,不在df2中的节点统一填充黑色
all_nodes = list(G.nodes())
color_map = color_map.reindex(all_nodes, fill_value='black')

# Add Attribute to each node
nx.set_node_attributes(G, color_map, name="colour")

# Then draw with colours based on attribute values:
nx.draw(G,
        node_color=nx.get_node_attributes(G, 'colour').values(),
        with_labels=True)

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 16:45:03