This Page

animation example code: strip_chart_demo.pyΒΆ

[source code]

Emulate an oscilloscope.  Requires the animation API introduced in
matplotlib 1.0 SVN.
import numpy as np
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
import matplotlib.animation as animation

class Scope:
    def __init__(self, ax, maxt=2, dt=0.02): = ax
        self.dt = dt
        self.maxt = maxt
        self.tdata = [0]
        self.ydata = [0]
        self.line = Line2D(self.tdata, self.ydata), 1.1), self.maxt)

    def update(self, y):
        lastt = self.tdata[-1]
        if lastt > self.tdata[0] + self.maxt: # reset the arrays
            self.tdata = [self.tdata[-1]]
            self.ydata = [self.ydata[-1]]
  [0], self.tdata[0] + self.maxt)

        t = self.tdata[-1] + self.dt
        self.line.set_data(self.tdata, self.ydata)
        return self.line,

def emitter(p=0.03):
    'return a random value with probability p, else 0'
    while True:
        v = np.random.rand(1)
        if v > p:
            yield 0.
            yield np.random.rand(1)

fig, ax = plt.subplots()
scope = Scope(ax)

# pass a generator in "emitter" to produce data for the update func
ani = animation.FuncAnimation(fig, scope.update, emitter, interval=10,

Keywords: python, matplotlib, pylab, example, codex (see Search examples)