Created
September 30, 2020 08:27
-
-
Save jonathanschilling/5adec32575a9c02a76d353b6016a7aa8 to your computer and use it in GitHub Desktop.
A PyQt5 demo with embedded matplotlib figure and toolbar and a QSlider to modify the plot data.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
import sys | |
import numpy as np | |
from PyQt5.QtCore import Qt | |
from PyQt5.QtWidgets import QWidget, QMainWindow, QVBoxLayout, QSlider, QApplication | |
import matplotlib | |
matplotlib.use('QT5Agg') | |
import matplotlib.pylab as plt | |
from matplotlib.backends.backend_qt5agg import FigureCanvas | |
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar | |
class sliderdemo(QMainWindow): | |
N = 1000 | |
x_data = np.linspace(0,1, N) | |
freq = 1.0 | |
y_data = np.sin(2.0*np.pi*freq*x_data) | |
fig = None | |
ax1 = None | |
pltLine = None | |
def __init__(self, parent = None): | |
super(sliderdemo, self).__init__(parent) | |
layout = QVBoxLayout() | |
# create plot and put into layout | |
self.fig, self.ax1 = plt.subplots() | |
self.plotWidget = FigureCanvas(self.fig) | |
layout.addWidget(self.plotWidget) | |
# add toolbar | |
self.addToolBar(Qt.BottomToolBarArea, NavigationToolbar(self.plotWidget, self)) | |
self.sl = QSlider(Qt.Horizontal) | |
self.sl.setMinimum(1) | |
self.sl.setMaximum(30) | |
self.sl.setValue(10) | |
self.sl.setTickPosition(QSlider.TicksBelow) | |
self.sl.setTickInterval(1) | |
# initial update so that we have some plotted data on startup | |
self.valuechange() | |
# update along with slider movement | |
layout.addWidget(self.sl) | |
self.sl.valueChanged.connect(self.valuechange) | |
# central widget for QMainWindow | |
centralWidget = QWidget() | |
centralWidget.setLayout(layout) | |
self.setCentralWidget(centralWidget) | |
self.setWindowTitle("PyQt5 QSlider demo") | |
def valuechange(self): | |
# obtain value from slider | |
self.freq = self.sl.value() | |
# recompute data | |
self.y_data = np.sin(2.0*np.pi*self.freq*self.x_data) | |
if self.pltLine is None: | |
# initial plot of data | |
self.pltLine = self.ax1.plot(self.x_data, self.y_data) | |
else: | |
# update data in plot and redraw | |
self.pltLine[0].set_data(self.x_data, self.y_data) | |
self.fig.canvas.draw() | |
self.fig.canvas.flush_events() | |
if __name__ == '__main__': | |
app = QApplication(sys.argv) | |
ex = sliderdemo() | |
ex.show() | |
sys.exit(app.exec_()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment