Python: matplotlib - loop, clear and show different plots over the same figure

前端 未结 2 512
南旧
南旧 2020-12-10 09:14

I want to see how a plot varies with different values using a loop. I want to see it on the same plot. But i do not want to remains of the previous plot in the figure. In MA

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-10 10:08

    There are essentially two different ways to create animations in matplotlib

    interactive mode

    Turning on interactive more is done using plt.ion(). This will create a plot even though show has not yet been called. The plot can be updated by calling plt.draw() or for an animation, plt.pause().

    import matplotlib.pyplot as plt
    
    x = [1,1]
    y = [1,2]
    
    fig, (ax1,ax2) = plt.subplots(nrows=2, sharex=True, sharey=True)
    line1, = ax1.plot(x)
    line2, = ax2.plot(y)
    ax1.set_xlim(-1,17)
    ax1.set_ylim(-400,3000)
    plt.ion()
    
    for i in range(15):
        x.append(x[-1]+x[-2])
        line1.set_data(range(len(x)), x)
        y.append(y[-1]+y[-2])
        line2.set_data(range(len(y)), y)
    
        plt.pause(0.1)
    
    plt.ioff()    
    plt.show()
    

    FuncAnimation

    Matplotlib provides an animation submodule, which simplifies creating animations and also allows to easily save them. The same as above, using FuncAnimation would look like:

    import matplotlib.pyplot as plt
    import matplotlib.animation
    
    x = [1,1]
    y = [1,2]
    
    fig, (ax1,ax2) = plt.subplots(nrows=2, sharex=True, sharey=True)
    line1, = ax1.plot(x)
    line2, = ax2.plot(y)
    ax1.set_xlim(-1,18)
    ax1.set_ylim(-400,3000)
    
    
    def update(i):
        x.append(x[-1]+x[-2])
        line1.set_data(range(len(x)), x)
        y.append(y[-1]+y[-2])
        line2.set_data(range(len(y)), y)
    
    ani = matplotlib.animation.FuncAnimation(fig, update, frames=14, repeat=False)   
    plt.show()
    

    An example to animate a sine wave with changing frequency and its power spectrum would be the following:

    import matplotlib.pyplot as plt
    import matplotlib.animation
    import numpy as np
    
    x = np.linspace(0,24*np.pi,512)
    y = np.sin(x)
    
    def fft(x):
        fft = np.abs(np.fft.rfft(x))
        return fft**2/(fft**2).max()
    
    fig, (ax1,ax2) = plt.subplots(nrows=2)
    line1, = ax1.plot(x,y)
    line2, = ax2.plot(fft(y))
    ax2.set_xlim(0,50)
    ax2.set_ylim(0,1)
    
    def update(i):
        y = np.sin((i+1)/30.*x)
        line1.set_data(x,y)
        y2 = fft(y)
        line2.set_data(range(len(y2)), y2)
    
    ani = matplotlib.animation.FuncAnimation(fig, update, frames=60, repeat=True)  
    plt.show()
    

提交回复
热议问题