1

Hi guys Im quite a newbie in python/matplotlib.

I am struggling to understand the following animation code on the matplotlib website. How is the data argument in the def update defined if this function is called in animation.FuncAnimation whithout specifying any data as input parameter?

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

fig, ax = plt.subplots()
line, = ax.plot(np.random.rand(10))
ax.set_ylim(0, 1)


def update(data):
    line.set_ydata(data)
    return line,


def data_gen():
    while True:
        yield np.random.rand(10)

ani = animation.FuncAnimation(fig, update, data_gen, interval=100)
plt.show()

1 Answers1

1

data_gen is a generator which, for each animation frame, will yield an array of 10 random values. The array returned from data_gen is what is passed to your update function as the first input argument.

If you called FuncAnimation using the fargs kwarg, you could also pass additional inputs to the update function.

def update(data, scale):
    line.set_ydata(scale * data)
    return line

animation.FuncAnimation(fig, update, data_gen, fargs=(100,), interval=100)
Suever
  • 64,497
  • 14
  • 82
  • 101
  • Thanks Suever, I was wondering... is there a way to generate animation in much easier way? Like in GNU octave when you just do consecutive calls to plot(x,y)? –  Jul 22 '16 at 16:58
  • @PintoDoido Yes you can. [here is a post](http://stackoverflow.com/questions/4098131/how-to-update-a-plot-in-matplotlib) with some ways to accomplish that – Suever Jul 22 '16 at 17:17