2025年4月23日 星期三

PyQt5 設計的 GUI 程式IMU 時域資料的折線圖1

 使用 PyQt5 設計的 GUI 程式,可用來:

  • ✅ 載入 homework.csv 檔案

  • ✅ 顯示 b1~b6 時域資料的折線圖(每筆間隔 0.01 秒)

  • ✅ 以 紅、藍、綠 顯示 b1b3、b4b6

  • ✅ 提供切換時間範圍(1秒、2秒、3秒)功能

  • ✅ 使用 matplotlib 進行資料繪圖


📦 套件需求

請先安裝:

bash
pip install pyqt5 matplotlib pandas

🧠 完整 Python 程式碼

python
import sys import pandas as pd import matplotlib.pyplot as plt from PyQt5.QtWidgets import ( QApplication, QWidget, QVBoxLayout, QPushButton, QFileDialog, QComboBox, QLabel ) from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure class IMUGUI(QWidget): def __init__(self): super().__init__() self.setWindowTitle('IMU CSV 時域顯示器') self.resize(800, 600) self.data = None self.fs = 100 # 0.01 sec -> 100 Hz # 建立 UI 元件 layout = QVBoxLayout() self.load_button = QPushButton('載入 CSV') self.combo = QComboBox() self.combo.addItems(['1 秒', '2 秒', '3 秒']) self.label = QLabel('目前未載入檔案') self.canvas = FigureCanvas(Figure()) self.ax = self.canvas.figure.add_subplot(111) layout.addWidget(self.load_button) layout.addWidget(self.combo) layout.addWidget(self.label) layout.addWidget(self.canvas) self.setLayout(layout) # 綁定事件 self.load_button.clicked.connect(self.load_csv) self.combo.currentIndexChanged.connect(self.update_plot) def load_csv(self): fname, _ = QFileDialog.getOpenFileName(self, '選擇 CSV 檔', '', 'CSV files (*.csv)') if fname: self.data = pd.read_csv(fname) self.label.setText(f'已載入:{fname.split("/")[-1]}') self.update_plot() def update_plot(self): if self.data is None: return duration = [1, 2, 3][self.combo.currentIndex()] samples = self.fs * duration if len(self.data) < samples: samples = len(self.data) self.ax.clear() time = [i * 0.01 for i in range(samples)] colors = ['red', 'blue', 'green'] for i in range(3): # b1~b3 self.ax.plot(time, self.data[f'b{i+1}'][:samples], color=colors[i], label=f'b{i+1}') for i in range(3, 6): # b4~b6 self.ax.plot(time, self.data[f'b{i+1}'][:samples], linestyle='--', color=colors[i-3], label=f'b{i+1}') self.ax.set_title(f'前 {duration} 秒 IMU 資料') self.ax.set_xlabel('時間 (秒)') self.ax.set_ylabel('IMU 數值') self.ax.legend() self.canvas.draw() if __name__ == '__main__': app = QApplication(sys.argv) gui = IMUGUI() gui.show() sys.exit(app.exec_())

🎨 顯示說明

  • b1~b3紅、藍、綠 實線顯示

  • b4~b6紅、藍、綠 虛線顯示(對應前面三色)

  • 可即時切換 1 秒、2 秒、3 秒 顯示長度

  • 讀取後自動更新圖表

沒有留言:

張貼留言