同一图中连续的Matplotlib动画

4

我有一个算法,由两个不同的部分组成,我想一个接一个地将它们可视化(同时可能在动画2开始时保留动画1的最终状态)。

我可以通过调用 animation.FuncAnimationplt.show() 来单独可视化这两个部分。由于两个部分都有固定的帧数和自己的行为,我想将它们的实现分别放在两个不同的类中,然后在它们周围做一个包装器,依次播放它们。

然而,是否可能在同一图中依次显示两个(或更多)动画对象?

非常感谢, 马特


1
是的,这是可能的。由于您知道第一个动画的帧数,我可以想象使用计时器来启动第二个动画会很好。也可以使用简单的包装类。如果您想提供问题的 [mcve],我们可以轻松地提供答案。 - ImportanceOfBeingErnest
1个回答

3

感谢ImportanceOfBeingErnest的提示,我想出了一种解决方案,根据当前时间步长仅更新我的动画状态中的某些元素。以下是一个小例子,说明这种方法:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from math import sin, radians


class AnimationHandler:
    def __init__(self, ax):

        self.ax = ax

        self.lines   = [self.ax.plot([], []), self.ax.plot([], [])]
        self.colors  = ['cyan', 'red']
        self.n_steps = [360, 360]
        self.step = 0

    def init_animation(self):
        for anim_idx in [0, 1]:
            self.lines[anim_idx], = self.ax.plot([0, 10], [0, 0], c=self.colors[anim_idx], linewidth=2)
        self.ax.set_ylim([-2, 2])
        self.ax.axis('off')

        return tuple(self.lines)

    def update_slope(self, step, anim_idx):
        self.lines[anim_idx].set_data([0, 10], [0, sin(radians(step))])

    def animate(self, step):
        # animation 1
        if 0 < step < self.n_steps[0]:
            self.update_slope(step, anim_idx=0)

        # animation 2
        if self.n_steps[0] < step < sum(self.n_steps):
            self.update_slope(step - self.n_steps[0], anim_idx=1)

        return tuple(self.lines)


if __name__ == '__main__':
    fig, axes = plt.subplots()
    animator = AnimationHandler(ax=axes)
    my_animation = animation.FuncAnimation(fig,
                                           animator.animate,
                                           frames=sum(animator.n_steps),
                                           interval=10,
                                           blit=True,
                                           init_func=animator.init_animation,
                                           repeat=False)

    Writer = animation.writers['ffmpeg']
    writer = Writer(fps=24, metadata=dict(artist='Me'), bitrate=1800)
    my_animation.save('./anim_test.mp4', writer=writer)

    plt.show()

enter image description here

我使用这种方法来可视化/调试一个运行时间不同的算法,方法是相同的:您知道每个子序列的步骤数并相应地调整状态。

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接