0

I currently have a simulation process that outputs a data point on each iteration. I would like to animate this with matplotlib, but am unsure if possible with matplotlib.animation.

Many online tutorials/examples I have come across always start with a list of predefined points, e.g. x = [1,2,3,4,5], y=[5.5,3.6,7.1,2.2,3.3], and essentially animate this list. Technically this also works for me, but I will have to first run the simulation and append the results into lists x and y, and then run the animation process on these lists (which would require iterating through the lists again, which is pointless as ideally it should be animating alongside the simulation phase.) This will be cumbersome if I run the simulation with millions of iterations.

I was wondering if mpl.animation can animate data as it comes, e.g. start with x=[], y=[], then on first iteration we get x=[0.1], y=[3.3] and we animate this, and then on second iteration we get x=[0.1,0.52], y=[3.3,4.4] and we animate again, and so on, rather than requiring the entire list to be populated first before animating.

1 Answer 1

2

Why not just try it?

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation


fig = plt.figure()
pltdata, = plt.plot([], [])
plt.ylim(-1.1,1.1)
plt.xlim(0,200)

def animate(i):
    x=np.arange(i, i*2+2)
    y=np.sin(x*0.1)
    pltdata.set_data(x, y)
    return [pltdata]

theAnim = animation.FuncAnimation(fig, animate, frames=100, interval=100, blit=True, repeat=False)
plt.show()

As you can see, it is not a predefined list (it could have been for this example, but it is not. First plot is with constant [] list. And then x and y are recomputed from scratch at each animate call).

And works as intended. (As always with animation, one must take care of xlim and ylim, because if they are chosen automatically, since there is no data at the beginning, they won't fit the future, yet unknown, data).

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

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.