报错信息:IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed
- subplots(9, 1)时返回axs是(9,),使用axs[i], subplots(9, 2)才使用axs[i, j]
当你使用 fig, axs = plt.subplots(9, 1) 时,axs 是一个包含 9 个 AxesSubplot 对象的一维数组。此时 axs 的形状是 (9,),表示有 9 个子图,每个子图在数组中的一个位置。要访问这些子图中的某一个,只需要一个索引,而不是两个。
例如,axs[0]、axs[1] 等是单个子图的对象。而当 axs 是一个二维数组时,比如 fig, axs = plt.subplots(2, 3),axs 的形状为 (2, 3),此时你可以用两个索引来访问特定的子图,比如 axs[0, 1]。
因此,如果你在 fig, axs = plt.subplots(9, 1) 中尝试使用 axs[i, j] 的方式来访问子图,会导致 IndexError 错误,因为 axs 是一维的。
解决方案:
你应该使用一维索引来访问子图。以下是如何正确地访问这些子图的代码示例:
import matplotlib.pyplot as plt
import numpy as np
# 示例数据
combined_array = np.random.rand(100, 9) # 100 行,9 列
# 创建 9 行 1 列的子图
fig, axs = plt.subplots(9, 1, figsize=(10, 15))
# 遍历每个子图位置
for i in range(9):
axs[i].plot(combined_array[:, i], label=f'Feature {i + 1}')
axs[i].legend()
plt.tight_layout()
plt.show()
代码解释:
- 创建示例数据:
combined_array是一个形状为(100, 9)的 2 维数组,每一列代表一个特征。
- 创建子图:
fig, axs = plt.subplots(9, 1, figsize=(10, 15))创建了 9 个子图,排列成一列。此时axs是一个包含 9 个元素的 1 维数组,每个元素是一个子图对象。
- 绘图:
- 使用
for i in range(9)遍历每个子图。 axs[i].plot(combined_array[:, i], label=f'Feature {i + 1}')在每个子图中绘制combined_array的第i列。axs[i].legend()为每个子图添加图例。
- 使用
通过这种方式,你可以确保每个子图都正确绘制并显示相应的数据。如果你的子图数量和列数不对称,可以适当地调整 figsize 以保持图形的布局清晰。