Search code examples
matplotlibmatplotlib-animation

Matplotlib line chart animation


I am trying to animate a simple line chart with 2 equal arrays. I've seen some guides online but honestly, I'm not sure what I'm doing here, am I close to the solution?

I'm looking for this: https://miro.medium.com/max/1126/1*j0LxVQPbwtQDpL17TH9gZw.gif

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

x = np.array([1,2,3,4,5,6,7,8])
y = np.array([6,9,12,42,50,62,76,82])
fig = plt.figure()
ax = plt.axes(xlim=(1, 8), ylim=(6, 82))
line, = ax.plot([], [], lw=2)

def init():
    line.set_data([], [])
    return line,

def animate(i):
    line.set_ydata(x[i:])
    line.set_xdata(y[i:])
    return line,

anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
plt.show()

Solution

  • We are changing the way the data is set up. And I changed the number of frames to 9 because the number of data is 8. In addition, I used PIL to create GIF images, so please correct it.

    import numpy as np
    from matplotlib import pyplot as plt
    from matplotlib import animation
    from IPython.display import HTML
    from matplotlib.animation import PillowWriter
    
    x = np.array([1,2,3,4,5,6,7,8])
    y = np.array([6,9,12,42,50,62,76,82])
    
    fig = plt.figure()
    ax = plt.axes(xlim=(1, 8), ylim=(6, 82))
    line, = ax.plot([], [], lw=2)
    
    def init():
        line.set_data([], [])
        return line,
    
    def animate(i):
        line.set_data(x[:i],y[:i])
        return line,
    
    anim = animation.FuncAnimation(fig, animate, init_func=init,
                                   frames=9, interval=200, blit=True)
    
    # anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
    # plt.show()
    anim.save('plot_ani.gif', writer='pillow')
    

    enter image description here