matplotlib subplots - IndexError: too many indices for array

matplotlib subplots - IndexError: too many indices for array

我正在使用 subplots 函数将 8 列绘制成一张图。但是,它显示

"IndexError: too many indices for array"

# -*- coding: utf-8 -*-
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib import style

df = pd.read_csv('XXXX', encoding='utf-8')

num = 0

for dim in ['A','B','C','D','E','F','G','H']:
    fig, axes = plt.subplots(nrows=8, ncols=1)
    df[dim].plot(ax=axes[num,0])
    plt.xlabel(dim)
    num += 1

plt.show()

您的代码有两个问题:

  • 首先,您在 for 循环中定义 subplots() 是错误的。你应该只在外面定义一次。
  • 其次,您需要使用 axes[num] 而不是 axes[num, 0] 来引用特定的子图,因为您只有一个列,这就是为什么您得到 > IndexError 的原因。如果您有超过 1 列,索引 axes[num, 0]axes[num, 1] 等将起作用。

解决方案

# import commands here 

df = pd.read_csv('XXXX', encoding='utf-8')
num = 0

fig, axes = plt.subplots(nrows=8, ncols=1) # <---moved outside for loop

for dim in ['A','B','C','D','E','F','G','H']:
    df[dim].plot(ax=axes[num])
    plt.xlabel(dim)
    num += 1
plt.show()

替代方法使用 enumerate 摆脱 num 变量

fig, axes = plt.subplots(nrows=8, ncols=1)

for i, dim in enumerate(['A','B','C','D','E','F','G','H']):
    df[dim].plot(ax=axes[i])
    plt.xlabel(dim)
plt.show()