I have some plot-related questions regarding FuncAnimation
used in Jupyter notebook.
- The main issue is the FuncAnimation runs twice of frames number while it saves the right number of frames.
- The minor issue is in the
%matplotlib tk
magic, the GUI window does not show the immediate plot. - The even minor issue is that
tqdm
progress bar only shows in the first line and frozens as 0%.
Here is a sample code (I guess there are many unnecessary global variables in the following codes, as I am not clear about FuncAnimation
on passing variables. Any suggestions will be greatly welcome):
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')
- In the above code, I expected
update
to run for 100 frames, the GUI window to show those 100 frames immediately and 100 frames to be saved. The result is: animation.mp4 saves the first 100 frames while the GUI window shows from 101st frame to 200th frame. - Nno matter if I tried any combination of
plt.ion()
,plt.ioff()
,plt.show()
. The GUI window is popped after initialization and stays blank. It shows the plot after first 100 frames are computed, and I didn't expect it to continue the runs after 100 frames...