Embedding a Matplotlib plot into PyQt - python

I have been trying unsuccessfully to embed a matplotlib into PyQt for the past few days and before you say anything, I have been to every site possible to help me.
When I run the code it produces a 1 by 1 graph but doesn't actually graph anything
from __future__ import unicode_literals
import sys
import os
import random
from matplotlib.backends import qt4_compat
use_pyside = qt4_compat.QT_API == qt4_compat.QT_API_PYSIDE
if use_pyside:
from PySide import QtGui, QtCore
else:
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import numpy as np
import scipy.io
import os
import pandas as pd
progname = os.path.basename(sys.argv[0])
progversion = "0.1"
class MyMplCanvas(FigureCanvas):
"""Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
# We want the axes cleared every time plot() is called
self.axes.hold(False)
self.compute_initial_figure()
#
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def compute_initial_figure(self):
pass
class MyStaticMplCanvas(MyMplCanvas):
def extract_data(self, name):
#setting up lists
Stim_trig = []
Stim_order = []
Sch_wav = []
data = scipy.io.loadmat(name)
for k,v in data.items():
#Sends Sch_wav data to a list
if "Sch_wav" in k:
for d in (((v[0])[0])[4]):
Sch_wav.append(d[0])
#Sends StimTrig to a list
if k=="StimTrig":
for g in (((v[0])[0])[4]):
Stim_trig.append(g[0])
Stim_trig.append(Stim_trig[-1]+1)
#Sends Stim order to a list
for w in (((v[0])[0])[5]):
Stim_order.append(w[0])
superdata = []
#Prepares grouping stimuli and trigger
for i in range(len(Stim_trig)-1):
fire = []
for p in Sch_wav:
if p > Stim_trig[i] and p < Stim_trig[i+1]:
fire.append(p - Stim_trig[i])
superdata.append([Stim_order[i],fire])
#sorts all the data
superdata.sort()
alladdedup = [[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[62]]
count = 0
for d in superdata:
if d[0] == (alladdedup[count])[0]:
for j in d[1]:
((alladdedup)[count]).append(j)
else:
count += 1
#places time stamps of triggers in lists for each trigger
for l in alladdedup:
l.pop(0)
l.sort()
#removes title and sorts data
ffmsb = []
#finds number of firings for each milisecond bin
for v in alladdedup:
fmsb = []
for b in range(100):
msbc = b/100
msb = []
for t in v:
if t > msbc and t < msbc + 0.01:
msb.append(t)
fmsb.append(len(msb))
ffmsb.append(fmsb)
#returns list of stimuli firings per milisecond bin
return ffmsb
#End of Sorting Code
#Start of Graphing Code
def stimuli_graph(self):
#Set file to use and the stimuli wanted. In this case stimuli 1 is being used
filename = ("654508_rec02_all.mat"[1])
self.extract_data(filename)
#Creates parameters for index
numberlist = []
for i in range(100):
numberlist.append(i/100)
#Adjusts the y-axis max according to the y-axis of a graphed stimuli e.g. If plotted graph has y-axis of 10
# then it'll be adjusted by 1.3. So it'll change to 13
x = 0
for i in filename:
if i > x:
x = i*1.3
#Dataframes the data from extract_data
c = pd.Series(filename, index = numberlist)
neurons = pd.DataFrame((c))
#This is where the data gets graphed. I know this is where the problem occurs, I just don't know where
#This code is a mess and for that I am sorry
times = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
ax = neurons.plot(
kind = 'bar',
title = 'Number of neurons firing for stimuli '+str(1),
legend = False,
xlim = (0, 100),
ylim = (0, x),
width = 1,
position = 0,
edgecolor = 'white',
xticks = (np.arange(min(times), max(times), 10)) #Makes the x-axis label in increments of 0.1 instead of 0.01
)
ax.set_xlabel('Time (s)')
ax.set_ylabel('Neurons Firing')
t = arange(0, 100, 1)
self.axes.plot(t, neurons)
class ApplicationWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.setWindowTitle("application main window")
self.file_menu = QtGui.QMenu('&File', self)
self.file_menu.addAction('&Quit', self.fileQuit,
QtCore.Qt.CTRL + QtCore.Qt.Key_Q)
self.menuBar().addMenu(self.file_menu)
self.help_menu = QtGui.QMenu('&Help', self)
self.menuBar().addSeparator()
self.menuBar().addMenu(self.help_menu)
self.main_widget = QtGui.QWidget(self)
l = QtGui.QVBoxLayout(self.main_widget)
sc = MyStaticMplCanvas(self.main_widget, width=5, height=4, dpi=100)
l.addWidget(sc)
self.main_widget.setFocus()
self.setCentralWidget(self.main_widget)
self.statusBar().showMessage("All hail matplotlib!", 2000)
def fileQuit(self):
self.close()
def closeEvent(self, ce):
self.fileQuit()
qApp = QtGui.QApplication(sys.argv)
aw = ApplicationWindow()
aw.setWindowTitle("%s" % progname)
aw.show()
sys.exit(qApp.exec_())
#qApp.exec_()
The data used in the graph is extracted from an external file

Related

New signal connects to old slot instead of separate slot

I am trying to tag x-spans of a data trace and populate a table with tagNames, starting x value, and the ending x value. I am using a dictionary of 'highlight' objects to keep track of the x-spans in case they need to be edited (increased or decreased) later. The dictionary maps the x Start value to the highlight object, as the x start values are expected to be unique (there is no overlap of x-spans for the tagging).
In order to do this, I am emitting a signal when the user beings to edit a cell on the table. The function that the first signal connects to emits another signal (ideally for whether the xStart is changed vs. the xEnd, but I have only implemented the xStart thus far), which actually changes the appearance of the span to match the edit.
I asked a similar question a few weeks ago but wasn't able to get an answer. The old question is here: PyQT5 slot parameters not updating after first call. In response to the tips given there, I wrote the following example:
import sys
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.widgets as mwidgets
from functools import partial
class Window(QMainWindow):
def __init__(self, parent = None):
super(Window, self).__init__(parent)
self.resize(1600, 800)
self.MyUI()
def MyUI(self):
canvas = Canvas(self, width=14, height=12, dpi=100)
canvas.move(0,0)
#use this object in the dictionary to hold onto all the spans.
class highlight:
def __init__(self, tag, xStart, xEnd, highlightObj):
self.tag = tag
self.xStart = xStart
self.xEnd = xEnd
self.highlightObj = highlightObj
class Canvas(FigureCanvas):
def __init__(self, parent, width = 14, height = 12, dpi = 100):
Plot = Figure(figsize=(width, height), dpi=dpi)
self.Axes = Plot.add_subplot(111)
self.Axes.set_position([0.05, 0.58, 0.66, 0.55])
self.rowCount = 0
super().__init__(Plot)
self.setParent(parent)
##add all relevant lines to plot
self.Axes.plot([0,1,2,3,4], [3, 4, 5, 6, 7])
self.Axes.set_xlabel('Frame', fontsize = 10)
self.Axes.grid()
self.Axes.set_aspect(1)
Plot.canvas.draw()
self.highlights = {} #empty dictionary to store all the tags.
##define a table to hold the values postselection
self.taggingTable = QTableWidget(self)
self.taggingTable.setColumnCount(3)
self.taggingTable.setRowCount(100)
self.taggingTable.setGeometry(QRect(1005,85, 330, 310))
self.taggingTable.setHorizontalHeaderLabels(['Behavior','Start Frame', 'End Frame'])
Canvas.span = mwidgets.SpanSelector(self.Axes, self.onHighlight, "horizontal",
interactive = True, useblit=True, props=dict(alpha=0.5, facecolor="blue"),)
self.draw_idle()
self.taggingTable.selectionModel().selectionChanged.connect(self.onCellSelect)
self.draw_idle()
##highlighting adds a highlight item to the directory.
def onHighlight(self, xStart, xEnd):
tagName = "No Tag"
self.taggingTable.setItem(self.rowCount, 0, QTableWidgetItem(tagName))
self.taggingTable.setItem(self.rowCount, 1, QTableWidgetItem(str(int(xStart))))
self.taggingTable.setItem(self.rowCount, 2, QTableWidgetItem(str(int(xEnd))))
self.rowCount = self.rowCount + 1
highlightObj = self.Axes.axvspan(xStart, xEnd, color = 'blue', alpha = 0.5)
self.highlights[int(xStart)] = highlight(tagName, xStart, xEnd, highlightObj)
self.draw_idle()
def xStartChanged(self, xStart, rowVal):
if self.inCounter == 0:
print("xStart in slot: ", xStart)
xEnd = self.highlights[xStart].xEnd
xStartNew = int(self.taggingTable.item(rowVal, 1).text())
self.highlights[xStart].highlightObj.remove() #remove old from the plot
del self.highlights[xStart] #remove old from directory
highlightObj = self.Axes.axvspan(xStartNew, xEnd, color = 'blue', alpha = 0.5) #add new to plot
self.highlights[xStartNew] = highlight("No tagName", xStartNew, xEnd, highlightObj) #add new to directory
self.taggingTable.clearSelection() #deselect value from table
self.draw_idle()
self.inCounter = self.inCounter + 1
def onCellSelect(self):
index = self.taggingTable.selectedIndexes()
if len(index) != 0:
rowVal = index[0].row()
if not (self.taggingTable.item(rowVal, 1) is None):
xStart = int(self.taggingTable.item(rowVal, 1).text())
print("--------------")
print("xStart in signal: ", xStart)
self.inCounter = 0
self.taggingTable.itemChanged.connect(lambda: self.xStartChanged(xStart, rowVal))
app = QApplication(sys.argv)
window = Window()
window.show()
app.exec()
A test I run is when I highlight two traces:
and then I successfully change a first trace:
However, when I attempt to edit the second trace, the program crashes:
To debug, I tried to check what the signals were emitting and receiving. it produces the following output:
--------------
xStart in signal: 0
xStart in slot: 0 ##First slot call gets correct signal
--------------
xStart in signal: 3
xStart in slot: 0 ## Second slot gets the first signal instead of the second
Traceback (most recent call last):
File "//Volumes/path/file.py", line 105, in <lambda>
self.taggingTable.itemChanged.connect(lambda: self.xStartChanged(xStart, rowVal))
File "//Volumes/path/file.py", line 86, in xStartChanged
xEnd = self.highlights[xStart].xEnd
KeyError: 0
zsh: abort python Volumes/path file.py
I tried to use information online on unique connections but I am not sure how to implement them. Thank you in advance for any help.
It seems that what you need is table-widget signal that emits an item and its old text value whenever a change is made to a specific column. Unfortunately, the itemChanged signal isn't really suitable, because it doesn't indicate what changed, and it doesn't supply the previous value. So, to work around this limitation, one solution would be to subclass QTableWidget / QTableWidgetItem and emit a custom signal with the required parameters. This will completely side-step the issue with multiple signal-slot connections.
The implementation of the subclasses is quite simple:
class TableWidgetItem(QTableWidgetItem):
def setData(self, role, value):
oldval = self.text()
super().setData(role, value)
if role == Qt.EditRole and self.text() != oldval:
table = self.tableWidget()
if table is not None:
table.itemTextChanged.emit(self, oldval)
class TableWidget(QTableWidget):
itemTextChanged = pyqtSignal(TableWidgetItem, str)
Below is basic a demo based on your example that shows how to use them. (Note that I have made no attempt to handle xEnd as well, as that would go beyond the scope of the immediate issue).
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.widgets as mwidgets
class Window(QMainWindow):
def __init__(self, parent = None):
super(Window, self).__init__(parent)
self.resize(1600, 800)
self.MyUI()
def MyUI(self):
canvas = Canvas(self, width=14, height=12, dpi=100)
canvas.move(0,0)
# CUSTOM SUBCLASSES
class TableWidgetItem(QTableWidgetItem):
def setData(self, role, value):
oldval = self.text()
super().setData(role, value)
if role == Qt.EditRole and self.text() != oldval:
table = self.tableWidget()
if table is not None:
table.itemTextChanged.emit(self, oldval)
class TableWidget(QTableWidget):
itemTextChanged = pyqtSignal(TableWidgetItem, str)
#use this object in the dictionary to hold onto all the spans.
class highlight:
def __init__(self, tag, xStart, xEnd, highlightObj):
self.tag = tag
self.xStart = xStart
self.xEnd = xEnd
self.highlightObj = highlightObj
class Canvas(FigureCanvas):
def __init__(self, parent, width = 14, height = 12, dpi = 100):
Plot = Figure(figsize=(width, height), dpi=dpi)
self.Axes = Plot.add_subplot(111)
self.Axes.set_position([0.05, 0.58, 0.66, 0.55])
self.rowCount = 0
super().__init__(Plot)
self.setParent(parent)
##add all relevant lines to plot
self.Axes.plot([0,1,2,3,4], [3, 4, 5, 6, 7])
self.Axes.set_xlabel('Frame', fontsize = 10)
self.Axes.grid()
self.Axes.set_aspect(1)
Plot.canvas.draw()
self.highlights = {} #empty dictionary to store all the tags.
##define a table to hold the values postselection
# USE CUSTOM TABLE SUBCLASS
self.taggingTable = TableWidget(self)
self.taggingTable.setColumnCount(3)
self.taggingTable.setRowCount(100)
self.taggingTable.setGeometry(QRect(1005,85, 330, 310))
self.taggingTable.setHorizontalHeaderLabels(['Behavior','Start Frame', 'End Frame'])
# CONNECT TO CUSTOM SIGNAL
self.taggingTable.itemTextChanged.connect(self.xStartChanged)
Canvas.span = mwidgets.SpanSelector(self.Axes, self.onHighlight, "horizontal",
interactive = True, useblit=True, props=dict(alpha=0.5, facecolor="blue"),)
self.draw_idle()
##highlighting adds a highlight item to the directory.
def onHighlight(self, xStart, xEnd):
tagName = "No Tag"
self.taggingTable.setItem(self.rowCount, 0, QTableWidgetItem(tagName))
# USE CUSTOM ITEM SUBCLASS
self.taggingTable.setItem(self.rowCount, 1, TableWidgetItem(str(int(xStart))))
self.taggingTable.setItem(self.rowCount, 2, QTableWidgetItem(str(int(xEnd))))
self.rowCount = self.rowCount + 1
highlightObj = self.Axes.axvspan(xStart, xEnd, color = 'blue', alpha = 0.5)
self.highlights[int(xStart)] = highlight(tagName, xStart, xEnd, highlightObj)
self.draw_idle()
def xStartChanged(self, item, oldVal):
try:
# VALIDATE NEW VALUES
xStart = int(oldVal)
xStartNew = int(item.text())
except ValueError:
pass
else:
print("xStart in slot: ", xStart)
xEnd = self.highlights[xStart].xEnd
self.highlights[xStart].highlightObj.remove() #remove old from the plot
del self.highlights[xStart] #remove old from directory
highlightObj = self.Axes.axvspan(xStartNew, xEnd, color = 'blue', alpha = 0.5) #add new to plot
self.highlights[xStartNew] = highlight("No tagName", xStartNew, xEnd, highlightObj) #add new to directory
self.taggingTable.clearSelection() #deselect value from table
self.draw_idle()
app = QApplication(sys.argv)
window = Window()
window.show()
app.exec()

Why are my plots not appearing with set_data using Tkinter?

I am trying to improve my plotting function. I want to plot data using my plotGraph function coming from an EEG board in real-time, pulling samples from an LSL # 250Hz. Previously, I had a functional version using the regular self.ax.plot(x,y), clearing the data with self.ax.clear() every time the plot needed to refresh. Nonetheless, some profiling showed that my code was taking way too much time to plot in comparison to the rest of it.
One of the suggestions I got was to use set_data instead of plot and clear. I have multiple lines of data that I want to plot simultaneously, so I tried following Matplotlib multiple animate multiple lines, which you can see below (adapted code). Also, I was told to use self.figure.canvas.draw_idle(), which I tried, but I'm not sure if I did it correctly.
Unfortunately, it didn't work, the graph is not updating and I can't seem to find why. I'm aware that the source I just mentioned uses animation.FuncAnimation but I'm not sure that would be the problem. Is it?
Any ideas of why none of my lines are showing in my canvas' graph?
import tkinter as tk
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
class AppWindow:
def plotGraph(self, x, y):
for lnum,line in enumerate(self.lines):
line.set_data(x[:], y[:, lnum])
self.figure.canvas.draw_idle()
plt.ylabel('Magnitude', fontsize = 9, color = tx_color)
plt.xlabel('Freq', fontsize = 9, color = tx_color)
self.figure.canvas.draw()
def __init__(self):
self.root = tk.Tk() #start of application
self.canvas = tk.Canvas(self.root, height = 420, width = 780, bg =
bg_color, highlightthickness=0)
self.canvas.pack(fill = 'both', expand = True)
self.figure = plt.figure(figsize = (5,6), dpi = 100)
self.figure.patch.set_facecolor(sc_color)
self.ax = self.figure.add_subplot(111)
self.ax.clear()
self.line, = self.ax.plot([], [], lw=1, color = tx_color)
self.line.set_data([],[])
#place graph
self.chart_type = FigureCanvasTkAgg(self.figure, self.canvas)
self.chart_type.get_tk_widget().pack()
self.lines = []
numchan = 8 #let's say I have 8 channels
for index in range(numchan):
lobj = self.ax.plot([],[], lw=2, color=tx_color)[0]
self.lines.append(lobj)
for line in self.lines:
line.set_data([],[])
def start(self):
self.root.mainloop()
You chart is empty because you are plotting empty arrays:
line.set_data([],[])
If you fill in the line arrays, the chart plots correctly.
Try this code. It updates the chart with new random data every second.
import tkinter as tk
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
import random
bg_color='grey'
tx_color='green'
sc_color='linen'
numchan = 8
chlen = 100
xvals=[(x-40)/20 for x in range(chlen)] # X coordinates
chcolors= ['gold','blue','green','maroon','red','brown','purple','cyan']
class AppWindow:
def plotGraph(self):
self.figure.canvas.draw_idle()
plt.ylabel('Magnitude', fontsize = 9, color = tx_color)
plt.xlabel('Freq', fontsize = 9, color = tx_color)
self.figure.canvas.draw()
def UpdateChannelData(self): # callback with new data
# fake random data
for i,ch in enumerate(self.chdata):
for p in range(len(ch)):
ch[p] += (random.random()-.5)/100
self.lines[i].set_data(xvals, ch)
self.plotGraph()
self.root.after(100, self.UpdateChannelData) # simulate next call
def __init__(self):
global chzero
self.root = tk.Tk() #start of application
self.canvas = tk.Canvas(self.root, height = 420, width = 780, bg = bg_color, highlightthickness=0)
self.canvas.pack(fill = 'both', expand = True)
self.figure = plt.figure(figsize = (5,6), dpi = 100)
self.figure.patch.set_facecolor(sc_color)
self.ax = self.figure.add_subplot(111)
self.ax.clear()
self.line, = self.ax.plot([], [], lw=1, color = tx_color)
self.line.set_data([],[])
#place graph
self.chart_type = FigureCanvasTkAgg(self.figure, self.canvas)
self.chart_type.get_tk_widget().pack()
self.lines = []
#numchan = 8 #let's say I have 8 channels
for index in range(numchan):
lobj = self.ax.plot([],[], lw=1, color=chcolors[index])[0]
self.lines.append(lobj)
# set flat data
self.chdata = [[0 for x in range(chlen)] for ch in range(numchan)]
self.root.after(1000, self.UpdateChannelData) # start data read
def start(self):
self.root.mainloop()
AppWindow().start()
Output:

Python scatter updating using Qt4 - Qslider

I am trying to write a GUI in Python3 using PyQt4.
For data visualization, I need to isolate a specific point on a curve plotted by the function whole_plot(). To do so, I am currently using a slider that let the GUI user choose a point of interest. When the slider_value is changed, the point is selected and plotted by calling the function point_plot().
Regarding some previous answers, I am now trying to update my graph through matplotlib.animation (cf. post python matplotlib update scatter plot from a function). But for some reasons, I still got the wrong updating, can someone help me figure out what is the problem in my code?
import sys
import numpy as np
from PyQt4 import QtGui
from PyQt4 import QtCore
import matplotlib.pyplot as plt
import matplotlib.animation
#
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
#%%
# some Arbitrary data
nbr_points = 500
my_X_data = np.linspace(-10,10,nbr_points)
my_Y_data = my_X_data**3 + 100*np.cos(my_X_data*5)
class MyWidget(QtGui.QWidget):
def __init__(self):
super(MyWidget, self).__init__()
self.initUI()
def initUI(self):
self.setGeometry(600,300,1000,600)
grid = QtGui.QGridLayout()
self.setLayout(grid)
self.figure_1 = plt.figure(figsize=(15,5))
self.canvas_1 = FigureCanvas(self.figure_1)
self.toolbar = NavigationToolbar(self.canvas_1, self)
grid.addWidget(self.canvas_1, 2,0,1,2)
grid.addWidget(self.toolbar, 0,0,1,2)
# Slider
self.slider = QtGui.QSlider(QtCore.Qt.Horizontal)
self.slider.setMinimum(0)
self.slider.setMaximum(nbr_points-1)
self.slider.setTickInterval(1)
self.slider.valueChanged.connect(self.point_plot)
# Slider info box
self.label = QtGui.QLabel(self)
grid.addWidget(self.label,4,0)
# +1 / -1 buttons
btn_plus_one = QtGui.QPushButton('+1', self)
btn_plus_one.clicked.connect(self.value_plus_one)
btn_minus_one = QtGui.QPushButton('-1', self)
btn_minus_one.clicked.connect(self.value_minus_one)
hbox = QtGui.QHBoxLayout()
hbox.addWidget(btn_minus_one)
hbox.addWidget(self.slider)
hbox.addWidget(btn_plus_one)
grid.addLayout(hbox, 3,0,1,3)
self.whole_plot()
self.point_plot()
self.show()
def whole_plot(self):
ax1 = self.figure_1.add_subplot(111)
ax1.clear()
ax1.cla()
#
ax1.plot(my_X_data,my_Y_data,'b-')
#
ax1.set_xlim([-10,10])
ax1.set_ylim([-1000,1000])
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
#
self.canvas_1.draw()
def point_plot(self):
ax1 = self.figure_1.add_subplot(111)
#
X_point, Y_point = [],[]
scat = ax1.scatter(X_point,Y_point, s=100,c='k')
def animate(i):
index_slider_value = self.slider.value()
X_point = my_X_data[index_slider_value,]
Y_point = my_Y_data[index_slider_value,]
scat.set_offsets(np.c_[X_point,Y_point])
anim = matplotlib.animation.FuncAnimation(self.figure_1,animate, frames=my_X_data, interval=200, repeat=True)
self.canvas_1.draw()
def value_plus_one(self):
# slider +1
if self.slider.value() < (my_X_data.shape[0]-1):
index_slider_value = self.slider.value() + 1
self.slider.setValue(index_slider_value)
def value_minus_one(self):
# slider -1
if self.slider.value() > 0:
index_slider_value = self.slider.value() - 1
self.slider.setValue(index_slider_value)
def main():
app = QtGui.QApplication(sys.argv)
MyWidget()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
You have to learn what is better to reuse than create, in this case you just need to create a scatter and update the data with set_offsets() when the value of the slider changes, so FuncAnimation is not necessary.
import numpy as np
from PyQt4 import QtCore, QtGui
import matplotlib.pyplot as plt
import matplotlib.animation
#
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
#%%
# some Arbitrary data
nbr_points = 500
my_X_data = np.linspace(-10,10,nbr_points)
my_Y_data = my_X_data**3 + 100*np.cos(my_X_data*5)
class MyWidget(QtGui.QWidget):
def __init__(self):
super(MyWidget, self).__init__()
self.initUI()
def initUI(self):
self.setGeometry(600,300,1000,600)
self.figure_1 = plt.figure(figsize=(15,5))
self.canvas = FigureCanvas(self.figure_1)
self.toolbar = NavigationToolbar(self.canvas, self)
# Slider
self.slider = QtGui.QSlider(minimum=0,
maximum= nbr_points-1,
orientation=QtCore.Qt.Horizontal,
tickInterval=1)
self.slider.valueChanged.connect(self.on_valueChanged)
# Slider info box
self.label = QtGui.QLabel()
# +1 / -1 buttons
btn_plus_one = QtGui.QPushButton('+1')
btn_plus_one.clicked.connect(self.value_plus_one)
btn_minus_one = QtGui.QPushButton('-1')
btn_minus_one.clicked.connect(self.value_minus_one)
grid = QtGui.QGridLayout(self)
grid.addWidget(self.canvas, 2, 0, 1, 2)
grid.addWidget(self.toolbar, 0, 0, 1, 2)
grid.addWidget(self.label, 4, 0)
hbox = QtGui.QHBoxLayout()
hbox.addWidget(btn_minus_one)
hbox.addWidget(self.slider)
hbox.addWidget(btn_plus_one)
grid.addLayout(hbox, 3, 0, 1, 3)
self.whole_plot()
def whole_plot(self):
ax = self.figure_1.add_subplot(111)
ax.clear()
ax.plot(my_X_data,my_Y_data,'b-')
ax.set_xlim([-10,10])
ax.set_ylim([-1000,1000])
ax.set_xlabel('X')
ax.set_ylabel('Y')
self.canvas.draw()
X_point, Y_point = [],[]
self.scat = ax.scatter(X_point, Y_point, s=100,c='k')
# set initial
self.on_valueChanged(self.slider.value())
#QtCore.pyqtSlot(int)
def on_valueChanged(self, value):
X_point = my_X_data[value,]
Y_point = my_Y_data[value,]
self.scat.set_offsets(np.c_[X_point,Y_point])
self.canvas.draw()
#QtCore.pyqtSlot()
def value_plus_one(self):
self.slider.setValue(self.slider.value() + 1)
#QtCore.pyqtSlot()
def value_minus_one(self):
self.slider.setValue(self.slider.value() - 1)
def main():
import sys
app = QtGui.QApplication(sys.argv)
w = MyWidget()
w.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
On the other hand QSlider will not update the value if it is less than minimum or greater than maximum

Matplotlib-Graph in PyQt5 not updating while running

I'm new here, and hope my question is right here.
I'm trying to programm a GUI where I can record some sound from the microphone and plot it in real-time, to see the left and right channel of the sound.
I'm using PyQt 5 for my GUI und Matplotlib-FigureCanvas for Plotting.
The streaming works fine, however the Plot only shows after the recording stops and does not update during recording, like it should.
In Debug-Mode I can see the plots everytime they should update, but when I run the code, the GUI freezes until the recording is done.
Is that, because the Plotting is too slow?
I tried different approaches with animate or threading, but nothing worked so far.
I would like to have a real-time-updating plot in the end, how can I achieve this? Also with longer recording?
I hope someone can help me, thanks in advance!
Here is the part of my code, where I'm recording and plotting:
import sys
from PyQt5 import QtGui, QtWidgets, QtCore
import numpy as np
import time
import pyaudio
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib.gridspec as gridspec
import matplotlib.animation as animation
class Window(QtWidgets.QMainWindow):
def __init__(self): # sort of template for rest of GUI, is always there, menubar/ mainmenu eg.
super(Window, self).__init__()
self.setGeometry(50, 50, 1500, 900)
self.setWindowTitle("PyQt Tutorial!")
self.centralwidget = QtWidgets.QWidget(self)
self.centralwidget.setObjectName("centralwidget")
self.channels = 2
self.fs = 44100 # samplerate
self.Chunks = 1024
self.tapeLength = 2 # seconds
self.tape = np.empty(self.fs * self.tapeLength) * np.nan # tapes where recorded audio is stored
self.taper = np.empty(self.fs * self.tapeLength) * np.nan
self.tapel = np.empty(self.fs * self.tapeLength) * np.nan
self.home()
def home(self):
btn = QtWidgets.QPushButton("Stream and Plot", self) # Button to start streaming
btn.clicked.connect(self.plot)
btn.resize(btn.sizeHint())
btn.move(100, 100)
self.scrollArea = QtWidgets.QScrollArea(self)
self.scrollArea.move(75, 400)
self.scrollArea.resize(600, 300)
self.scrollArea.setWidgetResizable(False)
self.scrollArea2 = QtWidgets.QScrollArea(self)
self.scrollArea2.move(775, 400)
self.scrollArea2.resize(600, 300)
self.scrollArea2.setWidgetResizable(False)
self.scrollArea.horizontalScrollBar().valueChanged.connect(self.scrollArea2.horizontalScrollBar().setValue)
self.scrollArea2.horizontalScrollBar().valueChanged.connect(self.scrollArea.horizontalScrollBar().setValue)
self.figure = Figure((15, 2.8), dpi=100) # figure instance (to plot on) F(width, height, ...)
self.canvas = FigureCanvas(self.figure)
self.scrollArea.setWidget(self.canvas)
self.toolbar = NavigationToolbar(self.canvas, self.scrollArea)
self.canvas2 = FigureCanvas(self.figure)
self.scrollArea2.setWidget(self.canvas2)
self.toolbar2 = NavigationToolbar(self.canvas2, self.scrollArea2)
self.gs = gridspec.GridSpec(1, 1)
self.ax = self.figure.add_subplot(self.gs[0])
self.ax2 = self.figure.add_subplot(self.gs[0])
self.figure.subplots_adjust(left=0.05)
self.ax.clear()
def start_streamsignal(self, start=True):
# open and start the stream
if start is True:
print("start Signals")
self.p = pyaudio.PyAudio()
self.stream = self.p.open(format=pyaudio.paFloat32, channels=self.channels, rate=self.fs, input_device_index=1,
output_device_index=5, input=True, frames_per_buffer=self.Chunks)
print("recording...")
def start_streamread(self):
"""return values for Chunks of stream"""
data = self.stream.read(self.Chunks)
npframes2 = np.array(data).flatten()
npframes2 = np.fromstring(npframes2, dtype=np.float32)
norm_audio2 = (npframes2 / np.max(np.abs(npframes2))) # normalize
left2 = norm_audio2[::2]
right2 = norm_audio2[1::2]
print(norm_audio2)
return left2, right2
def tape_add(self):
"""add chunks to tape"""
self.tape[:-self.Chunks] = self.tape[self.Chunks:]
self.taper = self.tape
self.tapel = self.tape
self.taper[-self.Chunks:], self.tapel[-self.Chunks:] = self.start_streamread()
def plot(self, use_blit=True):
# Plot the Tape and update chunks
print('Plotting')
self.start_streamsignal(start=True)
start = True
for duration in range(0, 15, 1):
plotsec = 1
time.sleep(2)
self.timeArray = np.arange(self.taper.size)
self.timeArray = (self.timeArray / self.fs) * 1000 # scale to milliseconds
self.tape_add()
# self.canvas.draw()
while start is True and plotsec < 3:
# self.ani = animation.FuncAnimation(self.figure, self.animate, interval=25, blit=True)
self.ax2.plot(self.taper, '-b')
self.canvas.draw()
self.ax2.clear()
self.ax2.plot(self.tapel, 'g-')
self.canvas2.draw()
plotsec += 1
def animate(self):
self.line.set_xdata(self.taper)
return self.line,
def main():
app = QtWidgets.QApplication(sys.argv)
GUI = Window()
GUI.show()
sys.exit(app.exec_())
main()
I do have severe problems understanding the complete code as to what all the stuff in there should actually do. So all I can tell for now is that you may want to get rid of the loops and use FuncAnimation to display the animation.
def plot(self, use_blit=True):
# Plot the Tape and update chunks
print('Plotting')
self.start_streamsignal(start=True)
start = True
self.line, = self.ax2.plot([],[], '-b')
self.ax.set_xlim(0, len(self.tape))
self.ax2.set_xlim(0, len(self.tape))
self.ax.set_ylim(-3, 3)
self.ax2.set_ylim(-3, 3)
self.ani = animation.FuncAnimation(self.figure, self.animate, frames=100,
interval=25, blit=use_blit)
def animate(self,i):
self.timeArray = np.arange(self.taper.size)
self.timeArray = (self.timeArray / self.fs) * 1000 # scale to milliseconds
self.tape_add()
self.line.set_data(range(len(self.taper)),self.taper)
return self.line,
Thanks for all the Help, here is the now working code, if someone is interested:
import sys
from PyQt5 import QtGui, QtWidgets, QtCore
import numpy as np
import time
import pyaudio
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib.gridspec as gridspec
import matplotlib.animation as animation
class Window(QtWidgets.QMainWindow):
def __init__(self): # sort of template for rest of GUI, is always there, menubar/ mainmenu eg.
super(Window, self).__init__()
self.setGeometry(50, 50, 1500, 900)
self.setWindowTitle("PyQt Tutorial!")
self.centralwidget = QtWidgets.QWidget(self)
self.centralwidget.setObjectName("centralwidget")
self.channels = 2
self.fs = 44100 # samplerate
self.Chunks = 1024
self.tapeLength = 2 # seconds
self.tape = np.empty(self.fs * self.tapeLength) * np.nan # tapes where recorded audio is stored
self.home()
def home(self):
btn = QtWidgets.QPushButton("Stream and Plot", self) # Button to start streaming
btn.clicked.connect(self.plot)
btn.resize(btn.sizeHint())
btn.move(100, 100)
self.scrollArea = QtWidgets.QScrollArea(self)
self.scrollArea.move(75, 400)
self.scrollArea.resize(600, 300)
self.scrollArea.setWidgetResizable(False)
self.scrollArea2 = QtWidgets.QScrollArea(self)
self.scrollArea2.move(775, 400)
self.scrollArea2.resize(600, 300)
self.scrollArea2.setWidgetResizable(False)
self.scrollArea.horizontalScrollBar().valueChanged.connect(self.scrollArea2.horizontalScrollBar().setValue)
self.scrollArea2.horizontalScrollBar().valueChanged.connect(self.scrollArea.horizontalScrollBar().setValue)
self.figure = Figure((15, 2.8), dpi=100) # figure instance (to plot on) F(width, height, ...)
self.canvas = FigureCanvas(self.figure)
self.scrollArea.setWidget(self.canvas)
self.toolbar = NavigationToolbar(self.canvas, self.scrollArea)
self.canvas2 = FigureCanvas(self.figure)
self.scrollArea2.setWidget(self.canvas2)
self.toolbar2 = NavigationToolbar(self.canvas2, self.scrollArea2)
self.gs = gridspec.GridSpec(1, 1)
self.ax = self.figure.add_subplot(self.gs[0])
self.ax2 = self.figure.add_subplot(self.gs[0])
self.figure.subplots_adjust(left=0.05)
self.ax.clear()
def start_streamsignal(self, start=True):
# open and start the stream
if start is True:
print("start Signals")
self.p = pyaudio.PyAudio()
self.stream = self.p.open(format=pyaudio.paFloat32, channels=self.channels, rate=self.fs, input_device_index=1,
output_device_index=5, input=True, frames_per_buffer=self.Chunks)
print("recording...")
def start_streamread(self):
"""return values for Chunks of stream"""
data = self.stream.read(self.Chunks)
npframes2 = np.array(data).flatten()
npframes2 = np.fromstring(npframes2, dtype=np.float32)
norm_audio2 = (npframes2 / np.max(np.abs(npframes2))) # normalize
left2 = norm_audio2[::2]
right2 = norm_audio2[1::2]
print(norm_audio2)
return left2, right2
def tape_add(self):
"""add chunks to tape"""
self.tape[:-self.Chunks] = self.tape[self.Chunks:]
self.taper = self.tape
self.tapel = self.tape
self.taper[-self.Chunks:], self.tapel[-self.Chunks:] = self.start_streamread()
def plot(self, use_blit=True):
# Plot the Tape and update chunks
print('Plotting')
self.start_streamsignal(start=True)
start = True
for duration in range(0, 15, 1):
QtWidgets.QApplication.processEvents()
plotsec = 1
time.sleep(2)
self.timeArray = np.arange(self.taper.size)
self.timeArray = (self.timeArray / self.fs) * 1000 # scale to milliseconds
self.tape_add()
while start is True and plotsec < 3:
self.ax.plot(self.taper, '-b')
self.canvas.draw()
self.ax2.clear()
self.ax2.plot(self.tapel, 'g-')
self.canvas2.draw()
plotsec += 1
def main():
app = QtWidgets.QApplication(sys.argv)
GUI = Window()
GUI.show()
sys.exit(app.exec_())
main()

matplotlib and pyqt5 - refresh with button handle

I am a newbie in Python programming, I have started recently.
I am also discovering OOP, I was mostly programming embedded software based on ASM and C languages.
I have a small project where I need to read a file, get the data and "clean" them. These data are plot on a figure in Cartesian and in Polar coordinate. So far I achieved to grab examples of code here and there and to make the interface with pyQt5 and integrate both matplotlib canvases on them.
I have created a button called 'clean' when pressed it creates an event which is working, which clean the data but so far I didn't achieve to refresh the canvasses with the cleaned data.
I think that I got lost with the classes, functions and variables in the OOP of the pyQt integration.
Can somebody help me to see the main structure of the program and to pooint out my issue?
I also know that my python code is not that 'clean' and that I am not using the best of it and I verbose quite a lot... This come from C background.
See below code, I have removed the data treatment from the file. I need to plot the following list of list called LDTvalue[][], I have two graph on one plot which is the list of LDTvalue[0] and LDTvalue[6]:
I figure out that I cannot change any widget when calling the button even clicked. The window title change but not the widgets label for example. So this is where I have a strong suspicion of messing up with the classes and objects functions.
### UPDATE, I have copied the complete code, a bit dirty, but was a first try :) ###
import sys
import matplotlib
matplotlib.use("Qt5Agg")
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
from numpy import arange, sin, cos, pi, radians
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
LDTheader = {'Company': 'xxx','Type_ind': 0,'Symmetry': 0, 'Mc': 0, 'Dc': 0 , 'Ng': 0, 'Dg': 0}
LDTline = list()
LDTCplane = list()
LDTCvalue = list()
LDTvalue = list()
LDTvalue2 = list()
LDTtemplist = list()
LDTfile = open('01.ldt')
for line in LDTfile :
LDTline.append(line.strip())
LDTheader['Company'] = LDTline[0];
LDTheader['Type_ind'] = LDTline[1];
LDTheader['Symmetry'] = LDTline[2];
LDTheader['Mc'] = int(LDTline[3]);
LDTheader['Dc'] = float(LDTline[4]);
LDTheader['Ng'] = int(LDTline[5]);
LDTheader['Dg'] = float(LDTline[6]);
print("Company name:", LDTheader['Company'])
print("Type indicator:", LDTheader['Type_ind'])
print("Symmetry:", LDTheader['Symmetry'])
print("Mc:", LDTheader['Mc'])
print("Dc", LDTheader['Dc'])
print("Ng:", LDTheader['Ng'])
print("Dg:", LDTheader['Dg'])
if LDTheader['Type_ind'] == '1' :
print('1 - point source with symmetry about the vertical axis')
elif LDTheader['Type_ind'] == '2' :
print('2 - linear luminaire')
elif LDTheader['Type_ind'] == '3' :
print('3 - point source with any other symmetry')
else: print('Error in source type indicator!')
if LDTheader['Symmetry'] == '0' :
print('0 - no symmetry')
elif LDTheader['Symmetry'] == '1' :
print('1 - symmetry about the vertical axis')
elif LDTheader['Symmetry'] == '2' :
print('2- symmetry to plane C0-C180')
elif LDTheader['Symmetry'] == '3' :
print('3- symmetry to plane C90-C270')
elif LDTheader['Symmetry'] == '4' :
print('4- symmetry to plane C0-C180 and to plane C90-C270')
else: print('Error in symmetry paramater!')
for i in range(42,42+LDTheader['Mc']) :
LDTCplane.append(LDTline[i])
for i in range(42+LDTheader['Mc'],42+LDTheader['Mc']+LDTheader['Ng']) :
LDTCvalue.append(float(LDTline[i]))
#Separate all the values of the different Cplane in a list of a list called LDTvalue
#print(int(LDTheader['Mc']/int(LDTheader['Symmetry']))+1)
for j in range(0,int(LDTheader['Mc']/int(LDTheader['Symmetry']))+1):
if LDTheader['Symmetry'] == '4':
for i in range(1,LDTheader['Ng']):
LDTtemplist.append(float(LDTline[42+LDTheader['Ng']*(j+1)+LDTheader['Mc']+(LDTheader['Ng']-i)]))
for i in range(0,LDTheader['Ng']-1):
LDTtemplist.append(float(LDTline[42+LDTheader['Ng']*(j+1)+LDTheader['Mc']+(i)]))
LDTvalue.append(list(LDTtemplist))
del LDTtemplist
LDTtemplist = list()
if LDTheader['Symmetry'] == '4':
for i in range(1,LDTheader['Ng']):
LDTtemplist.append(float(LDTline[42+LDTheader['Ng']+LDTheader['Mc']+(LDTheader['Ng']-i)]))
for i in range(0,LDTheader['Ng']-1):
LDTtemplist.append(float(LDTline[42+LDTheader['Ng']+LDTheader['Mc']+(i)]))
LDTvalue2 = LDTtemplist
del LDTtemplist
LDTtemplist = list()
class MyPDiagram(FigureCanvas):
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111,projection='polar')
# We want the axes cleared every time plot() is called
#self.axes.hold(False)
t = arange(-180,180,LDTheader['Dg'])
t = radians(t)
self.axes.plot(t, LDTvalue[0], color='r', linewidth=1)
self.axes.plot(t, LDTvalue[6], color='b', linewidth=1)
self.axes.set_theta_zero_location("S")
self.axes.grid(True)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,
QSizePolicy.Expanding,
QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
class MyCDiagram(FigureCanvas):
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
# We want the axes cleared every time plot() is called
#self.axes.hold(False)
x = arange(-180,180,LDTheader['Dg'])
self.axes.plot(x, LDTvalue[0], color='r', linewidth=1)
self.axes.plot(x, LDTvalue[6], color='b', linewidth=1)
self.axes.grid(True)
#
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,
QSizePolicy.Expanding,
QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
buttonOK = QPushButton('OK')
buttonClean = QPushButton('Clean')
pd_label = QLabel('Polar Diagram')
pd = MyPDiagram(QWidget(self), width=5, height=4, dpi=100)
cd_label = QLabel('Carthesian Diagram')
cd = MyCDiagram(QWidget(self), width=5, height=4, dpi=100)
buttonClean.clicked.connect(self.handleButtonClean)
grid = QGridLayout()
grid.setSpacing(10)
grid.addWidget(buttonOK, 1, 0)
grid.addWidget(buttonClean, 1, 1)
grid.addWidget(pd_label, 2, 0)
grid.addWidget(pd, 3, 0, 5, 1)
grid.addWidget(cd_label, 2, 1)
grid.addWidget(cd, 3, 1, 5, 1)
grid.update()
self.setLayout(grid)
self.setGeometry(300, 300, 1000, 600)
self.setWindowTitle('W&D LDTcleaner')
def handleButtonClean(self):
#1. Clean the value above 90 degrees
for j in range(0,int(LDTheader['Mc']/int(LDTheader['Symmetry']))+1):
for i in range(180,LDTheader['Ng']-1):
LDTvalue[j][i] = 0
#2. Clean when center value is not the max
for j in range(0,int(LDTheader['Mc']/int(LDTheader['Symmetry']))+1):
for i in range(0,LDTheader['Ng']-1):
if LDTvalue[j][0] < max(LDTvalue[j]):
LDTvalue[j][0] = max(LDTvalue[j])
self.initUI() #-----> This is where I am blocked. I tried to recall initUI()
print('Cleaned!')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MainWindow()
ex.show()
sys.exit(app.exec_())

Categories