我有一些关于 Jupyter notebook 中使用的
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 帧。plt.ion()
、plt.ioff()
、plt.show()
的任意组合。 GUI 窗口在初始化后弹出并保持空白。它显示了计算前 100 帧后的情节,我没想到它会在 100 帧后继续运行......