问题
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 ofaxes[num, 0]
to refer to a particular subplot since you are having only a single column which is why you get the> IndexError
. The indexingaxes[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