Laboratory of Statistical Signal Processing & Inverse Problems

Blog

Animated plots with Matplotlib

The script below will do this:

Enjoy it!

import matplotlib.pyplot as plt
import numpy as np
import time

# N: number of elements in the plot
N = 100
x = np.arange(N)
# Start with an all-zero vector (you can change this)
y1 = np.zeros(N, dtype=float)
y2 = np.zeros(N, dtype=float)

fig, ax = plt.subplots()
line1, = ax.plot(x, y1)
line2, = ax.plot(x, y2)
plt.grid()
plt.legend(['Plot 1', 'Plot 2'], loc=2)
plt.xticks([0, N//2, N], ['t-'+str(N), 't-'+str(N//2), 't'])
ymin = 0
ymax = 0

while True:
    # Shift all elements to the left
    y1 = np.roll(y1, -1)
    y2 = np.roll(y2, -1)

    # Insert new value at last element
    y1[-1] = np.cos(time.time()) + np.random.randn(1)*1e-1
    y2[-1] = np.sin(time.time()) + np.random.randn(1)*1e-1
    # Update plot
    line1.set_ydata(y1)
    line2.set_ydata(y2)

    # Adjust the range exhibited in the plot
    if y1.min() < ymin:
        ymin = y1.min()
    if y1.max() > ymax:
        ymax = y1.max()
    if y2.min() < ymin:
        ymin = y2.min()
    if y2.max() > ymax:
        ymax = y2.max()
    ax.axis([0, N, ymin, ymax])

    # Very small pause (required for update)
    plt.pause(1e-2)

Leave a Reply

Your email address will not be published. Required fields are marked *