matplotlib animation: datas appears on the plot at the beginning

Viewed 45

I am trying to calculate one of the basic decay simulation and plot the results as animation. Without animation results fine but when i try to create animation both line appears fully developed at the first time step. The change over time is not as it should be. What am I doing wrong? I'm open to suggestions.

Original plot: plot

Here the code:

# I135 Xe135 decay.
"""
    EQUATIONS:
    dIdt  = (-Lambda_I * N_I)
    dXedt = ((-Lambda_Xe * N_Xe) + (Lambda_I * N_I))
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy.integrate import odeint

def model(z,t):
    """
     INITIAL CONDITIONS:
     I(0)  = 1e8 atoms
     Xe(0) = 0 atom

     PARAMETERS:
     Lambda_I
     Lambda_Xe
    """
    Lambda_I   = (np.log(2) / 6.57)
    Lambda_Xe  = (np.log(2) / 9.2)
    N_I  = z[0]
    N_Xe = z[1]
    dIdt  = (-Lambda_I * N_I)
    dXedt = ((-Lambda_Xe * N_Xe) + (Lambda_I * N_I))
    return [dIdt,dXedt]

z0 = [1e8, 0.0] # initial conditions for N_Xe and N_I
n  = 10000
max_time = 100
t  = np.linspace(0,max_time,n)
N_I  = np.zeros(n)
N_Xe = np.zeros(n)

# Solution
for i in range(n):
    z  = odeint(model,z0,t)
    z0 = z[1]
    N_I[i]  = z0[0]
    N_Xe[i] = z0[1]

# Graph and animation
fig, ax = plt.subplots(figsize=(8,8))
ax.set_ylim(0, 1e8)
ax.set_xlim(0, max_time)
line1, = ax.plot(N_I, 'b-',  linewidth=2)
line2, = ax.plot(N_Xe,'g-.', linewidth=2)
plt.rcParams['font.size'] = '14'
plt.minorticks_on()
plt.tick_params(axis="both", which="major", length=12, labelsize=12, width=1, color="black")
plt.tick_params(axis="both", which="minor", length=6, labelsize=10, width=0.8, color="black")
plt.title('I-135 Xe-135 Decay Sim.', fontsize=18)
plt.xlabel('Time (h)', fontsize=16)
plt.ylabel('N', fontsize=16)
plt.legend(['I-135','Xe-135'],prop={'size': 12})
plt.grid(color = 'black', linestyle = '--', linewidth = 0.6)

def animate(j):
    line1.set_xdata(np.linspace(0,j,n))
    line2.set_xdata(np.linspace(0,j,n))
    return [line1,line2,]
ani = animation.FuncAnimation(fig, animate, frames=max_time, blit=True, interval=10, save_count=10)
plt.show()

f = r"C://Users/USER_NAME/Desktop/animation.gif" 
writergif = animation.PillowWriter(fps=30) 
ani.save(f, writer=writergif)
0 Answers
Related