0

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))?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Ethan S
  • 21
  • 3
  • 1
    Use matplotlib animation. Check out this post. https://stackoverflow.com/questions/16132798/python-animation-graph/16133279 – merit_2 Oct 14 '21 at 19:56
  • Thank you for the suggestion. I have heard of matplotlib animation. However, when you use animation.FuncAnimation(), it seems that no other processing can occur in the background (e.g., communicating with a sensor). Would using some sort of multi-core processing be the only solution there? – Ethan S Oct 14 '21 at 20:33
  • Check out: http://www.mikeburdis.com/wp/notes/plotting-serial-port-data-using-python-and-matplotlib/ I use something similar to talk to my device via serial. – merit_2 Oct 14 '21 at 20:47
  • Thanks, that is helpful for matplotlib. Also, if people are using pyqtgraph, it looks like QtTest.QTest.qWait() from PyQt is a non-blocking alternative for time.sleep(). – Ethan S Oct 14 '21 at 22:04

0 Answers0