python realtime plot using pyqtgraph

Viewed 24884

I need to plot in realtime a series floating point numbers from the serial port. These values are sepparated by the '\n' character, so the data sequence is something like this: x1 x2 x3 ...

How would you plot the data? I am using an Arduino board, the data rate is 200 samples/s, and my PC is running on Windows7 64 bits. I think a good choice is use the pyqtgraph library. I started to use the Plotting.py example in pyqtgraph (plenty more examples available after installing pyqtgraph and then running python3 -m pyqtgraph.examples), but I don't know how to adapt this code for my needs (see below). Thank you very much in advance.

from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg

# Set graphical window, its title and size
win = pg.GraphicsWindow(title="Sample process")
win.resize(1000,600)
win.setWindowTitle('pyqtgraph example')

# Enable antialiasing for prettier plots
pg.setConfigOptions(antialias=True)

# Random data process
p6 = win.addPlot(title="Updating plot")
curve = p6.plot(pen='y')
data = np.random.normal(size=(10,1000)) #  If the Gaussian distribution shape is, (m, n, k), then m * n * k samples are drawn.

# plot counter
ptr = 0 

# Function for updating data display
def update():
    global curve, data, ptr, p6
    curve.setData(data[ptr%10])
    if ptr == 0:
        p6.enableAutoRange('xy', False)  ## stop auto-scaling after the first data set is plotted
    ptr += 1

# Update data display    
timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(50)


## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
2 Answers

The best way to deal with this may be to run a separate "worker" thread to process your data and then update the graph. I believe you can do it with Qthread.

I don't know the exact reason why, but apparently .processEvents() is not the best way to solve this problem.

Related