【发布时间】:2016-11-15 01:11:21
【问题描述】:
我想为一些数据制作动画,我一直在关注另一个堆栈问题here 中的示例以启用暂停。但是,我正在做一些不同的事情。在该示例中,他们使用的是正弦函数,该函数可以在参数中采用非整数值。我正在做的是在 y 轴上绘制一组数据并将其与相应的 x 值(在这种情况下为时间)匹配。
期望的输出
我只是希望输出绘制数据并在运行时更新刻度线(因此下面的ax.set_xlim(0, i/sf)),同时能够暂停或播放动画。
关闭但不正确的解决方案
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()
这个解决方案的问题是,当我暂停然后取消暂停动画时,如果我没有暂停,绘图会将数据绘制到那个时间点的任何位置。
您应该能够复制并粘贴此代码以在您自己的机器上重现。
也试过了
我尝试了与我链接的示例类似的结构。它也不起作用。
问题是当我运行程序时似乎没有发生任何事情。我认为它在密谋什么,因为当我试图在情节中移动时,我可以看到情节。
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()
【问题讨论】:
标签: python animation matplotlib event-handling