Skip to content

Instantly share code, notes, and snippets.

@jonathanschilling
Created September 30, 2020 08:27
Show Gist options
  • Save jonathanschilling/5adec32575a9c02a76d353b6016a7aa8 to your computer and use it in GitHub Desktop.
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.
#!/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