1. ホーム
  2. Python

PyQt5演習:matplotlibでプロットする

2022-02-10 02:45:19
<パス

matplotlib の pyqt5 によるシンプルなプロット機能を、オンラインのサンプルを参考に実装しました。
関連する知識
(1) pyqt5 でコントロールを追加してレイアウトに追加する
(2) レイアウトはreplaceWidgetを使用してコントロールを置き換えることができる
(3) シグナル・スロット機構

timer = QtCore.QTimer(self)
timer.timeout.connect(self.update_figure)

self.btnPlot.clicked.connect(self.plotButton_callback)

得られた効果

import sys
from PyQt5 import QtCore, QtGui, uic
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication, QMessageBox, QVBoxLayout, QSizePolicy, QWidget

from PyQt5.QtGui import QIcon
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import numpy as np

qtCreatorFile = "matplotlib_ui.ui"
# Load with uic
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)

class MyMplCanvas(FigureCanvas):
    """This is a window widget, i.e. QWidget (and of course FigureCanvasAgg)"""
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)
        # Each time plot() is called, we want the original axes to be cleared (so False)
        self.axes.hold(False)
        self.axes.grid('on')

        self.compute_initial_figure()

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

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

    def compute_initial_figure(self):
        pass

class MyStaticMplCanvas(MyMplCanvas):
    """Static canvas: a sine line"""
    def compute_initial_figure(self):
        t = np.range(0.0, 3.0, 0.01)
        s = np.sin(2 * np.pi * t)
        self.axes.grid('on')
        self.axes.plot(t, s)


class MyDynamicMplCanvas(MyMplCanvas):
    """Dynamic canvas: automatically updates every second, replacing a line of folds. """
    def __init__(self, *args, **kwargs):
        MyMplCanvas.__init__(self, *args, **kwargs)
        timer = QtCore.QTimer(self)
        timer.timeout.connect(self.update_figure)
        timer.start(1000)

    def compute_initial_figure(self):
        self.axes.grid('on')
        self.axes.plot([0, 1, 2, 3], [1, 2, 0, 4], 'r')

    def update_figure(self):
        # construct 4 random integers in the closed interval [0, 10]
        l = [np.random.randint(0, 10) for i in range(4)]
        self.axes.grid('on')
        self.axes.plot([0, 1, 2, 3], l, 'r')
        self.draw()




class MyApp(QMainWindow, Ui_MainWindow):

    def __init__(self):
        QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        super(). __init__()


        self.initUI()
        self.initBtn()
        self.initFrame()

    def initFrame(self):
        self.main_widget = self.frame
        self.layout = QVBoxLayout(self.main_widget)
        self.f = MyMplCanvas(self.main_widget)
        self.layout.addWidget(self.f)

    def initUI(self):               

        self.setupUi(self)
        self.setWindowTitle("PyQt5 combined with Matplotlib drawing")
        self.setWindowIcon(QIcon("rocket.ico")) # set the icon, only the taskbar will show the icon under linux

        self.show()

    def initBtn(self):
        self.btnPlot.clicked.connect(self.plotButton_callback)
        self.btnPlot.setToolTip("Button")         

    def plotButton_callback(self):

        self.drawFrame()

    def drawFrame(self):

        sc = MyStaticMplCanvas(self.main_widget, width=5, height=4, dpi=100)
        dc = MyDynamicMplCanvas(self.f, width=5, height=4, dpi=100)
        self.layout.addWidget(sc)
        self.layout.replaceWidget(self.f,dc) # Replace the control


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())


参考リンク https://www.cnblogs.com/hhh5460/p/4322652.html