Matplotlib animation script runs fine first time but gets stuck on re-runs until kernel is restarted

I’m trying to run an animation where a scatter plot is updated every timestep. I am working in a jupyter notebook in vscode (if relevant). The animation script, given below, runs great the first time but it doesn’t execute as intended on subsequent runs. The problem is only fixed when I restart the kernel. My work requires me to constantly modify this animation code and hence need to rerun it multiple times. Restarting the kernel every time is cumbersome.

In following code, I am plotting object locations (block_centroids) using a scatter plot and updating them using the displacements at time timepoints[i] (given by fields[i]). The index i (val) increases in steps of 50 (tstep). The last time point is 5450 ms.

import matplotlib
matplotlib.use('Agg')
%matplotlib widget
import matplotlib.pyplot as plt
from matplotlib import animation

fig, axes = plt.subplots(figsize=(9,5), tight_layout = True)

tstep = 50
xs, ys = block_centroids.T
scat = axes.scatter(xs, ys)
axes.set_aspect('equal', adjustable='box')

def update(val):

    if val == len(timepoints)//tstep - 1:
        print('closing!')
        exit()
    
    scat.set_offsets(block_centroids + fields[tstep*val])
    fig.suptitle(fr'time $t = {timepoints[tstep*val]:.2f}$ sec')
    fig.canvas.draw_idle()
    return scat

def init():
    pass

ani = animation.FuncAnimation(fig=fig, func=update, init_func=init, frames=len(timepoints)//tstep, blit = True, interval=tstep)

After the first time I run this code block, the re-run either gets stuck at some midway time (between 0s and 5.45s) and prematurely prints ‘closing!’, or the code keeps running seemingly forever with no output and no error until I try to stop it and the kernel times out.

I have tried multiple things without completely understanding why they might work. My guess is that the animation-related objects are not reset and somehow the update() function gets called with the wrong (old) value and my attempts have mostly tried to close/delete the old instances.

  1. I added the if statement inside the update() function in an attempt to close the animation after a run. Earlier, instead of the exit() function, I was using plt.close(fig) which led to the animation getting stuck at a midway time and printing ‘closing!’ output repeatedly.

  2. I tried adding plt.cla(), plt.clf() and plt.close() at the start of the code block to close any open instances of fig and axes but that didn’t help.

  3. I tried deleting the fig and ani objects using del command to remove their previous instances in hopes of getting a fresh start for every run but that didn’t work.

  4. Earlier even the first runs of the animation were having problems. I added Agg backend after reading a stackoverflow answer recommending GTKAgg for handling animations better. I couldn’t use GTKAgg because I don’t have cairo, so I settled for the closest thing and that helped is making the first run successful.

What is not working here as intended? What can I try to debug this? I tried printing val at every function call, to check what is happening during reruns but then the code kept running without any output.

New contributor

gargantuar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật