Imshow in pyQt is not centered - python

I write a code to put an imshow in a pyqt environment but the imshow is not centered in the figure:
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import numpy as np
import sys
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
class GenerateCM(QMainWindow):
def __init__(self, parent=None):
super(GenerateCM, self).__init__()
self.CM = np.zeros((10,10))
#######################################
self.centralWidget = QWidget()
self.setCentralWidget(self.centralWidget)
self.mainHBOX_param_scene = QHBoxLayout()
#CM view
layout_plot = QHBoxLayout()
self.loaded_plot = CMViewer(self)
self.loaded_plot.setMinimumHeight(200)
self.loaded_plot.update()
layout_plot.addWidget(self.loaded_plot)
self.mainHBOX_param_scene.addLayout(layout_plot)
self.centralWidget.setLayout(self.mainHBOX_param_scene)
class CMViewer(QGraphicsView):
def __init__(self, parent=None):
super(CMViewer, self).__init__(parent)
self.parent=parent
self.scene = QGraphicsScene(self)
self.setScene(self.scene)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, self)
# self.canvas.setGeometry(0, 0, 1600, 500 )
layout = QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
self.setLayout(layout)
self.canvas.show()
def update(self):
self.connectivityMat = self.parent.CM
self.figure.clear()
self.axes=self.figure.add_subplot(1,1,1)
im = self.axes.imshow(self.connectivityMat)
self.figure.colorbar(im)
self.axes.axis('off')
self.axes.set_title('Loaded Matrix')
self.canvas.draw()
self.canvas.show()
def main():
app = QApplication(sys.argv)
ex = GenerateCM(app )
ex.show()
sys.exit(app.exec_( ))
if __name__ == '__main__':
main()
Which give me this result.
I would like the image to be in the center of the window and not shifted to the rigth as it is for now. I thing I did something wrong with adding a subplot but I cannot find the right way to correctly put the subplot right in the center

Related

PyQt, Matplotlib: Can't set-up matplotlib's navigation toolbar, Unexpected Type

I'm trying to make an app where the matplotlib's tab widget is embedded inside another widget
import os
import matplotlib
import matplotlib.pyplot as pp
import numpy as np
from PySide2 import QtGui
from PySide2.QtCore import QTimer
from PySide2.QtWidgets import *
from layout import Ui_Form
matplotlib.use('Qt5Agg')
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import sys
graphed = False
res = 180
class VentanaPrincipal(QDialog):
def __init__(self, parent=None):
super(VentanaPrincipal, self).__init__(parent)
self.ventana = Ui_Form()
self.ventana.setupUi(self)
self.timer = QTimer()
self.timer.timeout.connect(self.mainloop)
self.timer.start(20)
self.ancho = self.size().height()
self.alto = self.size().height()
self.ventana.pshBtnCalcularOrbita.clicked.connect(self.truer)
self.ventana.pshBtnCalcularOrbita.clicked.connect(self.graph)
self.oldsize = self.size()
self.figure = Figure()
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, self)
self.button = QPushButton('Plot')
self.button.clicked.connect(self.plot)
layout = QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
layout.addWidget(self.button)
self.setLayout(layout)
def truer(self):
global graphed
graphed = True
def graph(self):
self.ventana.graph()
def resizeEvent(self,event):
self.oldsize = event.size()
def mainloop(self):
self.ancho = self.size().width()
self.alto = self.size().height()
if self.size() != self.oldsize:
if graphed:
self.graph()
if __name__ == '__main__':
app = QApplication(sys.argv)
aplicacion = VentanaPrincipal()
aplicacion.show()
sys.exit(app.exec_())
Gives me:
TypeError: arguments did not match any overloaded call:
QToolBar(str, parent: QWidget = None): argument 1 has unexpected type 'VentanaPrincipal'
QToolBar(parent: QWidget = None): argument 1 has unexpected type 'VentanaPrincipal'
The Ui_Form is a .py file compiled from the original .ui file from QtDesigner
I've seen an identical example onto another question, the example i grabbed onto was:
import sys
from PySide2.QtWidgets import QDialog,QApplication,QPushButton, QVBoxLayout
from PySide2 import QtGui
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import random
class Window(QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
# a figure instance to plot on
self.figure = Figure()
print(self)
# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init__
self.canvas = FigureCanvas(self.figure)
# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar(self.canvas, self)
print(type(self))
# Just some button connected to `plot` method
self.button = QPushButton('Plot')
self.button.clicked.connect(self.plot)
# set the layout
layout = QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
layout.addWidget(self.button)
self.setLayout(layout)
def plot(self):
''' plot some random stuff '''
# random data
data = [random.random() for i in range(10)]
# create an axis
ax = self.figure.add_subplot(111)
# discards the old graph
ax.clear()
# plot data
ax.plot(data, '*-')
# refresh canvas
self.canvas.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
main = Window()
main.show()
sys.exit(app.exec_())
There are some prints i put inside the code to check which kind of object is accepted by the QToolbar init line inside Matplotlib's backend

How do I avoid displaying a matplotlib too large greather than 2^16 pixels?

I'm trying to display a large amont of signals in a matplotlib figure. I have a value in my interface to set the spacing that exists between signals. My issue is, if that value is too large, I get this error:
ValueError: Image size of 1266x121000 pixels is too large. It must be less than 2^16 in each direction.
and the soft crashs. What I would like to do is avoiding the soft to crash. Does it exist a way to detect if that error will occur and then tell to the user that the value is too large? I could also adjust the dpi for large figure but the error could still comes anyway.
here a minimal example:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
import numpy as np
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
class Mon_Graph(QMainWindow):
def __init__(self, parent=None):
super(Mon_Graph, self).__init__()
self.parent = parent
self.centralWidget = QWidget()
self.setCentralWidget(self.centralWidget)
self.mainHBOX = QHBoxLayout()
self.spacing_e = QLineEdit('1')
self.mainHBOX.addWidget(self.spacing_e)
self.graph= graphic(self)
self.mainHBOX.addWidget(self.graph)
self.centralWidget.setLayout(self.mainHBOX)
self.Sigs = np.random.rand(100,100)*10
self.spacing_e.editingFinished.connect(self.update_sigs)
def update_sigs(self):
self.graph.update()
class graphic(QGraphicsView):
def __init__(self, parent=None):
super(graphic, self).__init__(parent)
self.parent = parent
self.scene = QGraphicsScene(self)
self.setScene(self.scene)
self.figure = plt.figure(facecolor='white')
self.canvas = FigureCanvas(self.figure)
self.widget = QWidget()
self.widget.setLayout(QVBoxLayout())
self.scroll = QScrollArea(self.widget)
self.scroll.setWidget(self.canvas)
self.axes = self.figure.add_subplot(111)
self.axes.set_xlabel("Time (s)")
layout = QVBoxLayout()
layout.addWidget(self.scroll)
self.setLayout(layout)
def update(self):
Sigs = self.parent.Sigs
self.figure.clear()
plt.figure(self.figure.number)
plt.subplots_adjust(left=0.1, bottom=0.01, right=1, top=1, wspace=0.0 , hspace=0.0 )
self.axes = plt.subplot(1, 1, 1)
spacing = float(self.parent.spacing_e.text())
for i in range(Sigs.shape[0]):
plt.plot(Sigs[i,:]+i*spacing)
self.axes.autoscale(enable=True, axis='both', tight=True)
self.canvas.setGeometry(0, 0, self.parent.width()-100, (self.parent.height()-100)*spacing)
self.canvas.draw_idle()
def main():
app = QApplication(sys.argv)
app.setStyle('Windows')
ex = Mon_Graph(app)
ex.showMaximized()
sys.exit(app.exec())
if __name__ == '__main__':
main()
If I put 20 in the lineedit then it is ok but if I put 200, it crashes with the previous error.
Just add a condition in your update method to check if any of both dimensions of Sigs surpass 2^16 (before the call to plot)

Matplotlib draw() won't work in a pyqt environment on MacOS

I'm trying to update a matplotlib plot embeded in a pyqt5 window.
I used self.canvas.draw() (in the update function)to update the plot in a function to redraw the figure. This is working fine on Window but it doesn't work on MacOS.
I don't understand why and if it exists a solution to that?
In fact I need to click on the axes in order to the figure to be updated... weird.
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import numpy as np
import sys
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
class StimEdit(QMainWindow):
def __init__(self, parent=None):
super(StimEdit, self).__init__()
self.parent = parent
self.centralWidget = QWidget()
self.color = self.centralWidget.palette().color(QPalette.Background)
self.setCentralWidget(self.centralWidget)
self.mainHBOX_param_scene = QHBoxLayout()
self.set_Stims()
self.mainHBOX_param_scene.addWidget(self.Stimulation)
self.centralWidget.setLayout(self.mainHBOX_param_scene)
def set_Stims(self):
self.Stimulation = QGroupBox('Stim N°1')
self.layout_Stimulation_courbe = QVBoxLayout()
self.layout_Stimulation = QHBoxLayout()
self.button = QPushButton('push')
self.masceneparam = paramViewer(self)
self.button.clicked.connect(self.button_fun)
self.layout_Stimulation_courbe.addWidget(self.masceneparam)
self.layout_Stimulation_courbe.addWidget(self.button)
self.Stimulation.setLayout(self.layout_Stimulation_courbe)
def button_fun(self):
self.masceneparam.update()
self.parent.processEvents()
class paramViewer(QGraphicsView):
def __init__(self, parent=None):
super(paramViewer, self).__init__(parent)
self.parent=parent
self.scene = QGraphicsScene(self)
self.setScene(self.scene)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, self)
self.axes_stim=self.figure.add_subplot(111)
self.canvas.setGeometry(0, 0, 1600, 500 )
layout = QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
self.setLayout(layout)
self.canvas.show()
def update(self):
self.axes_stim.clear()
t = np.arange(1000)/100
self.axes_stim.plot(t,np.sin(2*np.pi*np.random.uniform()*100*t))
self.canvas.draw()
def main():
app = QApplication(sys.argv)
ex = StimEdit(app)
ex.setWindowTitle('St ')
ex.show()
sys.exit(app.exec_( ))
if __name__ == '__main__':
main()
edit
I try to use the example of matplotlib for embeded Figures in Qt (https://matplotlib.org/gallery/user_interfaces/embedding_in_qt_sgskip.html) from #ImportanceOfBeingErnest
# from PyQt5.QtGui import *
# from PyQt5.QtWidgets import *
import numpy as np
import sys
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.qt_compat import QtCore, QtWidgets, is_pyqt5
if is_pyqt5():
from matplotlib.backends.backend_qt5agg import (
FigureCanvas, NavigationToolbar2QT as NavigationToolbar)
else:
from matplotlib.backends.backend_qt4agg import (
FigureCanvas, NavigationToolbar2QT as NavigationToolbar)
from matplotlib.figure import Figure
class StimEdit(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(StimEdit, self).__init__()
self.parent = parent
self.centralWidget = QtWidgets.QWidget()
self.setCentralWidget(self.centralWidget)
self.mainHBOX_param_scene = QtWidgets.QHBoxLayout()
self.set_Stims()
self.mainHBOX_param_scene.addWidget(self.Stimulation)
self.centralWidget.setLayout(self.mainHBOX_param_scene)
def set_Stims(self):
self.Stimulation = QtWidgets.QGroupBox('Stim N°1')
self.layout_Stimulation_courbe = QtWidgets.QVBoxLayout()
self.layout_Stimulation = QtWidgets.QHBoxLayout()
self.button = QtWidgets.QPushButton('push')
self.masceneparam = paramViewer(self)
self.button.clicked.connect(self.button_fun)
self.layout_Stimulation_courbe.addWidget(self.masceneparam)
self.layout_Stimulation_courbe.addWidget(self.button)
self.Stimulation.setLayout(self.layout_Stimulation_courbe)
def button_fun(self):
self.masceneparam.update()
self.parent.processEvents()
class paramViewer(QtWidgets.QGraphicsView):
def __init__(self, parent=None):
super(paramViewer, self).__init__(parent)
self.parent=parent
self.scene = QtWidgets.QGraphicsScene(self)
self.setScene(self.scene)
self.figure = Figure()
self.canvas = FigureCanvas(self.figure )
self.toolbar = NavigationToolbar(self.canvas, self)
self.axes_stim=self.figure.add_subplot(111)
self.canvas.setGeometry(0, 0, 1600, 500 )
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
self.setLayout(layout)
self.canvas.show()
def update(self):
self.axes_stim.clear()
t = np.arange(1000)/100
self.axes_stim.plot(t,np.sin(2*np.pi*np.random.uniform()*100*t))
self.canvas.figure.canvas.draw()
# self.canvas.draw()
def main():
app = QtWidgets.QApplication(sys.argv)
ex = StimEdit(app)
ex.setWindowTitle('St ')
ex.show()
sys.exit(app.exec_( ))
if __name__ == '__main__':
main()
But the issue still remains.
Answer from #ImportanceOfBeingErnest
Since I don't have any experience with Macs I might not be able to help further here, but a last suggestion might be to replace .draw() by .draw_idle(). (Both should work in this case, but you never know...)

relim of matplotlib axes (embedded in pyqt)doesn't work is I previously zoomed in

In the below example, I update a figure with varying signal length. the relim function works find except when I zoom in the figure. If I zoomed in, the relim doesn't reset the correct limit and the axes stay zoomed in, whatever the length of the signal I plot. I don't know what I'm doing wrong here.
from PyQt5.QtWidgets import *
import sys
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import numpy as np
class SurfViewer(QMainWindow):
def __init__(self, parent=None):
super(SurfViewer, self).__init__()
self.parent = parent
self.centralWidget = QWidget()
self.setCentralWidget(self.centralWidget)
self.setFixedWidth(600)
self.setFixedHeight(600)
self.layout = QVBoxLayout()
self.button = QPushButton('redraw')
self.myscene= Viewer_signal(self)
self.layout.addWidget(self.button)
self.layout.addWidget(self.myscene)
self.centralWidget.setLayout(self.layout)
self.button.clicked.connect(self.load)
def load(self):
self.myscene.update_Signal(np.random.rand(np.random.randint(1000,100000)),1000)
class Viewer_signal(QGraphicsView):
def __init__(self, parent=None):
super(Viewer_signal, self).__init__(parent)
self.parent=parent
self.scene = QGraphicsScene(self)
self.setScene(self.scene)
self.figure = Figure(facecolor='white')
self.figure.subplots_adjust(left=0.08, bottom=0.03, right=0.98, top=0.99, wspace=0.28 , hspace=0.30)
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, self)
self.axes_Sig = self.figure.add_subplot(111)
self.axes_Sig.set_xlabel("Time [s]")
self.axes_Sig.set_ylabel("Amp [mV]")
self.Line_,= self.axes_Sig.plot(0,0 )
self.canvas.setGeometry(0, 0, 1500, 500)
layout = QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
self.setLayout(layout)
self.figure.tight_layout()
def update_Signal(self,data,Fs):
t = np.arange(data.shape[0])/Fs
self.Line_.set_data(t, data)
self.axes_Sig.relim()
self.axes_Sig.autoscale_view(True,True,True)
self.canvas.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = SurfViewer(app)
ex.setWindowTitle('window')
ex.show()
sys.exit(app.exec_( ))
update
even setting the limits by and doesn't help:
def update_Signal(self,data,Fs):
t = np.arange(data.shape[0])/Fs
self.Line_.set_data(t, data)
miniy = min(data)
maxiy = max(data)
self.axes_Sig.update_datalim( ((0, miniy), (t[-1], maxiy)))
self.axes_Sig.relim()
self.axes_Sig.autoscale_view(True,True,True)
self.canvas.draw()
I think you want to use autoscale() instead of autoscale_view()
def update_Signal(self,data,Fs):
t = np.arange(data.shape[0])/Fs
self.Line_.set_data(t, data)
self.axes_Sig.relim()
self.axes_Sig.autoscale()
self.canvas.draw()

Using PyQt5 to embed a dynamical bar chart

I wrote the following code in python to show a bar chart in the GUI generated by PyQt5.
import sys
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout, \
QLineEdit, QMessageBox, QInputDialog, QLabel, QHBoxLayout, QGridLayout, QStackedLayout, QFormLayout
from PyQt5 import QtCore, QtGui, QtWidgets
import time
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.lines import Line2D
import matplotlib.animation as animation
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
# data
import numpy as np
#import matplotlib.pyplot as plt
import pandas as pd
import os
import csv
#define the path to data
pathToData='C:/RC/python/data/'
dataName= '31122017ARB.csv'
# import
data=pd.read_csv(pathToData+dataName, delimiter=';',encoding='cp1252')
# percent MW
data['MWP']=data[' MW ']/sum(data[' MW '])
#aggregate by Best
datag=data.groupby('Best', as_index=False).agg({'MW': 'sum'})
x=["BE"+s for s in[str(s) for s in [int(x) for x in datag.iloc[:,0].tolist()]]]
y=datag.ix[:,1].tolist()
figure = plt.figure()
H = np.array([[100, 2, 39, 190], [402, 55, 369, 1023], [300, 700, 8, 412], [170, 530, 330, 1]])
Z = np.array([[3, 290, 600, 480], [1011, 230, 830, 0], [152, 750, 5, 919], [340, 7, 543, 812]])
class Window(QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
# a figure instance to plot on
self.figure = plt.figure()
# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init_
self.im = None
self.canvas = FigureCanvas(self.figure)
self.canvas.mpl_connect('button_press_event', self.on_button_press_event)
# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar(self.canvas, self)
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.plot)
self.timer.setInterval(5000)
# Just some button connected to `plot` method
self.button = QPushButton('Plot')
self.button.clicked.connect(self.timer.start)
self.button.setDefault(False)
self.stop = QPushButton("Stop")
self.stop.clicked.connect(self.timer.stop)
self.stop.setDefault(False)
self.exit = QPushButton('Exit')
self.exit.clicked.connect(self.close)
self.exit.setDefault(True)
layout = QFormLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
layout.addWidget(self.button)
layout.addWidget(self.stop)
layout.addWidget(self.exit)
self.setLayout(layout)
self.lb = QtWidgets.QLabel(self)
self.lb.setWindowFlags(QtCore.Qt.ToolTip)
def plot(self):
self.x = ["BE"+s for s in[str(s) for s in [int(x) for x in datag.iloc[:,0].tolist()]]]
self.y = datag.iloc[:,1].tolist()#np.sin(self.x)
self.setWindowTitle("Bestandseingruppierung")
def update_figure(self):
self.axes.bar(self.x, self.y)
#self.y = np.roll(self.y,-1)
#self.draw()
self.canvas.draw()
def on_button_press_event(self, event):
print('button={}, x={}, y={}, xdata={}, ydata={}'
.format(event.button, event.x, event.y, event.xdata, event.ydata))
if self.im:
message = str(self.im.get_cursor_data(event))
delay = 1000
w = self.lb.fontMetrics().width(message)
self.lb.resize(w, self.lb.size().height())
self.lb.setText(message)
self.lb.move(QtGui.QCursor.pos())
self.lb.show()
QtCore.QTimer.singleShot(delay, self.lb.hide)
if __name__ == '__main__':
app = QApplication(sys.argv)
main = Window()
main.show()
sys.exit(app.exec_())
The Problem is: it is not shown any plot, even I do not get any error. I just obtain an empty .
How can I get the chart by pressing the plot bottom? I guess, I am doing some thing wrong under def plot(self):.
Just because of clarification: I tested the chart within a GUI generated by PyQt5 as a stand alone code, which works totally fine:
# FigureCanvas inherits QWidget
class MainWindow(FigureCanvas):
def __init__(self, parent=None, width=4, height=3, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
self.axes.hold(False)
super(MainWindow, self).__init__(fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,
QSizePolicy.Expanding,
QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
timer = QTimer(self)
timer.timeout.connect(self.update_figure)
timer.start(50)
self.x = ["BE"+s for s in[str(s) for s in [int(x) for x in datag.iloc[:,0].tolist()]]]#np.arange(0, 4*np.pi, 0.1)
self.y = datag.iloc[:,1].tolist()#np.sin(self.x)
self.setWindowTitle("Best")
def update_figure(self):
self.axes.bar(self.x, self.y)
#self.y = np.roll(self.y,-1)
self.draw()
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
I found the solution!
I have 3 botons in this GUI as shown in the following part of the code:
class Window(QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
# a figure instance to plot on
self.figure = plt.figure()
# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init_
self.im = None
self.canvas = FigureCanvas(self.figure)
self.canvas.mpl_connect('button_press_event', self.on_button_press_event)
# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar(self.canvas, self)
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.plot)
self.timer.setInterval(0)
# Just some button connected to `plot` method
self.button = QPushButton('Plot')
self.button.clicked.connect(self.timer.start)
self.button.setDefault(False)
self.stop = QPushButton("Stop")
self.stop.clicked.connect(self.timer.stop)
self.stop.setDefault(False)
self.exit = QPushButton('Exit')
self.exit.clicked.connect(self.close)
self.exit.setDefault(True)
One has to set the time delay in self.timer.setInterval(0) to Zero! That is the first point.
The part def plot(self) should be changed as follows:
def plot(self):
data=x
self.setWindowTitle("Bestandseingruppierung")
# instead of ax.hold(False)
self.figure.clear()
# create an axis
ax = self.figure.add_subplot(111)
#fig.autofmt_xdate()
# discards the old graph
ax.hold(False) # deprecated, see above
# plot data
ax.axes.bar(data,y)
self.canvas.draw()

Categories

Resources