【问题标题】:How to clear a plot in a `while` loop when using PyQtGraph?使用 PyQtGraph 时如何清除“while”循环中的绘图?
【发布时间】:2016-06-02 19:52:21
【问题描述】:

我正在使用 PyQtGraph 快速可视化我的数据采集。为此,我使用while 循环不断地重绘数据。此代码的简化版本如下:

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

当我为每次迭代计时时,我发现我没有正确清除图表。迭代时间不断增加,我正在减慢数据采集速度。对于上面的例子,开始的迭代时间大约是0.009 s,而最后大约是0.04 s。因此我有内存泄漏。

我知道在matplotlib 中我应该调用clf() 以正确清除情节。不幸的是,我对 PyQtGraph 并不熟悉,并认为 clear = True 会解决这个问题。我相信这应该是可能的,因为PyQtGraph 是为这种类型的使用而设计的。

我应该如何在每次迭代中清除图表以确保我不会减慢数据采集速度?

【问题讨论】:

    标签: python plot memory-leaks pyqtgraph


    【解决方案1】:

    当你在你的 plotItem 上调用 plot 时,你创建了一个新的 plotDataItem。所有这些 plotDataItems 似乎都没有正确清除。您可以尝试只使用一个 plotDataItem 并更新它的内容。使用

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

    然后在你的循环中

    plot.setData(x, y_new)
    

    【讨论】:

      猜你喜欢
      • 2022-09-24
      • 2012-08-06
      • 2022-12-10
      相关资源
      最近更新 更多