0

As stated above, I am trying to animate a set of data that varies over time (position). I would like my graph to only show the position data but animate the position history over time. I have started with this example here, and got it working. Now, instead of the whole line animating, I would like for the line to be drawn from left to right. I also need the line to be colored relative to a secondary set of data, which I have been able to accomplish with a LineCollection.

My code:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))

line = LineCollection([], cmap=plt.cm.jet)
line.set_array(np.linspace(0, 2, 1000))
ax.add_collection(line)

x = np.linspace(0, 2, 10000)
y = np.sin(2 * np.pi * (x))

# initialization function: plot the background of each frame
def init():
    line.set_segments([])
    return line,

# animation function.  This is called sequentially
def animate(i, xss, yss, line):
    xs = xss[:i]
    ys = yss[:i]
    points = np.array([xs, ys]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    line.set_segments(segments)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, fargs=[x, y, line], init_func=init, frames=200, interval=20)
plt.show()

I create a basic sine wave data set and again would like to animate the line being drawn from left to right. Right now, the LineCollection is being colored by the y-value of the line at the current x-position. Eventually, this will be a position data set pulled from a .csv file.

Finally, the issue. The code above runs without errors, however the line is not being drawn. I can see in my debugger that the xs and ys arrays are being added to during each step so that syntax seems to be working, just the updated LineCollection is not being displayed.

I am working on macOS Mojave 10.14.6.

1 Answers1

0

Your code is correct, the line you're plotting is just very small. This is because the function you animate is given by

x = np.linspace(0, 2, 10000)  # Note that `num=10000`
y = np.sin(2 * np.pi * (x))

which has 10000 points, but you only animate the first 200 points.

anim = animation.FuncAnimation(..., frames=200, interval=20)

Easy fix

num_frames = 200
x = np.linspace(0, 2, num_frames)
...
anim = animation.FuncAnimation(..., frames=num_frames, interval=20)
Emerson Harkin
  • 889
  • 5
  • 13
  • Yep that was it. I also realized that i could see the line at 200 frames, but it was animating much slower than I thought it would so I wasn't even waiting long enough for it to really animate anything. Thanks! – collin1021 Jul 14 '20 at 18:38