FuncAnimation 在 Jupyter Notebook 的 tk 后端运行两次帧

问题描述 投票:0回答:0

我有一些关于 Jupyter notebook 中使用的

FuncAnimation
的情节相关问题。

  • 主要问题是 FuncAnimation 运行两倍的帧数,同时保存正确的帧数。
  • 小问题是
    %matplotlib tk
    魔法,GUI窗口不显示即时剧情
  • 更小的问题是
    tqdm
    进度条只显示在第一行并且冻结为0%。

这里是一个示例代码(我猜下面的代码中有很多不必要的全局变量,因为我不太清楚

FuncAnimation
传递变量。欢迎任何建议):

from tqdm.notebook import tqdm
import matplotlib.animation as animation
from IPython import display
import sys

def ini_plot(fig, axs, iter_num, y, A):

    line, = axs[0,0].plot(np.arange(iter_num), y)
    im0 = axs[0,1].imshow(A, origin='lower', extent=(0,1,0,1))
    cbar = fig.colorbar(im0, ax=axs[0,:].ravel().tolist(), shrink=0.8)

    return line, cbar

def con_plot(fig, axs, frame, y, A, z):
    
    # each time update a point on the line
    y[frame] = z[-1]
    line.set_ydata(np.log10(y))
    im0 = axs[0,1].imshow(A, origin='lower', extent=(0,1,0,1))
    cbar.update_normal(im0)
    
    fig.canvas.draw()

    return line, cbar

def update(frame):
    global y, A, z, fig, axs

    A = A_update()
    z = z_update()

    line, cbar = con_plot(fig, axs, frame, y, A, z)
    return line, cbar

## Main function
plt.close('all')

%matplotlib tk

iter_num = 100
y = y_ini()
A = A_ini()

fig, axs = plt.subplots(1,2, figsize=(16,8))
plt.ioff()
line, cbar = ini_plot(fig, axs, iter_num, y, A)
global line, cbar

ani = FuncAnimation(fig, update, frames=tqdm(range(iter_num), file=sys.stdout), 
                   interval=10, blit=False, init_func=None, repeat= False)

ani.save('animation.mp4', writer='ffmpeg')
     
 

  • 在上面的代码中,我预计
    update
    运行 100 帧,GUI 窗口立即显示这 100 帧并保存 100 帧。结果是:animation.mp4 保存前 100 帧,而 GUI 窗口显示从第 101 帧到第 200 帧。
  • N不管我是否尝试过
    plt.ion()
    plt.ioff()
    plt.show()
    的任意组合。 GUI 窗口在初始化后弹出并保持空白。它显示了计算前 100 帧后的情节,我没想到它会在 100 帧后继续运行......
python matplotlib frame matplotlib-animation ffmpeg-python
© www.soinside.com 2019 - 2024. All rights reserved.