Search code examples
pythonmatplotlibanimationdata-visualizationvisualization

Matplotlib FuncAnimation 1st interval of graph not coming


I have the following code which creates a graph animation. The graph should start from 0, but the 1st interval graph isn't coming.
Below is the code:

import matplotlib.pylab as plt
import matplotlib.animation as animation
import numpy as np

fig, ax = plt.subplots()

left = -1
right = 2*np.pi - 1

def animate(i):
    global left, right
    left = left + 1
    right = right + 1
    x = np.linspace(left, right, 50)
    y = np.cos(x)
    ax.cla()
    ax.set_xlim(left, right)
    ax.plot(x, y, lw=2)

ani = animation.FuncAnimation(fig, animate, interval = 1000)

plt.show()

For the 1st interval [0, 2π] the graph isn't coming. What's the mistake?


Solution

  • I changed a little bit your code:

    • first of all I plot the first frame outside the animate function and I generate a line object from it
    • then I update the line data within animate function
    • I suggest to use i counter (which starts from 0 and increases by 1 in each frame) to update your data, in place of calling global variables and change them

    Complete Code

    import matplotlib.pylab as plt
    import matplotlib.animation as animation
    import numpy as np
    
    fig, ax = plt.subplots()
    
    left = 0
    right = 2*np.pi
    
    x = np.linspace(left, right, 50)
    y = np.cos(x)
    
    line, = ax.plot(x, y)
    ax.set_xlim(left, right)
    
    
    def animate(i):
        x = np.linspace(left + i, right + i, 50)
        y = np.cos(x)
    
        line.set_data(x, y)
        ax.set_xlim(left + i, right + i)
    
        return line,
    
    ani = animation.FuncAnimation(fig = fig, func = animate, interval = 1000)
    
    plt.show()
    

    enter image description here