Home > Software design >  Need help on animating a 2-D trajectory using FuncAnimation
Need help on animating a 2-D trajectory using FuncAnimation

Time:01-24

I have an array x_trj that has shape (50,3), and I want to plot a 2-D trajectory using the 1st and the 2nd columns of this array (x & y coordinates respectively). This trajectory will be on top of a circle. Here is my code so far:

from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt

fig = plt.figure()
ax = plt.axes(xlim=(-5, 5), ylim=(-5, 5))
line, = ax.plot([], [], lw=2)

# Plot circle
theta = np.linspace(0, 2*np.pi, 100)
plt.plot(r*np.cos(theta), r*np.sin(theta), linewidth=5)
ax = plt.gca()

def animate(n):
    # Plot resulting trajecotry of car
    for n in range(x_trj.shape[0]):
      line.set_xdata(x_trj[n,0])
      line.set_ydata(x_trj[n,1])
      
    return line,



anim = FuncAnimation(fig, animate,frames=200, interval=20)

However, the animation turns out to be a stationary figure. I checked out the Matplotlib animation example on the documentation page, but I still can't figure out what my animate(n) function should look like in this case. Can someone give me some hints?

CodePudding user response:

The code below makes the following changes:

  • added some test data
  • in animate:
    • remove the for loop
    • only copy the part of the trajectory until the given n
  • in the call to FuncAnimation:
    • `frames should be equal to the given number of points (200 frames and 50 points doesn't work well)
    • interval= set to a larger number, as 20 milliseconds make things too fast for only 50 frames
  • added plt.show() (depending on the environment where the code is run, plt.show() will trigger the animation to start)
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np

# create some random test data
x_trj = np.random.randn(50, 3).cumsum(axis=0)
x_trj -= x_trj.min(axis=0, keepdims=True)
x_trj /= x_trj.max(axis=0, keepdims=True)
x_trj = x_trj * 8 - 4

fig = plt.figure()
ax = plt.axes(xlim=(-5, 5), ylim=(-5, 5))
line, = ax.plot([], [], lw=2)

# Plot circle
theta = np.linspace(0, 2 * np.pi, 100)
r = 4
ax.plot(r * np.cos(theta), r * np.sin(theta), linewidth=5)

def animate(n):
    line.set_xdata(x_trj[:n, 0])
    line.set_ydata(x_trj[:n, 1])
    return line,

anim = FuncAnimation(fig, animate, frames=x_trj.shape[0], interval=200)
# anim.save('test_trajectory_animation.gif')
plt.show()

test animation

  •  Tags:  
  • Related