Reputation: 165
I have a the following code which creates a plot using matplotlib:
plot.py
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
class Canvas(FigureCanvas):
def __init__(self, parent = None, width=5, height=10, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
FigureCanvas.__init__(self, fig)
def plot(self):
print("im plotting")
current_data = [46.67, 50.0, 47.06, 50.0]
ax = self.figure.add_subplot(111)
ax.scatter(current_data, current_data)
print(current_data)
This Canvas class is used here in another file:
guiwrapper.py
from PyQt5 import QtCore, QtGui, QtWidgets, uic
import driver
from plot import Canvas
baseUIClass, baseUIWidget = uic.loadUiType("mygui.ui")
class Logic(baseUIWidget, baseUIClass):
def __init__(self, parent=None):
super(Logic, self).__init__(parent)
self.setupUi(self)
canvas = Canvas(self, width=8, height=4)
self.plot_location.addWidget(canvas)
canvas.plot()
#self.run_simulation.clicked.connect(canvas.plot)
#self.run_simulation.clicked.connect(lambda: canvas.plot())
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
ui = Logic(None)
ui.show()
sys.exit(app.exec_())
I simply cannot figure out why I am not able to plot the graph when clicking the run_simulation
button. If I simply write canvas.plot(), the GUI opens fine with the graph in there, but connecting buttons to call that function doesn't work, the graph doesn't get plotted and never shows up.
Does anyone known what's going on here?
Upvotes: 0
Views: 427
Reputation: 13671
Try it:
from PyQt5 import QtCore, QtGui, QtWidgets #, uic
#import driver
#from plot import Canvas
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import random
class Canvas(FigureCanvas):
def __init__(self, parent = None, width=5, height=10, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
FigureCanvas.__init__(self, fig)
def plot(self):
print("im plotting")
current_data = random.sample(range(100), 4) #[46.67, 50.0, 47.06, 50.0] # +
ax = self.figure.add_subplot(111)
ax.scatter(current_data, current_data)
ax.set_title('Graphique')
print(current_data)
#baseUIClass, baseUIWidget = uic.loadUiType("mygui.ui")
class Logic(QtWidgets.QWidget): #(baseUIWidget, baseUIClass):
def __init__(self, parent=None):
super(Logic, self).__init__(parent)
# self.setupUi(self)
self.canvas = Canvas(self, width=8, height=4)
self.plot_location = QtWidgets.QGridLayout(self)
self.plot_location.addWidget(self.canvas)
self.canvas.plot()
self.run_simulation = QtWidgets.QPushButton("Update Graphique")
self.run_simulation.clicked.connect(self.canvasPlot)
self.plot_location.addWidget(self.run_simulation)
def canvasPlot(self): # +++
self.canvas.figure.clf()
self.canvas.plot()
# Draw Graph
self.canvas.draw()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
ui = Logic() #(None)
ui.show()
sys.exit(app.exec_())
Upvotes: 1