Background: I am trying to prepare a python script that will read data from several sensors, live-plot the data, and also perform calculations with the data.
Problem: The realtime plot is very "laggy". It seems to be attributed to the time.sleep() duration. For example, I want to record data every 10 s, so I am using time.sleep(10) in the main loop. With this, if I try to move or re-size the plot widget, it is very slow to respond. For time.sleep(1), the problem is not as pronounced.
I am using PyQtGraph (as I have read that it is fast), but the same problem occurs with other plotting packages such as Matplotlib for example.
Minimum working example:
The code runs a loop: every 10 seconds, the time is printed to the shell, and a data array is appended with random data to be plotted with PyQtGraph.
import pyqtgraph as pg
import numpy as np
import time
t0 = time.time()
win = pg.GraphicsLayoutWidget(show=True)
p1 = win.addPlot()
def update(xData, yData):
p1.plot(xData, yData, clear = True)
pg.QtGui.QApplication.processEvents()
x = np.empty(0)
y = np.empty(0)
for i in range(100):
print(f'i = {i}, t = {time.time()-t0} s')
x = np.append(x, i)
y = np.append(y, i+i*np.random.rand())
update(x, y)
time.sleep(10)
I am thinking that some sort of asynchronous timer may be necessary to avoid the lag problem? From what I understand, use of multiple threads is to be avoided when possible.
In summary, my primary questions are:
How do you avoid lag in live-plotted data?
Are there simpler/more straight-forward ways to live plot data (with other processes occuring in the background (e.g. printing info to the shell))?