I have a little issue in my code since I have a matplotlib graph with checkboxes (to choose what to plot) but when I open it with Pyqt5 (a Pushbutton) it does open but the checkboxes do not work, we can not touch them. My function works well, but not with Pyqt5, I hope I'm enough precise and I'm sorry if I am not. Here is my code if that can help you :
from PyQt5.QtWidgets import QPushButton, QMainWindow, QApplication
import sys
from matplotlib.widgets import CheckButtons
import matplotlib.pyplot as plt
def graph_check () :
x = [1,2,3,4,5,6]
y1 = [1,1,1,1,3,1]
y2 = [0,2,1,2,2,1]
y3 = [4,3,2,0,0,5]
fig,ax = plt.subplots()
p1, = ax.plot(x,y1,color = 'red', label = 'red')
p2, = ax.plot(x,y2,color = 'green', label = 'green')
p3, = ax.plot(x,y3,color = 'blue', label = 'blue')
lines = [p1,p2,p3]
plt.subplots_adjust(left = 0.25, bottom=0.1, right=0.95,top = 0.95)
# checkbuttons widgets
labels = ['red', 'green', 'blue']
activated = [True, True,True]
axCheckbutton = plt.axes([0.03,0.4,0.15,0.15])
chxbox = CheckButtons(axCheckbutton, labels,activated)
def set_visible (label) :
index = labels.index(label)
lines[index].set_visible(not lines[index].get_visible())
plt.draw()
chxbox.on_clicked(set_visible)
plt.show()
# that function does work well, in the end we have a graph with 3 lines and we can make
# them visible or not thanks to the checkbox.
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(100, 100, 600, 400)
self.btn1 = QPushButton('Graph check', self)
self.btn1.setGeometry(130, 215, 125, 55)
self.btn1.clicked.connect(self.btn1_onClicked)
self.show()
def btn1_onClicked(self):
graph_check()
# it works, we can see the graph but it is impossible to use the checkbox...
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())
CodePudding user response:
The problem is caused because "chxbox" is a local variable whose reference will be removed when the function finishes executing. A possible solution is to make it an attribute of another object that has a greater scope:
# ...
plt.chxbox = CheckButtons(axCheckbutton, labels, activated)
def set_visible(label):
index = labels.index(label)
lines[index].set_visible(not lines[index].get_visible())
plt.draw()
plt.chxbox.on_clicked(set_visible)
# ...