python 在pyqt中matplotlib图形之间的变化

Posted

技术标签:

【中文标题】python 在pyqt中matplotlib图形之间的变化【英文标题】:Python Change between matplotlib graphic in pyqt 【发布时间】:2018-12-12 22:59:33 【问题描述】:

有没有办法在 pyqt 应用程序中更改 matplotlib 显示? 我制作了一个带有 2 个单选按钮的 destopapplication,具体取决于按下哪个按钮,我希望在 radioButton_p graphics1 和 radioButton_b graphics2 上显示。 我可以将它从按下的第一个按钮更改为第二个,但如果再次按下第一个按钮,它不会变回第一个按钮的图形。

到目前为止,这是我的代码:

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')

【问题讨论】:

【参考方案1】:

您可以将两个图形小部件添加到同一布局并隐藏您不希望显示的一个,而不是制作 2 个单独的小部件(这就是我在下面所做的)。或者,您可以进行布局并添加或删除要显示的小部件。

工作代码

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_())

【讨论】:

以上是关于python 在pyqt中matplotlib图形之间的变化的主要内容,如果未能解决你的问题,请参考以下文章

在 PyQt5 中嵌入 Matplotlib 图形

Matplotlib 和 PyQt5 绘图图

带有 Matplotlib 的 PyQT5 插槽没有效果

当我在 PyQt5 窗口中嵌入 Matplotlib 图形时,为啥有两个重复的轴标签?

将 Matplotlib 图形嵌入到小部件中 - PyQt5

Matplotlib 将图形嵌入到 UI PyQt5