'I need some help on making an animated plot using Matplotlib
I have an array x_trj that has shape (50,12), and I would like to make an animation for all the rows corresponding to certain columns in a 2-D plot (so I can see what direction each line is going). Below is my code:
from matplotlib.animation import FuncAnimation
fig,ax = plt.subplots()
# Plot initial line to fill in as we go
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return line,
def animate(i):
# Plot resulting trajecotry of car
line.set_xdata(x_trj[i,0:9:4])
line.set_ydata(x_trj[i,1:10:4])
return line,
anim = FuncAnimation(fig, animate, init_func = init, frames=x_trj.shape[0], interval=200) # animation doesn't show up?
However, the animation does not show up at all. All I get is an empty figure. How should I fix this issue? I am writing my code in Google colab.
The animation shows up but it's empty (it has a built-in play button):

Solution 1:[1]
I don't know what values you have in x_traj but I had to set xlim, ylim to see animation because animation doesn't change visible area automatically and it displays line in area which I can see.
I tested it only on local computer.
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
np.random.seed(0) # `randint()` will always select the same values
x_trj = np.random.randint(0, 10, (52,12))
fig, ax = plt.subplots()
ax.set_xlim(0, 10) # it would need to get min(), max() values from x_trj
ax.set_ylim(0, 10) # it would need to get min(), max() values from x_trj
#ax = plt.axes(xlim=(0, 10), ylim=(0, 10)) # needs `ax =`
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return line,
def animate(i):
print('i:', i)
x = x_trj[i,0:9:4]
y = x_trj[i,1:10:4]
print('x,y:', x, y)
line.set_xdata(x)
line.set_ydata(y)
return line,
anim = FuncAnimation(fig, animate, init_func=init, frames=x_trj.shape[0], interval=200)
plt.show()
Eventually you can change xlim, ylim during animation to change visible area but this may not look as you expect.
def animate(i):
print('i:', i)
x = x_trj[i,0:9:4]
y = x_trj[i,1:10:4]
print('x,y:', x, y)
line.set_xdata(x)
line.set_ydata(y)
ax.set_xlim(min(x), max(x)) # change visible are
ax.set_ylim(min(y), max(y)) # change visible are
return line,
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
