Loading [MathJax]/extensions/TeX/AMSsymbols.js

Thursday, July 30, 2015

Animated stripchart

This script creates a moving stripchart-style plot of a data stream. Change num_points to increase the length of the section that gets plotted. (TODO: put in a matplotlib slider widget for num_points.)
# Monitor and plot
from __future__ import division, print_function
import numpy as np
from numpy import sin, cos, random
from scipy.constants import c,e,h,hbar,u,pi
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
def return_values():
time.sleep(0.2) # delay for 200 ms
# replace the following line with a function that returns data from the labjack
return np.random.uniform()
# Plot and animate
t0 = time.time()
t = []
t.append(time.time()-t0)
y = []
y.append(return_values())
fig, ax = plt.subplots()
t0 = time.time()
num_points = 30 # length of trace to plot
line, = ax.plot(t[-num_points:],y[-num_points:],lw=2)
text_template = 'y-value = %.2g'
text = ax.text(0.15,0.15,text_template%(y[-1]), transform=ax.transAxes, family='monospace',fontsize=20,weight='heavy')
def animate(i):
# add new points to time and y-value arrays
t.append(time.time()-t0)
y.append(return_values())
# rescale axes to keep moving
ax.set_xlim(t[-num_points:][0],t[-1])
avg = np.average(y[-num_points:])
variation = max(y[-num_points:]) - min(y[-num_points:])
ax.set_ylim(avg - 1.2*variation/2, avg + 1.2*variation/2)
ax.figure.canvas.draw() # this is necessary, to redraw the axes
# refresh line and text
line.set_xdata( t[-num_points:] )
line.set_ydata( y[-num_points:] )
text.set_text( text_template%(y[-1]) )
return line, text
def init(): #Init only required for blitting to give a clean slate.
line.set_ydata(np.ma.array(t[-num_points:], mask=True))
text.set_text(" ")
return line, text
ani = animation.FuncAnimation(fig, animate, init_func=init,
interval=0.6, blit=False) # blit has to be False, to avoid ugly artefacts on the text
plt.show()