Skip to main content
 首页 » 编程设计

python之使用基于示例的代码暂停动画时遇到问题

2025年04月02日14think

我想为一些数据设置动画,我一直在关注另一个堆栈问题的示例 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() 

请您参考如下方法:

传递给 animate 的参数是一个帧号。但是,无论动画是否暂停,此数字都会递增。

因此,引入您自己的全局变量 frame,它记录真实的帧数并且仅在动画未暂停时递增:

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as am 
 
length = 8*10**6 
data = np.random.rand(length) 
sf = 100 #Sampling frequency in MHz 
x = np.arange(length)/sf 
 
pause = False 
frame = 0 
 
def init(): 
    line.set_data([], []) 
    return line, 
 
def animate(i): 
    global frame 
    if not pause: 
        frame += 1 
        y = data[0:frame] 
        xax = x[0:frame] 
        line.set_data(xax, y) 
        ax.set_xlim(0, frame/sf) 
        time_text.set_text(time_template%(frame/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()