Search code examples
pausematplotlibpyplot

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.


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)

    Edit: It should also work with the magic %matplotlib command that will open an interactive window instead of using the cell output. See Plots that varies over the time on Python Matplotlib with Jupyter