如何在创建动画之前创建绘图?

时间:2016-06-09 14:23:46

标签: python animation matplotlib multiprocessing

我想使用多处理绘制数据,然后使用绘制的数据创建动画。我的意思是这样的:

frames = []

def get_frames()
        ...
        [index, frame] = mp_queue.get()
        frames[index]=frame

def get_frames_process(queue, index, x_vals, y_vals):
    frame = plt.scatter(x_vals[index], y_vals[index])
    queue.put([index, frame])

def animate(frame):
    frames.pop(0)
    plt.plot(frame)

anim = animation.FuncAnimation(fig, animate, frames=frames)

或者,还有一种使用FuncAnimation进行多处理的方法吗?

1 个答案:

答案 0 :(得分:1)

来自FuncAnimation documentation

  

frames可以是生成器,可迭代或多个帧。

我建议你编写一个生成器函数,它使用多处理来迭代你的帧计算。这是一个例子:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from multiprocessing import Pool

def calc_fib(n):
    if n in (0, 1):
        return 1
    return calc_fib(n-1) + calc_fib(n-2)

class FibonacciAnimation(object):
    def __init__(self, count):
        self.count = count
        self.line, = plt.plot([], [], 'r-')
        self.pool = Pool(8)

    def update(self, n):
        self.line.set_data(self.xs, self.ys)
        return self.line,

    def frames(self):
        for n in range(self.count):
            self.xs = range(n)
            self.ys = self.pool.map(calc_fib, self.xs)
            yield

fig = plt.figure()
fib = FibonacciAnimation(30)
plt.xlim(0, fib.count)
plt.ylim(0, 1000000)
plt.title('Fibonacci Animation')
fib_ani = animation.FuncAnimation(fig, fib.update, fib.frames,
                                  interval=50, blit=True)
plt.show()

我故意将Fibonacci计算效率低下,因此您可以将mapself.pool.map进行比较并查看多处理的效果。

相关问题