If you plot multiple subplots, the plt.subplots()
returns the axes in an array, that array allows indexing like you do with ax[plot]
. When only 1 subplot is created, by default it returns the axes itself, not the axes within an array.
So your error occurs when len(channels)
equals 1. You can suppress this behavior by setting squeeze=False
in the .subplots()
command. This forces it to always return a 'Rows x Cols' sized array with the axes, even if its a single one.
So:
def plot(df):
channels=[]
for i in df:
channels.append(i)
fig, ax = plt.subplots(len(channels),1, sharex=True, figsize=(50,100), squeeze=False)
plot=0
for j in df:
ax[plot,0].plot(df["%s" % j])
ax[plot,0].set_xlabel('%s' % j)
plot=plot+1
plt.tight_layout()
plt.show()
By adding the squeeze
keyword you always get a 2D array in return, so the indexing for a subplot changes to ax[plot,0]
. I have also specifically added the amount of columns (1 in this case).