PyQtGraph 实时更新直方图示例
以下是一个简单的示例代码,使用 PyQtGraph 实现实时刷新的直方图:
import pyqtgraph as pg
import numpy as np
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QTimer
class HistogramWindow(QMainWindow):
def __init__(self):
super().__init__()
# 创建一个 PlotWidget 对象
self.plot = pg.PlotWidget()
self.setCentralWidget(self.plot)
# 创建一个直方图
self.hist = pg.HistogramLUTItem()
self.hist.setImageItem(self.plot.getPlotItem().getImageItem())
self.plot.addItem(self.hist)
# 创建一个定时器,用于实时更新数据
self.timer = QTimer()
self.timer.timeout.connect(self.update)
self.timer.start(50) # 每 50 毫秒更新一次
def update(self):
# 生成随机数据
data = np.random.normal(size=1000)
# 更新直方图
self.hist.setImage(data, levels=[-3, 3])
if __name__ == '__main__':
app = QApplication([])
win = HistogramWindow()
win.show()
app.exec_()
在上面的代码中,我们创建了一个 HistogramWindow 类,继承自 QMainWindow,用于显示直方图。在 __init__() 方法中,我们创建了一个 PlotWidget 对象,并将其设置为窗口的中央部件。然后,我们创建了一个 HistogramLUTItem 对象,用于显示直方图,并将其添加到 PlotWidget 对象中。接着,我们创建了一个定时器 timer,用于每隔一定时间更新直方图。在 update() 方法中,我们生成了一个长度为 1000 的随机数据,并使用 setImage() 方法更新直方图。levels 参数指定了直方图的范围,这里设置为 [-3, 3],表示数据的最小值为 -3,最大值为 3。最后,我们启动应用程序并显示窗口。定时器每 50 毫秒触发一次 update() 方法,从而实现了实时刷新的直方图。
原文地址: https://www.cveoy.top/t/topic/oIUz 著作权归作者所有。请勿转载和采集!