Mady
Mady

Reputation: 473

Python Change between matplotlib graphic in pyqt

Is there a way to change the matplotlib display in a pyqt application ? I made a destopapplication with 2 radiobuttons, dependinging which button is pressed, i want on radioButton_p graphic1 to be shown and on radioButton_b the graphic2. I am able to change it from the first button which is pressed to the second, but if the first button is pressed again it will not change back to the graphic of the first button.

Here is my code so far:

from PyQt5 import QtWidgets, QtCore, QtPrintSupport, QtGui
import matplotlib
matplotlib.use("Qt5Agg")
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from PyQt5.QtWidgets import *


found_words = ["a", "b", "c", "d", "e", "f", "g", "h"]
cound_words = ['1','2','3','4','5','6','7','8']

found_pos = [ 'aaa','ssss']
count_pos = ['2','3']

class MyMplCanvas_begr(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)

       # self.compute_initial_figure()
        self.axes.bar(found_words, cound_words, color=['r', 'b', 'k', 'y', 'g'])
        self.axes.set_ylabel('Anzahl')
        self.axes.set_xlabel('Begriffe')
        self.axes.set_title('hi')

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                QSizePolicy.Expanding,
                QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

class MyMplCanvas_pos(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)

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        self.plot()

    def plot(self):
        colors = ['yellowgreen', 'lightcoral']
        explode = (0.1, 0)  # explode 1st slice
        ax = self.figure.add_subplot(111)

        ax.pie(count_pos, explode=explode, labels=found_pos, colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=140)



class main_statistic(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(main_statistic, self).__init__(parent)


        self.radioButton_p = QRadioButton('Pos', self)
        self.radioButton_p.setGeometry(QtCore.QRect(100, 10, 95, 20))
        self.radioButton_p.setCheckable(True)
        self.radioButton_p.toggled.connect(self.clicked_pos)

        self.radioButton_b = QRadioButton('Word', self)
        self.radioButton_b.setGeometry(QtCore.QRect(200, 10, 95, 20))
        self.radioButton_b.setCheckable(True)
        self.radioButton_b.toggled.connect(self.clicked_begr)

        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)

        self.main_widget = QWidget(self)
        self.main_widget.setGeometry(QtCore.QRect(100, 100, 700, 500))

        self.main_widget1 = QWidget(self)
        self.main_widget1.setGeometry(QtCore.QRect(100, 100, 700, 500))


    def clicked_pos(self, down):
        if down:
            l = QVBoxLayout(self.main_widget)
            dc = MyMplCanvas_pos(self.main_widget, width=5, height=4, dpi=100)
            l.addWidget(dc)
        else:
            print('not prssed')


    def clicked_begr(self, down):
        if down:
            l1 = QVBoxLayout(self.main_widget1)
            dc1 = MyMplCanvas_begr(self.main_widget1, width=5, height=4, dpi=100)
            l1.addWidget(dc1)
        else:
            print('not prssed2')

Upvotes: 1

Views: 75

Answers (1)

Stephen
Stephen

Reputation: 64

Instead of making 2 separate widgets you can add both of the graph widgets to the same layout and hide the one you don't want displayed (this is what i did bellow). Alternatively, you could make a layout and add or remove the widget you want displayed.

working code

from PyQt5 import QtWidgets, QtCore, QtPrintSupport, QtGui
import matplotlib
matplotlib.use("Qt5Agg")
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget, QRadioButton
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from PyQt5.QtWidgets import *


found_words = ["a", "b", "c", "d", "e", "f", "g", "h"]
cound_words = ['1','2','3','4','5','6','7','8']

found_pos = [ 'aaa','ssss']
count_pos = ['2','3']

class MyMplCanvas_begr(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)

    # self.compute_initial_figure()
        self.axes.bar(found_words, cound_words, color=['r', 'b', 'k', 'y', 'g'])
        self.axes.set_ylabel('Anzahl')
        self.axes.set_xlabel('Begriffe')
        self.axes.set_title('hi')

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                QSizePolicy.Expanding,
                QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

class MyMplCanvas_pos(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)

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        self.plot()

    def plot(self):
        colors = ['yellowgreen', 'lightcoral']
        explode = (0.1, 0)  # explode 1st slice
        ax = self.figure.add_subplot(111)

        ax.pie(count_pos, explode=explode, labels=found_pos, colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=140)



class main_statistic(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(main_statistic, self).__init__(parent)


        self.radioButton_p = QRadioButton('Pos', self)
        self.radioButton_p.setGeometry(QtCore.QRect(100, 10, 95, 20))
        self.radioButton_p.setCheckable(True)
        self.radioButton_p.toggled.connect(self.clicked_pos)

        self.radioButton_b = QRadioButton('Word', self)
        self.radioButton_b.setGeometry(QtCore.QRect(200, 10, 95, 20))
        self.radioButton_b.setCheckable(True)
        self.radioButton_b.toggled.connect(self.clicked_begr)

        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)

        self.main_widget = QWidget(self)
        self.main_widget.setGeometry(QtCore.QRect(100, 100, 700, 500))

        #self.editmenu.setHidden(True)
        #self.sideMenu.setHidden(False)

        l = QVBoxLayout()
        self.dc = MyMplCanvas_pos( width=5, height=4, dpi=100)
        self.dc.setHidden(True)
        l.addWidget(self.dc)
        self.dc1 = MyMplCanvas_begr( width=5, height=4, dpi=100)
        self.dc1.setHidden(True)
        l.addWidget(self.dc1)
        self.main_widget.setLayout(l)

    def clicked_pos(self):
        self.dc.setHidden(False)
        self.dc1.setHidden(True)
    def clicked_begr(self):
        self.dc.setHidden(True)
        self.dc1.setHidden(False)

if __name__ == '__main__':

    import sys

    app = QApplication(sys.argv)
    mainWin = main_statistic()
    mainWin.show()
    sys.exit(app.exec_())

Upvotes: 1

Related Questions