matplotlib subplots - IndexError: too many indices for array

我的梦境 提交于 2020-04-18 06:14:29

问题


I'm plotting 8 columns into one figure by using subplots function. However, it shows

"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()

回答1:


There are two problems with your code:

  • First, you are defining the subplots() inside the for loop which is wrong. You should define it just once outside.
  • Second, you need to use axes[num] instead of axes[num, 0] to refer to a particular subplot since you are having only a single column which is why you get the > IndexError. The indexing axes[num, 0], axes[num, 1] etc. will work if you have more than 1 column.

Solution

# 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()

Alternative using enumerate getting rid of num variable

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()


来源:https://stackoverflow.com/questions/54170394/matplotlib-subplots-indexerror-too-many-indices-for-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!