0

This program is very simple, but I do not know why I get this error:

IndexError: too many indices for array

The error is caught for df1 (doesn't even go to df2). Can someone explain why I get this error? I think the bigger question is what's the logic for having a 2 by 1 subplot that I am not understanding.

Here is the program:

import pandas as pd
import matplotlib.pyplot as plt

x = range(5)
y = range(0,10,2)

w = x
z = y

df1 = pd.DataFrame(data = {'col1':x,'col2':y})
df2 = pd.DataFrame(data = {'col1':w,'col2':z})

fig, axes = plt.subplots(2,1)
df1.plot(ax=axes[0,0])
df2.plot(ax=axes[1,0])
Sheldore
  • 37,862
  • 7
  • 57
  • 71
dayxx369
  • 332
  • 4
  • 9

1 Answers1

1

You need to specify the correct indices. Since you are using plt.subplots(2,1), the axes object has length of 2 where the first and the second subplots are accessed using indices [0] and [1] respectively. If you do print (axes.shape), you will get (2,) so you have no second index. For plt.subplots(2,2), the print (axes.shape) would give (2,2) where you can use the double indices.

You can use axes[0, 0], axes[1, 0], axes[0, 1], axes[1, 1] and so on when you have more than 1 column. For a single column, axes[0, 0] has to be replaced by ax[0] and axes[1, 0] has to be replaced by ax[1].

fig, axes = plt.subplots(2,1)
print (len(axes))
# 2

df1.plot(ax = axes[0])
df2.plot(ax = axes[1])

Alternative approach would be

axes[0].plot(df1)
axes[1].plot(df2)

enter image description here

Your way works for a 2 by 2 subplots

fig, axes = plt.subplots(2,2)
print (axes.shape)
# (2, 2)

df1.plot(ax = axes[0,0])
df2.plot(ax = axes[0,1])
df1.plot(ax = axes[1,0])
df2.plot(ax = axes[1,1])

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71