matplotlib [python] : help in explaining an animat

2019-09-11 08:42发布

问题:

Hello All and Merry Christmas,

Could someone please explain me how the following sample of code works (http://matplotlib.sourceforge.net/examples/animation/random_data.html) ?

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


timeline = [1,2,3,4,5,6,7,8,9,10] ;
metric = [10,20,30,40,50,60,70,80,90,100] ;

fig = plt.figure()
window = fig.add_subplot(111)
line, = window.plot(np.random.rand(10))

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=5*1000)
plt.show()

In particular, I would like to use lists ("metric") in order to update the list. Th problem is that FuncAnimation is using generators if I am not mistaken, but, how can I make it work ?

Thank you.

回答1:

You can feed FuncAnimation with any iterable not just a generator. From docs:

class matplotlib.animation.FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, **kwargs)

Makes an animation by repeatedly calling a function func, passing in (optional) arguments in fargs. frames can be a generator, an iterable, or a number of frames. init_func is a function used to draw a clear frame. If not given, the results of drawing from the first item in the frames sequence will be used.

Thus the equivalen code with lists could be:

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

start = [1, 0.18, 0.63, 0.29, 0.03, 0.24, 0.86, 0.07, 0.58, 0]

metric =[[0.03, 0.86, 0.65, 0.34, 0.34, 0.02, 0.22, 0.74, 0.66, 0.65],
         [0.43, 0.18, 0.63, 0.29, 0.03, 0.24, 0.86, 0.07, 0.58, 0.55],
         [0.66, 0.75, 0.01, 0.94, 0.72, 0.77, 0.20, 0.66, 0.81, 0.52]
        ]

fig = plt.figure()
window = fig.add_subplot(111)
line, = window.plot(start)

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

ani = animation.FuncAnimation(fig, update, metric, interval=2*1000)
plt.show()