IndexError:for循环中数组的索引太多

时间:2018-02-20 05:25:21

标签: python numpy matplotlib

我创建了错误:IndexError:数组的索引太多了。因为我尝试在我的数组上执行for循环。我不知道为什么会出现这个错误。因为这个错误意味着我的数据不适合我的数组,但我的数组是否正确填充?

我的节目:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import matplotlib.dates as mdates
import numpy as np
from datetime import datetime
from dateutil.parser import parse
import time



style.use('fivethirtyeight')

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)


def animate(i):

    graph_data = open('Test.txt','r').read()
    lines = graph_data.split('\n')
    xs = []
    ys = []

    for line in lines:
        if len(line) > 1:
            x,y = line.split (',')
            xs.append(float(x))
            ys.append(float(y))


    ax1.clear()
    ax1.plot(xs,ys)

    gems = []
    gem = open ('Test1.txt','r').read()
    gem = float(gem)
    gems.append(float(gem))
    y = float(y)
    x = float(x)

    ax1.axhline(gem, color='k', linewidth=1)

    print (xs, ys)

    for i in range (len(xs)):
        num = i
        if ys[num] <= gem:
            ax1.fill_between(xs[num], gem, ys[num], facecolor='g', alpha=1)
        else:
            ax1.fill_between(xs[num], gem, ys[num], facecolor='r', alpha=1)

错误代码:

Traceback (most recent call last):
  File "C:\Users\Benjamin\Python37\lib\site-packages\matplotlib\cbook\__init__.py", line 388, in process
    proxy(*args, **kwargs)
  File "C:\Users\Benjamin\Python37\lib\site-packages\matplotlib\cbook\__init__.py", line 228, in __call__
    return mtd(*args, **kwargs)
  File "C:\Users\Benjamin\Python37\lib\site-packages\matplotlib\animation.py", line 1081, in _start
    self._init_draw()
  File "C:\Users\Benjamin\Python37\lib\site-packages\matplotlib\animation.py", line 1792, in _init_draw
    self._draw_frame(next(self.new_frame_seq()))
  File "C:\Users\Benjamin\Python37\lib\site-packages\matplotlib\animation.py", line 1814, in _draw_frame
    self._drawn_artists = self._func(framedata, *self._args)
  File "C:\Users\Benjamin\Python37\Test.py", line 49, in animate
    ax1.fill_between(xs[num], gem, ys[num], facecolor='g', alpha=1)
  File "C:\Users\Benjamin\Python37\lib\site-packages\matplotlib\__init__.py", line 1717, in inner
    return func(ax, *args, **kwargs)
  File "C:\Users\Benjamin\Python37\lib\site-packages\matplotlib\axes\_axes.py", line 4786, in fill_between
    for ind0, ind1 in mlab.contiguous_regions(where):
  File "C:\Users\Benjamin\Python37\lib\site-packages\matplotlib\mlab.py", line 3835, in contiguous_regions
    idx, = np.nonzero(mask[:-1] != mask[1:])
IndexError: too many indices for array
>>> 

当我尝试这个程序时,我没有错误,但它填满了整个x轴。 程序:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import matplotlib.dates as mdates
import numpy as np
from datetime import datetime
from dateutil.parser import parse
import time



style.use('fivethirtyeight')

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)


def animate(i):

    graph_data = open('Test.txt','r').read()
    lines = graph_data.split('\n')
    xs = []
    ys = []

    for line in lines:
        if len(line) > 1:
            x,y = line.split (',')
            xs.append(float(x))
            ys.append(float(y))


    ax1.clear()
    ax1.plot(xs,ys)

    gems = []
    gem = open ('Test1.txt','r').read()
    gem = float(gem)
    gems.append(float(gem))
    y = float(y)
    x = float(x)

    ax1.axhline(gem, color='k', linewidth=1)

    print (xs, ys)

    for i in range (len(xs)):
        num = i
        if ys[num] <= gem:
            ax1.fill_between(xs, gem, ys[num], facecolor='g', alpha=1)
        else:
            ax1.fill_between(xs, gem, ys[num], facecolor='r', alpha=1)

XS和YS:

[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0] [1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, 1.0, 0.0, -1.0, -1.0, 1.0]

最后你看到的颜色不是零。 The solution graph

1 个答案:

答案 0 :(得分:1)

如果你想填充,你需要提供两条曲线。例如,此代码将使用绿色

填充gem和ys之间的曲线
ax1.fill_between(xs, [gem] * len(xs), ys, facecolor='g', alpha=1)

您似乎希望用红色填充宝石阈值上方的部分,并以绿色填充宝石阈值以下。它是否正确?好吧,不幸的是,为了真正起作用,你需要宝石线和曲线的部分作为点数组的一部分(将这些点作为xs和ys的一部分)。这是因为fill_between仅使用实际传递给它的点。

以下代码将首先添加交点,然后将分离到宝石上方和下方的曲线进行着色

# Add intersection points
yys = [ys[0]]
xxs = [xs[0]]
for i in range(1, len(xs)):
    if (ys[i - 1] < gem and ys[i] > gem) or (ys[i - 1] > gem and ys[i] < gem):
        yys.append(gem)
        xxs.append(xs[i - 1] + (gem - ys[i - 1]) / (ys[i] - ys[i - 1]) \
                   * (xs[i] - xs[i - 1]))
    xxs.append(xs[i])
    yys.append(ys[i])

# Seperate to above and below gem curves
belowgem = [y if y <= gem else gem for y in yys]
abovegem = [y if y >= gem else gem for y in yys]

# fill between
ax1.fill_between(xxs, [gem] * len(xxs), belowgem, facecolor='g', alpha=1)
ax1.fill_between(xxs, [gem] * len(xxs), abovegem, facecolor='r', alpha=1)