Python-PyQt版面配置與嵌入即時動態圖
控制板讀到的訊號需要即時顯示,因此我用PyQT寫了個GUI範例,並且能即時更新圖表,畫圖的部分採用matplotlib。
上面圖表就是程式碼會顯示的即時圖,右邊是即時產生sin與cos值,左邊是cos、sin分別在x,y軸產生出來的圖形。
上面圖表就是程式碼會顯示的即時圖,右邊是即時產生sin與cos值,左邊是cos、sin分別在x,y軸產生出來的圖形。
import sys import PyQt5 import time import numpy as np from matplotlib.backends.qt_compat import QtCore, QtWidgets, is_pyqt5 if is_pyqt5(): from matplotlib.backends.backend_qt5agg import ( FigureCanvas, NavigationToolbar2QT as NavigationToolbar) else: from matplotlib.backends.backend_qt4agg import ( FigureCanvas, NavigationToolbar2QT as NavigationToolbar) from matplotlib.figure import Figure class ApplicationWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__() self._main = QtWidgets.QWidget() self.setCentralWidget(self._main) layout = QtWidgets.QGridLayout(self._main) #新增圖表 dynamic_canvas_total = FigureCanvas(Figure(figsize=(5, 3))) dynamic_canvas_x = FigureCanvas(Figure(figsize=(5, 3))) dynamic_canvas_y = FigureCanvas(Figure(figsize=(5, 3))) #將圖表加入介面 layout.addWidget(dynamic_canvas_total,1,1,2,1) #圖在第1 row 1 column為起始 共佔2 row 1 colcolumn self.addToolBar(NavigationToolbar(dynamic_canvas_total, self)) layout.addWidget(dynamic_canvas_x,1,2,1,1) #圖在第1 row 2 column為起始 共佔1 row 1 colcolumn #self.addToolBar(NavigationToolbar(dynamic_canvas_x, self)) layout.addWidget(dynamic_canvas_y,2,2,1,1) #圖在第2 row 2 column為起始 共佔1 row 1 colcolumn #self.addToolBar(QtCore.Qt.BottomToolBarArea, # NavigationToolbar(dynamic_canvas_y, self)) #繪圖 self._dynamic_total = dynamic_canvas_total.figure.subplots() self._timer_total = dynamic_canvas_total.new_timer( 100, [(self._update_canvas, (), {})]) self._timer_total.start() self._dynamic_ax = dynamic_canvas_x.figure.subplots() self._timer_x = dynamic_canvas_x.new_timer( 100, [(self._update_canvas, (), {})]) self._timer_x.start() self._dynamic_ay = dynamic_canvas_y.figure.subplots() self._timer_y = dynamic_canvas_y.new_timer( 100, [(self._update_canvas, (), {})]) self._timer_y.start() def _update_canvas(self): self._dynamic_ax.clear() t = np.linspace(0, 10, 101) # Shift the sinusoid as a function of time. self._dynamic_ax.plot(t, np.cos(t + time.time())) self._dynamic_ax.figure.canvas.draw() self._dynamic_ay.clear() t = np.linspace(0, 10, 101) # Shift the sinusoid as a function of time. self._dynamic_ay.plot(t, np.sin(t + time.time())) self._dynamic_ay.figure.canvas.draw() self._dynamic_total.scatter(np.cos(t + time.time()), np.sin(t + time.time())) self._dynamic_total.figure.canvas.draw() if __name__ == "__main__": qapp = QtWidgets.QApplication(sys.argv) app = ApplicationWindow() app.resize(1024, 768) app.setWindowTitle("振動監測") app.show() qapp.exec_()可以先看主程式的部份,就是呼叫我們定義的class並且調整一下初始大小與title,最後呈現。 而class的部分,我們使用網格layout(QGridLayout),並新增三個圖表,依序把圖加到適當位置(程式碼註解有介紹),再來用timer定期去更新我們的圖表。
留言
張貼留言