Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear a plot in a `while` loop when using PyQtGraph?

I am using PyQtGraph for a speedy visualization of my data acquisition. For this I am redrawing the data constantly using a while loop. A simplified version of this code is given by:

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

x = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, 1000)
y = numpy.cos(x)

# Plot
win = pg.GraphicsWindow()
win.resize(800, 800)

p = win.addPlot()
p.plot(x, y, pen = "y")

i = 0
while i < 5000:
  start_time = time.time()

  noise = numpy.random.normal(0, 1, len(y))
  y_new = y + noise

  p.plot(x, y_new, pen = "y", clear = True)
  p.enableAutoRange("xy", False)

  pg.QtGui.QApplication.processEvents()

  i += 1

  end_time = time.time()
  print("It has been {0} seconds since the loop started".format(end_time - start_time))

win.close()

When I time each iteration I find that I am not properly clearing the graph. The iteration time just keeps on increasing, and I am slowing down my data acquisition. For the example above, the iteration time in the beginning is about 0.009 s whereas at the end it is about 0.04 s. I therefore have a memory-leak.

I know that in matplotlib I should be calling be clf() to properly clear the plot. Unfortunately I am not that familiar with PyQtGraph and thought the clear = True would take care of this issue. I am confident it should be possible as PyQtGraph was designed for this type of usage.

How should I clear the graph each iteration to make sure I am not slowing down my data acquisition?

like image 513
The Dude Avatar asked Feb 21 '16 12:02

The Dude


People also ask

How do you dynamically plot in Python?

To dynamically update plot in Python matplotlib, we can call draw after we updated the plot data. to define the update_line function. In it, we call set_xdata to set the data form the x-axis. And we call set_ydata to do the same for the y-axis.


1 Answers

When you call plot on you plotItem, you create a new plotDataItem. All these plotDataItems doesn't seem to clear up properly. You can instead try to use only one plotDataItem and update the contents of it. Do this by using

plot = p.plot(x, y, pen = "y")

and then inside your loop

plot.setData(x, y_new)
like image 186
luddek Avatar answered Nov 01 '22 07:11

luddek