Programing

pyqt에 matplotlib를 포함하는 방법-초보자 용

lottogame 2020. 11. 4. 07:39
반응형

pyqt에 matplotlib를 포함하는 방법-초보자 용


현재 내가 디자인 한 pyqt4 사용자 인터페이스에 플롯하려는 그래프를 삽입하려고합니다. 내가 프로그래밍에 거의 완전히 새로운 오전으로 - - 나는 사람들이 내가 찾은 예에서 매입 한 방법하지 않습니다 (맨 아래)이 하나하나가 .

누군가가 단계별 설명을 게시하거나 최소한 하나의 pyqt4 GUI에서 그래프와 버튼을 생성하는 아주 작고 매우 간단한 코드를 게시 할 수 있다면 멋질 것입니다.


실제로 그렇게 복잡하지 않습니다. 관련 Qt 위젯은 matplotlib.backends.backend_qt4agg. FigureCanvasQTAgg그리고 NavigationToolbar2QT당신이 필요 일반적입니다. 이들은 일반 Qt 위젯입니다. 당신은 그것들을 다른 위젯으로 취급합니다. 다음은와 아주 간단한 예입니다 Figure, Navigation어떤 임의의 데이터를 그리는 하나의 버튼. 설명을 추가했습니다.

import sys
from PyQt4 import QtGui

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure

import random

class Window(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = Figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.button = QtGui.QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def plot(self):
        ''' plot some random stuff '''
        # random data
        data = [random.random() for i in range(10)]

        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        ax.clear()

        # plot data
        ax.plot(data, '*-')

        # refresh canvas
        self.canvas.draw()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())

편집 :

주석 및 API 변경 사항을 반영하도록 업데이트되었습니다.

  • NavigationToolbar2QTAgg 변경 NavigationToolbar2QT
  • Figure대신 직접 가져 오기pyplot
  • 사용되지 바꾸기 ax.hold(False)ax.clear()

다음은 PyQt5Matplotlib 2.0 에서 사용하기위한 이전 코드의 수정입니다 . 몇 가지 작은 변경 사항이 있습니다. PyQt 하위 모듈의 구조, matplotlib의 다른 하위 모듈, 더 이상 사용되지 않는 메서드가 대체되었습니다 ...


import sys
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt

import random

class Window(QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = plt.figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.button = QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        # set the layout
        layout = QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def plot(self):
        ''' plot some random stuff '''
        # random data
        data = [random.random() for i in range(10)]

        # instead of ax.hold(False)
        self.figure.clear()

        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        # ax.hold(False) # deprecated, see above

        # plot data
        ax.plot(data, '*-')

        # refresh canvas
        self.canvas.draw()

if __name__ == '__main__':
    app = QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())

참고URL : https://stackoverflow.com/questions/12459811/how-to-embed-matplotlib-in-pyqt-for-dummies

반응형