Skip to main content
 首页 » 编程设计

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

2025年04月02日14wayfarer

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

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 与多处理一起使用的方法吗?

请您参考如下方法:

来自FuncAnimation documentation :

frames can be a generator, an iterable, or a number of 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 计算效率低下,因此您可以比较 map 和 self.pool.map 并查看多处理的效果。