0

I create the error: IndexError: too many indices for array. Because I try to do a for loop on my arrays. I don't know why i get this error. Because this error means my data don't fit in my array, but my arrays are filled in correctly?

my program:

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)

Error code:

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
>>> 

When i try this program i don't have an error but it fill trough the whole x-axis. program:

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 and 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]

On the end you see the colors when its not zero.. The solution graph

10
  • What specifically does the error say? Paste it into your question. Commented Feb 20, 2018 at 5:26
  • I have add it in my question Commented Feb 20, 2018 at 5:29
  • It is something on the end of my program with xs[num] but I don't see the fault Commented Feb 20, 2018 at 5:30
  • Why on earth do you re-read your text files every animation step? Commented Feb 20, 2018 at 6:33
  • when there are new data in the files I have the show them to.. Commented Feb 20, 2018 at 6:48

1 Answer 1

1

If you want to fill_between you need to provide two curves. This code, for example, will fill the curves between gem and ys with green

ax1.fill_between(xs, [gem] * len(xs), ys, facecolor='g', alpha=1)

You seem to want to fill the parts above the gem threshold with red and below the gem threshold in green. Is this correct? Well, unfortunately for that to really work you need the intesection of the gem line and the curve to be part of the points array (have these points as part of xs and ys). That is because fill_between uses only the points that are actually passed to it.

The following code will first add intersection points, and then will seperate to curves above and below gem for the colorization

# 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)
Sign up to request clarification or add additional context in comments.

3 Comments

Yes you have it correct. But when the intersections are not part of the curve? Now it's okay but by example i have a gem = 0 but if the data are not zero it's creating weird stuff. see question
As I said, then you need to work harder. Maybe weite some code to find the intersections points and add them to the arrays
Added a simple way to do it to the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.