Home > Enterprise >  How to animate the vector field?
How to animate the vector field?

Time:11-22

As the question, how do I animate a series of plots instead of printing each individual plot? Thanks a lot!!!


import numpy as np
from matplotlib import pyplot as plt
from scipy.integrate import odeint
import matplotlib.animation as animation
%matplotlib inline

 # Define vector field
def vField(x,t,a):
    u = 2*x[1]
    v = -x[0]   a*(x[1] - 1/4 * x[1]**2)
    return [u,v]
    
vec = [-10,-5,0,5,10]

for a in vec:
    # Plot vector field
    X, Y = np.mgrid[-2:2:20j,-2:2:20j]
    U, V = vField([X,Y],0,a)

    fig, ax = plt.subplots(figsize=(10, 7))
    ax.quiver(X, Y, U, V)
    plt.pause(0.01)
    
plt.show()

CodePudding user response:

You can use matplotlib's FuncAnimation:

import numpy as np
from matplotlib import pyplot as plt
from scipy.integrate import odeint
from matplotlib.animation import FuncAnimation

 # Define vector field
def vField(x,t,a):
    u = 2*x[1]
    v = -x[0]   a*(x[1] - 1/4 * x[1]**2)
    return [u,v]
    

vec = np.linspace(-10, 10, 100)

fig, ax = plt.subplots()
X, Y = np.mgrid[-2:2:20j,-2:2:20j]
U, V = vField([X,Y],0, vec[0])
q = ax.quiver(X, Y, U, V)

def animate(i):
    U, V = vField([X,Y],0, vec[i])
    q.set_UVC(U, V)

ani = FuncAnimation(fig, animate, frames=len(vec), repeat=False)
plt.show()

CodePudding user response:

You have to declare your fig, ax before the loop and clear it between each quiver.

Indeed, you want to use only one figure and not create one by iteration. Moreover, you want to clear the figure between each iteration or all plots will be shown on top of the others.

fig, ax = plt.subplots(figsize=(10, 7))

for a in vec:
    # Plot vector field
    X, Y = np.mgrid[-2:2:20j,-2:2:20j]
    U, V = vField([X,Y],0,a)

    ax.clear()
    ax.quiver(X, Y, U, V)
    plt.pause(0.01)

Please note that you will not see anything with your current vec because it is too short and the pause is 0.01. With a longer one you will see a smooth drawing.

  • Related