PyQtGraph:问题循环通过绘制数据切片
Posted
技术标签:
【中文标题】PyQtGraph:问题循环通过绘制数据切片【英文标题】:PyQtGraph: Issue looping through plotting slices of data 【发布时间】:2020-10-05 16:53:41 【问题描述】:我有一个 python 类,它生成一个大小为 10000 的 numpy
数组并对其执行一些计算。该类有两个绘图方法,都使用pyqtgraph
我想知道如何循环遍历数据段(一次 200 个样本)并向用户显示处理后的数据,并等到用户按下任意键后再绘制接下来的 200 个样本?
我希望能够在不关闭 Qt 窗口的情况下更新绘图,以通过仅更新已绘制对象的内容来实现更高效的性能。
import numpy as np
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg
class testqt:
def __init__(self):
self.data = np.random.randn(10000) # for the sake of providing a MWE
self.do_some_processing()
def do_some_processing(self):
self.data_processed = 2*self.data
def plot_entire_processed_data(self):
# Plot the entire processed data
win = pg.GraphicsLayoutWidget(show=True)
p = win.addPlot()
curve_data = p.plot(self.data_processed)
QtGui.QApplication.instance().exec_()
def plot_processed_data_every_200(self):
# animate the processed data in segments of 200 samples
win = pg.GraphicsLayoutWidget(show=True)
p = win.addPlot()
curve_data = p.plot(self.data_processed[:200])
for i in range(200, len(self.data_processed), 200):
curve_data.setData(self.data_processed[i:i+200])
# How can I pause here and use keyboard to move to the next 200 samples?
# I would like to be able to visually evaluate each segment first and then
# press any key to see the next segment
QtGui.QApplication.instance().exec_() # unfortunately, this only plot the last 200 samples
a = testqt()
a.plot_entire_processed_data()
a.plot_processed_data_every_200()
如果有任何帮助或提示,我将不胜感激。
【问题讨论】:
【参考方案1】:要检测键盘事件,有几个选项取决于具体目标:
如果您想在焦点位于窗口小部件时检测任何键的按下,则只需覆盖窗口的 keyPressEvent 方法即可。
1234563 >另一方面,逻辑是获取数据片段,所以要做到这一点,只需使用生成器函数即可。
考虑第一种情况,解决办法是:
import numpy as np
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg
def iter_by_step(data, step):
for i in range(0, len(data), step):
yield data[i : i + step]
class GraphicsLayoutWidget(pg.GraphicsLayoutWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.data = np.random.randn(10000)
self.iter = None
curve = self.addPlot()
self.p = curve.plot()
def do_some_processing(self):
self.data_processed = 2 * self.data
self.iter = iter_by_step(self.data_processed, 200)
self.plot_processed_data_every_200()
def keyPressEvent(self, event):
super().keyPressEvent(event)
if self.iter is not None:
self.plot_processed_data_every_200()
def plot_processed_data_every_200(self):
try:
data = next(self.iter)
except StopIteration:
pass
else:
self.p.setData(data)
if __name__ == "__main__":
w = GraphicsLayoutWidget()
w.show()
w.do_some_processing()
QtGui.QApplication.instance().exec_()
【讨论】:
多么巧妙的解决方案!谢谢你。您能否评论一下这种方法是否适合使用计时器而不是按键来循环数据片? @AFP 使用 QTimer以上是关于PyQtGraph:问题循环通过绘制数据切片的主要内容,如果未能解决你的问题,请参考以下文章