0

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
  • Could you show df.head() in your question, so we have a minimal, complete and verifibiable example? Commented Jan 13, 2019 at 15:40

1 Answer 1

7

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.