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

使用seaborn绘制热力图保存时出现AxesSubplot不可解包错误如何解决

报错根因

你遇到的TypeError: cannot unpack non-iterable AxesSubplot object报错来自这行代码:

fig, ax= plt.subplot()

plt.subplot() 方法的返回值只有单个坐标轴对象(AxesSubplot),不是可以解包的二元组,所以无法同时赋值给fig、ax两个变量。

解决方法

有两种可行修改方案,选其中一种即可:

方案1(推荐):将plt.subplot()替换为plt.subplots()

plt.subplots()方法会返回「画布对象、坐标轴对象」组成的二元组,完美匹配你后续的代码逻辑,修改后其他代码不需要调整:

filename = 'Results/confusion_matrix_'+model_name+'.png'
cm = confusion_matrix(labels_test_true, labels_test_pred[0,:])
# 只改这一行,把subplot改成subplots即可
fig, ax= plt.subplots()
sns.heatmap(cm, annot=True, fmt='g', ax=ax);
# labels, title and ticks
ax.set_xlabel('Predicted labels');ax.set_ylabel('True labels'); 
ax.set_title('Confusion Matrix'); 
ax.xaxis.set_ticklabels(['normal', 'anomaly']); ax.yaxis.set_ticklabels(['anomaly', 'normal']);
fig.savefig(filename)

方案2:修改变量接收逻辑,保留plt.subplot()

如果你不想修改subplot调用,就调整变量接收和保存的逻辑:

filename = 'Results/confusion_matrix_'+model_name+'.png'
cm = confusion_matrix(labels_test_true, labels_test_pred[0,:])
# 只接收ax对象
ax = plt.subplot()
sns.heatmap(cm, annot=True, fmt='g', ax=ax);
# labels, title and ticks
ax.set_xlabel('Predicted labels');ax.set_ylabel('True labels'); 
ax.set_title('Confusion Matrix'); 
ax.xaxis.set_ticklabels(['normal', 'anomaly']); ax.yaxis.set_ticklabels(['anomaly', 'normal']);
# 通过ax获取关联的画布对象再保存
ax.figure.savefig(filename)

额外注意

如果你的代码后续添加了plt.show()调用,需要把savefig的逻辑放在plt.show()之前,否则保存的图片会是空白的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 15:24:00