DEV Community

petercour
petercour

Posted on

Matplotlib Animation, Fun with Python

Did you know you can animate matplotlib plots?

Matplotlib is a plotting library for Python. By default all plots are static, not animated. You can create bar charts, line charts, pie charts and all types of charts.

That means you can plot data that it's interactive. That can be just a range it loops over or data you receive from the web. This is easy to do.

In this example we'll plot 2 lines, the red line will move.

First import:

from matplotlib.animation import FuncAnimation
Enter fullscreen mode Exit fullscreen mode

Call the function

anim = FuncAnimation(fig, update, frames=np.arange(0, 10, 0.1), interval=200)
Enter fullscreen mode Exit fullscreen mode

Where frames show the start, end and step parameter for each frame.
Thus, running the code will show an animated plot.

So your code can be something like this:

#!/usr/bin/python3
import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
fig.set_tight_layout(True)

x = np.arange(0, 20, 0.1)
line, = ax.plot(x, x - 5, 'r-', linewidth=2)

ax.plot(x, x, 'b', linewidth=2)

def update(i):
    label = 'timestep {0}'.format(i)
    line.set_ydata(0 + x*i)
    ax.set_xlabel(label)    
    return line, ax

if __name__ == '__main__':
    anim = FuncAnimation(fig, update, frames=np.arange(0, 10, 0.1), interval=200)
    plt.grid(True)
    plt.title("Matplotlib Animation")
    plt.show()
Enter fullscreen mode Exit fullscreen mode

Then you'll see the red line move:

Related links:

Top comments (0)