Problem with animation saving in an awkward manner

Viewed 41

I want to save a sequence of plots generated by matplotlib as an animation. Here's the code I'm running:

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

M = 100 # Número de walkers
L = 100 # Tamanho da malha

# A cada intervalo de tempo, mover o walker e propagar a difusão

p = 0.1 # Probabilidade de andar
pinv = 1.0-p
nsteps = 3001 # Número de intervalos de tempo

# Iniciando os walkers

x = np.zeros(M) # Posição inicial dos walkers
edges = np.array(range(-L,L+1))-0.5
xc = 0.5*(edges[:-1]+edges[1:])

#  Iniciando as concentrações

c = np.zeros((2*L+1,2))
i0 = 0
i1 = 1
c[L] = M # c[L] corresponde a x = 0
cx = range(-L,L+1)
D = p

#%%
plt.ion()
noutput = 100
fig, ax = plt.subplots()

def animate(i):
    global x
   
    for it in range(nsteps):
        # Atualizar a posição de todos os walkers
        for iw in range(M):
            rnd = np.random.rand(1)
            dx = -1*(rnd<p)+1*(rnd>pinv)
            x[iw] = x[iw] + dx
            
        # Trajetória dos walkers no eixo x
        if (np.mod(it,noutput)==0):
            y = np.zeros(M)
            
            ax.scatter(x, y, s = 1)
            fig.set_size_inches(10, 2, True)
            ax.set_xlim((-100, 100))
            ax.axes.get_yaxis().set_visible(False)
            ax.set_title('Tempo:{}'.format(it))
            ax.set_xlabel('Distância percorrida')

ani = animation.FuncAnimation(fig, animate, nsteps)
ani.save('randomwalk1d.gif')
plt.show()

I expected to have blue dots moving over the x axis as the individual plots show, but I'm getting a weird result and I don't know what I'm doing wrong:

.gif generated by the code

0 Answers
Related