I want to animate some data, and I have been following the example from another stack question here to enable pausing. However, I am doing something a little different. In that example, they are using the sine function which can take non-integer values in the argument. What I am doing is plotting a set of data in the y-axis and matching it with a corresponding x-value (time in this case).
Desired Output
I simply want the output to plot the data and update the tick marks as it goes (thus the ax.set_xlim(0, i/sf)
below), while being able to pause or play the animation.
Close but not correct solution
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as am
length = 8e6
data = np.random.rand(length)
sf = 100 #Sampling frequency in MHz
x = np.arange(length)/sf
pause = False
def init():
line.set_data([], [])
return line,
def animate(i):
if not pause:
y = data[0:i]
xax = x[0:i]
line.set_data(xax, y)
ax.set_xlim(0, i/sf)
time_text.set_text(time_template%(i/sf))
return line, time_text
def onPress(event):
if event.key==' ':
global pause
pause ^= True
fig = plt.figure(figsize=(15,15))
ax = fig.add_subplot(111)
ax.set_ylim(min(data),max(data))
line, = ax.plot([], [], lw=2)
time_template = 'Time = %.1f $\mu$s' # prints running simulation time
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)
anim = am.FuncAnimation(fig, animate, interval=40, init_func=init)
fig.canvas.mpl_connect('key_press_event', onPress)
plt.show()
The problem with this solution is that when I pause and then unpause the animation the plot draws data to whatever it would have been at that point in time, had I not paused it.
You should be able to copy and paste this code to reproduce on your own machine.
Also Tried
I tried a similar structure to that of the example I linked. It doesn't work either.
The problem is nothing seemingly happens when I run the program. I think it's plotting something, because I can see the plot when I try to move around the plot.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as am
length = 8e6
data = np.random.rand(length)
sf = 100 #Sampling frequency in MHz
x = np.arange(length)/sf
pause = False
def init():
line.set_data([], [])
return line,
def theData():
i=0
while i<50:
if not pause:
y = data[0:i]
t = x[0:i]
i=i+1
yield t, y, i
def animate(theData):
t = theData[0]
y = theData[1]
i = theData[2]
line.set_data(t, y)
ax.set_xlim(0, i/sf)
time_text.set_text(time_template%(t))
return line, time_text
def onPress(event):
if event.key==' ':
global pause
pause ^= True
fig = plt.figure(figsize=(15,15))
ax = fig.add_subplot(111)
ax.set_ylim(min(data),max(data))
line, = ax.plot([], [], lw=2)
time_template = 'Time = %.1f $\mu$s' # prints running simulation time
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)
anim = am.FuncAnimation(fig, animate, theData, interval=40, init_func=init)
fig.canvas.mpl_connect('key_press_event', onPress)
plt.show()