'FuncAnimation only draw last frame

I've been trying some sand simulation animation. I've been trying to make a video or a gif of it. Unfortunately, the gif contains only the last frame and I don't understand why.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from matplotlib.backend_bases import MouseButton
from matplotlib.animation import FuncAnimation


mat_colors = ['#ffffff', '#c2b280', '#aaaaaa', '#7777aa', '#774411', '#ee3333', '#999999', '#44bb44']
cmap = ListedColormap(mat_colors)


fig, axs = plt.subplots()

pixels = np.zeros((40,80), dtype=int)

cax = axs.matshow(pixels,cmap=cmap)
h_pixmap = axs.matshow(pixels, cmap=cmap, vmin=0, vmax=len(mat_colors)-1)



position_sand = []

def Sand(col,lign):
    pixels[int(lign),int(col)] = 1
    position_sand.append([int(lign),int(col)])

def update_uni(n=0):
    h_pixmap.set_data(pixels)

def cb_click(event):
    if (event.button == MouseButton.LEFT):
        Sand(event.xdata,event.ydata)
    
fig.canvas.mpl_connect('button_press_event', cb_click)

while plt.fignum_exists(fig.number):   
  
    for k in range(len(position_sand)):
        i = position_sand[k][0]
        j = position_sand[k][1]        
        if (i<39 and i>0 and j<79 and j>0):
            if pixels[i+1,j] == 0:
                pixels[i+1,j] = 1
                pixels[i,j] = 0
                position_sand[k][0]+=1               
            elif ( pixels[i+1,j-1] == 0):
                pixels[i+1,j-1] = 1
                pixels[i,j] = 0
                position_sand[k][0]+=1
                position_sand[k][1]-=1            
            elif ( pixels[i+1,j+1] == 0):
                pixels[i+1,j+1] = 1
                pixels[i,j] = 0
                position_sand[k][0]+=1
                position_sand[k][1]+=1                
            
    update_uni()
    plt.draw(), plt.pause(0.3)
        


ani = FuncAnimation(fig, update_uni, init_func=None, interval=0.001)
ani.save('animation.gif', writer=' Pillow')

plt.show()

I saved each pixel matrix in a list 'video' and tried to redo the animation but it still doesn't work.

def update_uni2(i):
    h_pixmap.set_data(video[i])


ani = FuncAnimation(fig, update_uni2,frames=len(video), init_func=None, interval=0.01)
ani.save('animation.gif', writer='Pillow')

Could someone help me please :)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source