连续matplotlib动画在同一图中 [英] Consecutive matplotlib animation in same figure

查看:88
本文介绍了连续matplotlib动画在同一图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个算法,该算法由两个不同的部分组成,我希望一个接一个地可视化(同时可能在动画2开始时将动画1的最终状态保持在屏幕上)。

I have an algorithm which consists of two distinct parts which I want to visualize one after another (while possibly keeping the final state of animation 1 on the screen when animation 2 starts).

我可以通过调用 animation.FuncAnimation plt.show()来分别可视化这两个部分。由于这两个部分都有设定的帧数和它们自己的行为,因此我想将它们的实现分为两个不同的类,然后对它们进行包装,以按顺序播放它们。

I can visualize both parts individually by calling animation.FuncAnimation and plt.show(). Since both parts have set number of frames and their very own behaviour, I would like to keep their implementations apart in two different classes and then do a wrapper around them which plays them in sequence.

但是,是否有可能在同一幅图中一个接一个地显示两个(或更多)动画对象?

However, is it possible to have two (or more) animation objects to be displayed one after another in the same figure?

非常感谢,
Matt

Many thanks, Matt

推荐答案

多亏了ImportanceOfBeingErnest的提示,我提出了一个解决方案,该解决方案仅根据动画师状态的某些元素来更新在当前时间步。这是一个说明此方法的小示例:

Thanks to the hint of ImportanceOfBeingErnest, I came up with a solution which updates only certain elements of my animator state depending on the current time step. Here is a small example illustrating this approach:

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()

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

I used this approach to visualize/debug an algorithm which has different elements with varying runtimes. Approach is the same: You know the number of steps of each subsequence and adjust the state accordingly.

这篇关于连续matplotlib动画在同一图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆