Skip to content

Instantly share code, notes, and snippets.

@tianrking
Last active August 7, 2023 07:08
Show Gist options
  • Save tianrking/cef3d81825e14a53af5e1f9883506444 to your computer and use it in GitHub Desktop.
Save tianrking/cef3d81825e14a53af5e1f9883506444 to your computer and use it in GitHub Desktop.
Pyside6 & matplotlib
import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QLabel
from PySide6.QtCore import QThread, Signal
import serial
import numpy as np
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import random
import time
class SerialThread(QThread):
data_received = Signal(float)
data2_received = Signal(float)
def run(self):
# with serial.Serial('COM3', 9600) as ser:
# while True:
# data = float(ser.readline().decode('utf-8').strip())
# self.data_received.emit(data)
while True:
data = random.uniform(0, 100)
self.data_received.emit(data)
data2 = random.uniform(-10, 0)
self.data2_received.emit(data2)
time.sleep(0.1)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('w0x7ce')
self.data = np.array([])
self.data2 = np.array([])
# MAX data
self.max_data_length = 100
self.total_data_count = 0
self.figure = Figure()
self.canvas = FigureCanvas(self.figure)
self.ax = self.figure.add_subplot(111)
self.ax.set_title("Real-time data plot")
self.ax.set_xlabel("Samples")
self.ax.set_ylabel("Value")
self.line, = self.ax.plot(self.data, 'r-', label='Data 1')
self.line2, = self.ax.plot(self.data2, 'b-', label='Data 2')
#self.ax.legend()
self.ax.legend(loc='upper left')
self.data_count_label = QLabel()
layout = QVBoxLayout()
layout.addWidget(self.canvas)
layout.addWidget(self.data_count_label)
container = QWidget()
container.setLayout(layout)
self.setCentralWidget(container)
self.serial_thread = SerialThread()
self.serial_thread.data_received.connect(self.update_plot)
self.serial_thread.data2_received.connect(self.update_plot2)
self.serial_thread.start()
def update_plot(self, data):
self.data = np.append(self.data, data)
self.total_data_count += 1
#MAX data
if len(self.data) > self.max_data_length:
self.data = self.data[-self.max_data_length:]
self.line.set_ydata(self.data)
self.line.set_xdata(range(len(self.data)))
self.ax.relim()
self.ax.autoscale_view(True, True, True)
self.canvas.draw()
# Update data count label
self.data_count_label.setText(f"Data count: {self.total_data_count}")
def update_plot2(self, data):
self.data2 = np.append(self.data2, data)
if len(self.data2) > self.max_data_length:
self.data2 = self.data2[-self.max_data_length:]
self.line2.set_ydata(self.data2)
self.line2.set_xdata(range(len(self.data2)))
self.ax.relim()
self.ax.autoscale_view(True, True, True)
self.canvas.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment