matplotlib子图-IndexError:数组的索引过多 [英] matplotlib subplots - IndexError: too many indices for array
本文介绍了matplotlib子图-IndexError:数组的索引过多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 subplots
函数将8列绘制到一个图形中.但是,它显示
I'm plotting 8 columns into one figure by using subplots
function. However, it shows
"IndexError:数组的索引过多"
"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()
推荐答案
你的代码有两个问题:
- 首先,您要在for循环中定义
subplots()
,这是错误的.你应该只在外面定义一次. - 第二,您需要使用
axes [num]
而不是axes [num,0]
来引用特定的子图,因为您只有一列,这就是为什么你得到>IndexError
.如果您有多于1列,则索引axes [num,0]
,axes [num,1]
等将起作用.
- 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.
解决方案
# 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()
<小时>
替代使用 enumerate
摆脱 num
变量
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()
这篇关于matplotlib子图-IndexError:数组的索引过多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文