代码报错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
相关产品推荐
相关产品推荐

