pyqtgraph 实时更新柱状图
import sys
import numpy as np
from PyQt5.QtWidgets import QApplication, QMainWindow
import pyqtgraph as pg
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.plot_widget = pg.PlotWidget(title='实时更新的柱状图')
self.setCentralWidget(self.plot_widget)
self.data = np.random.rand(10) # 初始数据(模拟数据)
self.bars1 = pg.BarGraphItem(x=np.arange(10), height=self.data, width=0.8, brush='g')
self.bars2 = pg.BarGraphItem(x=np.arange(10), height=self.data, width=0.8, brush='r')
self.plot_widget.addItem(self.bars2)
self.plot_widget.addItem(self.bars1)
self.timer = pg.QtCore.QTimer() # 创建定时器
self.timer.timeout.connect(self.update_data_and_plot) # 连接定时器超时信号与更新数据和绘制方法
self.timer.start(100) # 设置定时器间隔为1秒
def update_data_and_plot(self):
self.data = np.random.rand(10) # 更新数据(模拟新的随机数据)
self.bars2.setOpts(x=np.arange(10), height=[10] * 10) # 更新柱状图数据
self.bars1.setOpts(x=np.arange(10), height=self.data) # 更新柱状图数据
if __name__ == '__main__':
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())