调用seaborn.heatmap()遇AttributeError: 'NoneType'无canvas属性问题
AttributeError: 'NoneType' object has no attribute 'canvas'(Colab中调用seaborn.heatmap()时的问题)
在Google Colab的Jupyter Notebook中执行Python代码调用seaborn.heatmap()绘制混淆矩阵时,触发AttributeError,提示'NoneType' object has no attribute 'canvas'。相同代码在Intellij IDEA中可正常运行,且两端使用的matplotlib(3.5.2)和seaborn(0.11.2)版本完全一致。
报错代码
ax = sns.heatmap(conf_matrices[j], annot=True, cmap='Blues')
完整报错栈
Traceback (most recent call last): File "/content/IMUSensorsRecognizer/source-files/Main.py", line 334, in <module> show_and_save_images(save, scores, confusion_matrices, params, test_sizes, File "/content/IMUSensorsRecognizer/source-files/Main.py", line 93, in show_and_save_images ax = sns.heatmap(conf_matrices[j], annot=True, cmap='Blues') File "/usr/local/envs/py39/lib/python3.9/site-packages/seaborn/_decorators.py", line 46, in inner_f return f(**kwargs) File "/usr/local/envs/py39/lib/python3.9/site-packages/seaborn/matrix.py", line 550, in heatmap ax = plt.gca() File "/usr/local/envs/py39/lib/python3.9/site-packages/matplotlib/pyplot.py", line 2274, in gca return gcf().gca(**kwargs) File "/usr/local/envs/py39/lib/python3.9/site-packages/matplotlib/pyplot.py", line 867, in gcf return figure() File "/usr/local/envs/py39/lib/python3.9/site-packages/matplotlib/pyplot.py", line 812, in figure fig = manager.canvas.figure AttributeError: 'NoneType' object has no attribute 'canvas'
混淆矩阵示例
conf_matrices[j]的结构示例(由sklearn的confusion_matrix累加生成):
[[3091 2152 581 70 276] [1741 3454 491 122 255] [ 721 716 4330 60 382] [ 231 344 261 3198 281] [ 878 429 539 67 1131]]
运行代码的Notebook Cell
%%bash ls source activate py39 python --version cd ~/../content/IMUSensorsRecognizer pip install -r requirements.txt pip install ipykernel cd source-files ls python Main.py rf 50 0.75 1 5 4 7 24 t f
排查过程与结论
- 尝试断开重连Colab会话、删除重新挂载数据,问题仍存在
- 更换Colab分配的机器后,问题完全解决
推测该问题是Colab分配的特定机器存在matplotlib后端环境异常,导致无法正常创建绘图上下文(figure/manager)。
临时规避方案
如果再次遇到同类问题,可尝试以下两种方法:
手动创建绘图对象并传入heatmap
显式创建figure和axes,避免依赖plt.gca()自动获取上下文:import matplotlib.pyplot as plt # 显式创建figure和axes fig, ax = plt.subplots(figsize=(8, 6)) # 将ax传入heatmap sns.heatmap(conf_matrices[j], annot=True, cmap='Blues', ax=ax)强制指定matplotlib后端
在代码开头添加以下配置,指定稳定的绘图后端:import matplotlib # 针对Colab使用inline后端,或用'Agg'作为无界面后端 matplotlib.use('inline')
内容的提问来源于stack exchange,提问作者Federico Locatelli
相关产品推荐
相关产品推荐

