Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pyplot animation not working properly when plt.pause() is used

I’m trying to create a pyplot simulation using plt.pause() but I can’t make even the simplest example work. This is the code:

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(19680801)
data = np.random.random((50, 50, 50))

fig, ax = plt.subplots()

for i, img in enumerate(data):
    ax.clear()
    ax.imshow(img)
    ax.set_title(f"frame {i}")
    plt.pause(0.1)

The issue seems to have something to do with the last line of code (plt.pause(0.1)). Without this line the final output shows the final frame of the simulation—frame 49 (indicating the whole loop has finished). If I include the final line and run the simulation, the output stops at the first frame—frame 0 (and the simulation doesn’t progress to the next step in the loop). I’ve also tried to set plt.pause(0.0) but that had exactly same effect as setting it to any other number.

I’m on mac, using python 3.12 under jupyter notebook 7.2.1. I would appreciate any advice. Thank you.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think this example is not made to work in Jupyter notebooks. Getting matplotlib animation to run in notebooks can be cumbersome….

Try this minimal example to get started. Does it work?:

import matplotlib.animation
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["animation.html"] = "jshtml"
plt.rcParams['figure.dpi'] = 150  
plt.ioff()
fig, ax = plt.subplots()

x= np.linspace(0,10,100)
def animate(t):
    plt.cla()
    plt.plot(x-t,x)
    plt.xlim(0,10)

matplotlib.animation.FuncAnimation(fig, animate, frames=10)

see Inline animations in Jupyter for more information (this example was also taken from there)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading