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

Python 如何在创建动画之前创建绘图?,python,animation,matplotlib,multiprocessing,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[in

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

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)
或者,还有一种方法可以将动画与多处理结合使用

来自:

frames
可以是生成器、iterable或多个帧

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

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()
我故意使斐波那契计算效率低下,因此您可以将
map
self.pool.map
进行比较,并查看多处理的效果