我有一个算法,由两个不同的部分组成,我想一个接一个地将它们可视化(同时可能在动画2开始时保留动画1的最终状态)。
我可以通过调用 animation.FuncAnimation
和 plt.show()
来单独可视化这两个部分。由于两个部分都有固定的帧数和自己的行为,我想将它们的实现分别放在两个不同的类中,然后在它们周围做一个包装器,依次播放它们。
然而,是否可能在同一图中依次显示两个(或更多)动画对象?
非常感谢, 马特
我有一个算法,由两个不同的部分组成,我想一个接一个地将它们可视化(同时可能在动画2开始时保留动画1的最终状态)。
我可以通过调用 animation.FuncAnimation
和 plt.show()
来单独可视化这两个部分。由于两个部分都有固定的帧数和自己的行为,我想将它们的实现分别放在两个不同的类中,然后在它们周围做一个包装器,依次播放它们。
然而,是否可能在同一图中依次显示两个(或更多)动画对象?
非常感谢, 马特
感谢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()
我使用这种方法来可视化/调试一个运行时间不同的算法,方法是相同的:您知道每个子序列的步骤数并相应地调整状态。