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

代码报错AttributeError:numpy.ndarray对象无bar属性,如何修复?

问题排查:seaborn countplot触发AttributeError: 'numpy.ndarray'对象没有'bar'属性

错误原因

当调用plt.subplots(ncols=2)时,函数会返回一个包含两个Axes绘图对象的numpy数组。但你用(ax1)的方式接收返回值,导致ax1实际指向的是这个数组,而非单个Axes实例。而seaborn的countplot要求传入单个Axes对象,传入数组自然会触发'numpy.ndarray' has no attribute 'bar'的错误。

另外原代码遗漏了matplotlib.pyplot的导入,运行时会先触发NameError,需要补上。

修复方案

提供两种修复方式,根据你的实际需求选择:

方式1:仅需单个子图

将ncols=2改为ncols=1,保持原接收逻辑:

import seaborn as sns
import matplotlib.pyplot as plt

fig, (ax1) = plt.subplots(ncols=1, figsize=(25, 7.5), dpi=100)
fig.suptitle(f'Counts of Observation Labels in ciciot_2023 ', fontsize=25)
sns.countplot(x="class_label", palette="OrRd_r", data=dataset, order=dataset['class_label'].value_counts().index, ax=ax1)

ax1.set_title('ciciot2023', fontsize=20)
ax1.set_xlabel('label', fontsize=15)
ax1.set_ylabel('count', fontsize=15)
ax1.tick_params(labelrotation=90)

plt.show()

方式2:需要两个子图

正确接收两个Axes对象,传入单个对象给countplot:

import seaborn as sns
import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(25, 7.5), dpi=100)
fig.suptitle(f'Counts of Observation Labels in ciciot_2023 ', fontsize=25)
# 使用ax1绘制第一个子图
sns.countplot(x="class_label", palette="OrRd_r", data=dataset, order=dataset['class_label'].value_counts().index, ax=ax1)

ax1.set_title('ciciot2023', fontsize=20)
ax1.set_xlabel('label', fontsize=15)
ax1.set_ylabel('count', fontsize=15)
ax1.tick_params(labelrotation=90)

# 可在ax2添加其他绘图逻辑,示例:
# sns.countplot(x="other_column", data=dataset, ax=ax2)

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 06:55:15