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

Networkx节点着色后添加colorbar报AttributeError错误求助

问题解决:NetworkX节点着色后添加ColorBar报错

错误原因

nx.draw()执行后返回None,而fig.colorbar()需要接收matplotlib的可映射对象(mappable)(比如PathCollection),直接传入None会触发AttributeError: 'NoneType' object has no attribute 'get_array'。

修正方案

改用nx.draw_networkx_nodes()单独绘制节点(该函数返回可用于生成colorbar的对象),再分别绘制边和标签,最后基于节点绘制结果生成colorbar。

完整修正代码

import numpy as np
import networkx as nx
import matplotlib.pyplot as plt

G = nx.grid_2d_graph(3,3)
new_nodes = {e: n for n, e in enumerate(G.nodes, start=1)}
new_edges = [(new_nodes[e1], new_nodes[e2]) for e1, e2 in G.edges]
G = nx.Graph()
G.add_edges_from(new_edges)

A1 = nx.adjacency_matrix(G) 
A = A1.toarray()
print(A) 

fig, ax = plt.subplots(1, 1)
P = np.array([1,2,5,4,5,6,7,2,10])

# 单独绘制节点,获取可映射对象
scatter = nx.draw_networkx_nodes(G, pos=nx.spring_layout(G), node_color=P, node_size=1000, cmap='Blues', ax=ax)
# 绘制边
nx.draw_networkx_edges(G, pos=nx.spring_layout(G), ax=ax)
# 绘制节点标签
nx.draw_networkx_labels(G, pos=nx.spring_layout(G), ax=ax)

# 基于节点绘制对象生成colorbar
fig.colorbar(scatter)
plt.show()

关键说明

  • nx.draw_networkx_nodes()返回的scatter是matplotlib的PathCollection对象,具备get_array()方法,可被colorbar()识别。
  • node_color直接传入P即可,无需用[P]包装(包装后会变成二维数组,可能导致颜色映射不符合预期)。
  • 统一使用ax参数指定绘图坐标轴,保证所有元素绘制在同一个子图中。

原报错信息:

in <module>
    fig.colorbar(D)

  File "C:\Users\USER\anaconda3\lib\site-packages\matplotlib\figure.py", line 1176, in colorbar
    cb = cbar.Colorbar(cax, mappable, **cb_kw)

  File "C:\Users\USER\anaconda3\lib\site-packages\matplotlib\colorbar.py", line 1171, in __init__
    if mappable.get_array() is not None:

AttributeError: 'NoneType' object has no attribute 'get_array'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 09:03:21