Can't plot real time plot using matplotlib
I wrote the following code using an online search. My intention here is to get a real time plot of time along the x-axis and some randomly generated value along the y-axis
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import numpy as np
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def animate(i):
xar = []
yar = []
x,y = time.time(), np.random.rand()
xar.append(x)
yar.append(y)
ax1.clear()
ax1.plot(xar,yar)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
With the above code, I just see the range of the y-axis change continuously and the graph will not appear in the figure.
+3
source to share
1 answer
The problem is, you never update xvar
and yvar
. You can do this by moving the list definitions outside of the definition animate
.
import matplotlib.pyplot as plt import matplotlib.animation as animation import time import numpy as np fig = plt.figure() ax1 = fig.add_subplot(1,1,1) xar = [] yar = [] def animate(i): x,y = time.time(), np.random.rand() xar.append(x) yar.append(y) ax1.clear() ax1.plot(xar,yar) ani = animation.FuncAnimation(fig, animate, interval=1000) plt.show()
+1
source to share