I am new to matplotlib and was trying out animation. Watched few tutorials from youtube and created below code, which is pretty much copy/paste from one of the tutorials. I was expecting the plot to be continuously updated with new data points, but it is not happening. I added the print statements for trouble shooting and saw that xcord and ycord were printed just once - meaning the animate function does not seem to be called at all. Please help to figure out what I am doing wrong. I am running this code in Spyder 4.1.5
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from itertools import count
import random
xcord = []
ycord = [5]
index = count()
xcord.append(next(index))
def animate(i):
xcord.append(next(index))
ycord.append(random.randint(0,5))
print(xcord)
print(ycord)
plt.cla()
plt.plot(xcord,ycord)
fig, ax = plt.subplots(1,1)
print(xcord)
print(ycord)
ani = FuncAnimation(fig,animate,interval=1000)
plt.tight_layout()
plt.show()
CodePudding user response:
I will answer by modifying the animation from the official one to fit your code. The line color is red and the line width is set to 3. There's no reason to specify the number of frames and turn off repetition. You can customize the rest as you like.
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from itertools import count
import random
xcord = []
ycord = [5]
index = count()
xcord.append(next(index))
fig, ax = plt.subplots(1,1)
ax.set(xlim=(0,20), ylim=(0, 5))
line, = ax.plot([], [], 'r-', lw=3)
def animate(i):
xcord.append(next(index))
ycord.append(random.randint(0,5))
line.set_data(xcord, ycord)
ani = FuncAnimation(fig, animate, frames=19, interval=200, repeat=False)
plt.show()