【问题标题】:How to animate multiple figures at the same time如何同时为多个人物设置动画
【发布时间】:2019-01-04 20:59:06
【问题描述】:

我为排序算法制作了动画,它非常适合为一种排序算法制作动画,但是当我尝试同时为多个排序算法制作动画时,两个窗口都会出现,但它们都没有移动。我想知道我该如何解决这个问题。

当我运行代码时,第一个图卡在第一帧,第二个图跳到最后一帧

import matplotlib.pyplot as plt
from matplotlib import animation
import random
# my class for getting data from sorting algorithms
from animationSorters import * 


def sort_anim(samp_size=100, types=['bubblesort', 'quicksort']):

    rndList = random.sample(range(1, samp_size+1), samp_size)
    anim = []
    for k in range(0, len(types)):

        sort_type = types[k]
        animation_speed = 1

        def barlist(x):
            if sort_type == 'bubblesort':
                l = bubblesort_swaps(x)#returns bubble sort data
            elif sort_type == 'quicksort':
                l = quicksort_swaps(x)#returns quick sort data

            final = splitSwaps(l, len(x)) 
            return final

        fin = barlist(rndList)

        fig = plt.figure(k+1)
        plt.rcParams['axes.facecolor'] = 'black'

        n= len(fin)#Number of frames
        x=range(1,len(rndList)+1)
        barcollection = plt.bar(x,fin[0], color='w')

        anim_title = sort_type.title() + '\nSize: ' + str(samp_size)
        plt.title(anim_title)

        def animate(i):
            y=fin[i]
            for i, b in enumerate(barcollection):
                b.set_height(y[i])


        anim.append(animation.FuncAnimation(fig,animate, repeat=False, 
                    blit=False, frames=n, interval=animation_speed))

    plt.show()

sort_anim()

【问题讨论】:

标签: python-3.x matplotlib animation


【解决方案1】:

正如the documentation 中对animation 模块的解释:

保持对实例对象的引用至关重要。这 动画由计时器推进(通常来自主机 GUI 框架),动画对象持有唯一的引用。如果 您没有对 Animation 对象的引用,它(因此 计时器),将被垃圾收集,这将停止动画。

因此,您需要从函数中返回对动画的引用,否则这些对象会在退出函数时被销毁。

考虑对您的代码进行以下简化:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np


def my_func(nfigs=2):
    anims = []
    for i in range(nfigs):
        fig = plt.figure(num=i)
        ax = fig.add_subplot(111)
        col = ax.bar(x=range(10), height=np.zeros((10,)))
        ax.set_ylim([0, 1])

        def animate(k, bars):
            new_data = np.random.random(size=(10,))
            for j, b in enumerate(bars):
                b.set_height(new_data[j])
            return bars,

        ani = animation.FuncAnimation(fig, animate, fargs=(col, ), frames=100)
        anims.append(ani)

    return anims


my_anims = my_func(3)
# calling simply my_func() here would not work, you need to keep the returned
# array in memory for the animations to stay alive
plt.show()

【讨论】:

  • 我最初尝试过,但它仍然给了我我的问题,这就是为什么我尝试将 plt.show() 放在函数内。我正在玩它,我在创建第二个图形和动画开始播放之间放置了一个pause,直到暂停结束。知道这是为什么吗?
  • 我通过将其修改为一次仅返回一个动画来使其工作,然后将每个人添加到具有单独功能的列表中。现在完美运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多