Skip to content

Instantly share code, notes, and snippets.

@vanne02135
Last active August 29, 2015 14:23
Show Gist options
  • Save vanne02135/00b7bd225022295e510d to your computer and use it in GitHub Desktop.
Save vanne02135/00b7bd225022295e510d to your computer and use it in GitHub Desktop.
Online plotter using matplotlib
# Plot line per line, can be used as a serial plotter
import matplotlib.pyplot as plt
import numpy
import time
import math
import random
class OnlinePlotter:
# Plot data as it arrives. DataLimit is the max number of data points in a view
def __init__(self, dataLimit=500):
self.limit = dataLimit
self.h = None
def update(self, valueArray):
if self.h == None:
self.h = []
for x in valueArray:
h = plt.plot(0, x)
self.h.extend(h)
plt.show(block=False)
else:
for i, h in enumerate(self.h):
xdata = h.get_xdata()
ydata = h.get_ydata()
if len(xdata) > self.limit:
xdata = xdata[-self.limit-1:]
ydata = ydata[-self.limit-1:]
h.set_xdata(numpy.append(xdata, xdata[-1]+1))
h.set_ydata(numpy.append(ydata, valueArray[i]))
plt.axes().relim()
plt.axes().autoscale_view()
plt.draw()
def serialPlotter(port = "/dev/cu.usbserial-DA01L9R9"):
import serial
ser = serial.Serial(port, 9600, timeout=5)
if not ser.isOpen():
print "Could not open serial port %s" % port
return
plotter = OnlinePlotter(dataLimit = 50)
line = ser.readline()
Nplots = len(line.split())
while True:
line = ser.readline()
if len(line.split()) != Nplots:
print "Number of channels mismatch"
continue
values = []
for v in line.split():
values.append(float(v))
print values
plotter.update(values)
def TestOnlinePlotter():
plotter = OnlinePlotter()
x1 = 0
x2 = 0
for k in range(10000):
x1 += random.random() - 0.5
x2 = math.sin(k/10.0)
newValues = [x1, x2]
#print newValues
plotter.update(newValues)
#time.sleep(0.01)
print "Press enter to quit"
raw_input()
if __name__ == "__main__":
# TestOnlinePlotter()
serialPlotter()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment