DEV Community

petercour
petercour

Posted on

3 2

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:

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay