
在使用 matplotlib.pyplot 和 seaborn 进行数据可视化时,attributeerror: 'numpy.ndarray' object has no attribute 'bar' 是一个常见的错误,尤其是在创建包含多个子图的图形布局时。这个错误通常发生在尝试在一个 numpy.ndarray 类型的对象上调用绘图方法(如 bar、countplot 等)时,而这些方法实际上应该在 matplotlib.axes.axes 对象上调用。问题的根源在于对 plt.subplots 返回值的误解和不正确的解包操作。
plt.subplots 函数用于创建一个包含多个子图的图形。它的返回值是一个元组,通常包含两个元素:
关键在于 ax 的类型取决于你如何调用 plt.subplots:
fig, ax = plt.subplots() # ax 是一个 Axes 对象
fig, axes = plt.subplots(nrows=2, ncols=1) # axes 是一个包含两个 Axes 对象的 NumPy 数组 fig, axes = plt.subplots(nrows=1, ncols=2) # axes 是一个包含两个 Axes 对象的 NumPy 数组
fig, axes = plt.subplots(nrows=2, ncols=2) # axes 是一个 2x2 的 NumPy 数组
考虑以下导致 AttributeError 的代码片段:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
# 假设 dataset 是一个 DataFrame,包含 'class_label' 列
# 这里创建一个示例数据集
data = {'class_label': np.random.choice(['A', 'B', 'C', 'D'], 100)}
dataset = pd.DataFrame(data)
# 错误的代码示例
fig, (ax1) = plt.subplots(ncols=2, 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()在这个例子中,plt.subplots(ncols=2, ...) 明确要求创建两个列的子图。根据上面的解释,plt.subplots 会返回一个 fig 对象和一个包含两个 Axes 对象的 numpy.ndarray。然而,代码中使用了 fig, (ax1) = ... 这样的解包方式。这里的 (ax1) 仅仅是给变量 ax1 加上了括号,它并没有实现数组的解包。因此,ax1 变量实际上接收到的是整个 numpy.ndarray 对象,而不是第一个 Axes 对象。
当 sns.countplot 函数尝试在 ax=ax1 上绘图时,它会内部调用 ax1.bar 方法。但由于 ax1 是一个 numpy.ndarray 对象,它并没有 bar 这个方法,从而引发 AttributeError: 'numpy.ndarray' object has no attribute 'bar'。
要解决这个问题,关键在于正确地解包 plt.subplots 返回的 Axes 数组。当 ncols=2 时,你需要提供两个变量来接收这两个 Axes 对象。
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
# 假设 dataset 是一个 DataFrame,包含 'class_label' 列
data = {'class_label': np.random.choice(['A', 'B', 'C', 'D'], 100)}
dataset = pd.DataFrame(data)
# 正确的代码示例
# 当 ncols=2 时,需要解包为两个 Axes 对象,例如 (ax1, ax2)
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 是一个 Axes 对象,可以正确地传递给 seaborn
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="another_label", data=dataset, ax=ax2)
# ax2.set_title('Another Plot')
plt.tight_layout(rect=[0, 0.03, 1, 0.95]) # 调整布局以避免标题重叠
plt.show()通过将 fig, (ax1) 修改为 fig, (ax1, ax2),我们正确地将 plt.subplots 返回的 Axes 数组解包为两个独立的 Axes 对象 ax1 和 ax2。这样,ax1 就不再是 numpy.ndarray,而是真正的 matplotlib.axes.Axes 对象,其上所有绘图方法(如 bar)都可正常调用。
AttributeError: 'numpy.ndarray' object has no attribute 'bar' 错误通常源于对 matplotlib.pyplot.subplots 返回值(特别是 Axes 对象)的误解和不当解包。通过理解 plt.subplots 如何根据 nrows 和 ncols 参数返回单个 Axes 对象或 Axes 对象的 numpy.ndarray,并采用正确的解包或索引访问方式,可以有效地避免此类错误,确保绘图代码的顺利执行。始终记住,绘图函数如 sns.countplot 需要一个 matplotlib.axes.Axes 对象作为其 ax 参数。
以上就是Matplotlib subplots 轴对象解包错误解析与修正的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号