如何同时为多个图形制作动画

时间:2019-01-04 20:59:07

标签: python-3.x matplotlib animation

我制作了一个用于排序算法的动画,它非常适合用于动画一个排序算法,但是当我尝试同时对多个动画进行动画处理时,两个窗口都出现了,但是它们都没有移动。我想知道如何解决这个问题。

运行代码时,第一个图形停留在第一帧上,第二个图形跳跃到最后一帧

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

1 个答案:

答案 0 :(得分:1)

the documentation中有关animation模块的说明:

  

保留对实例对象的引用至关重要。的   动画由计时器推进(通常从主机GUI进行)   框架),Animation对象拥有唯一的引用。如果   您没有保存对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()