yassineCAE
yassineCAE

Reputation: 27

Animating two curves in the same plot at the same time in Matplotlib

I am trying to animate two Gaussian profiles so they can progress simultaneously at the same speed, the exact solution will keep its original profile while the calculated solution will diffuse with time.

I made all the calculations but i could not animate the two curves so they can progress together on the same plot.

import numpy as np 
import pandas as pd
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.animation as animation
%matplotlib notebook

xmin = 0        # minimum value of x 
xmax = 2        # maximum value of x
N = 200         # Number of nodes  
dt = 0.005      # time step
tmax = 2      # solution time
v = 0.5           # velocity
t0 = 0

# Discritize the domain 
dx = (xmax - xmin)/N
x = np.arange(xmin-dx,xmax+dx,dx)
# set initial condition 
u0 = np.exp(-200*np.square(x-0.25))

u = u0.copy()
unp1 = u0.copy()
unpf = []
uexact = []
t = np.arange(t0, tmax, dt)
#Newman boundary condition no gradient across the boundary 
u[0]= u[2]
u[-1]= u[N-1]
#Loop through time
nsteps = int(tmax/dt)
for n in range (0,nsteps):    
    #Calculate the FOU scheme
    for i in range (1, N+1):
        unp1[i] = u[i] - v*(dt/dx)*(u[i]-u[i-1])
    unpf.append(unp1.copy())
    uexact.append(np.exp(-200*np.square(x-0.25-v*t[n])))
    u = unp1

fig, ax = plt.subplots()

plt.xlabel('x')
plt.ylabel('u')
plt.title('Initial condition')
line, = ax.plot(x, u0)
def animate(i):
    line.set_ydata(uexact[i])  # update the data
    return line,
ani = animation.FuncAnimation(fig, animate, np.arange(1, len(uexact)), interval=100)

line, = ax.plot(x, u0)
ax.set_xlim(xmin, xmax)
ax.set_xlabel('X nodes - Axis')
ax.set_ylabel('Y nodes - Axis')
def animate(i):
    line.set_ydata(unpf[i])  # update the data
    return line,
ani = animation.FuncAnimation(fig, animate, np.arange(1, len(unpf)), interval=100)
plt.show()

Upvotes: 2

Views: 3319

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339052

There is no reason to use two different FuncAnimations here, as you want one single animation, animating two or more objects.

Since unpf and uexact seem to have the same number of items, implementing this is straight forward.

... # all other code

line, = ax.plot(x, u0)
line2, = ax.plot(x, u0)
def animate(i):
    line.set_ydata(uexact[i])  # update the data
    line2.set_ydata(unpf[i])  # update the data
    return line, line2,

ani = animation.FuncAnimation(fig, animate, np.arange(1, len(unpf)), interval=100)
plt.show()

Upvotes: 3

Related Questions