如何将Matplotlib翻译为pyQt5

时间:2018-01-03 13:45:14

标签: matplotlib pyqt pyqt5

我正在研究pyqt5并且我必须使用一些matplotlib我看了如何使用matplotlib.backends.backend_qt5agg在pyqt5中嵌入matplotlib但是我仍然有几行我无法将它们设置为工作pyqt5 我的意思是我还不知道怎么在画布上展示这个?

int

在我的MainWindow中我只使用普通的类实例:

food = [sh//2, sw//2]

1 个答案:

答案 0 :(得分:0)

嗯,您的代码不可重复,但这是一个适用于PyQt5的版本。我认为,在您的代码中肯定无法正常工作的是plt.show()。您想使用MyMplCanvas生成的图形对象进行绘图,我认为pyplot将使用自己的UI而不是

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from PyQt5 import QtWidgets 
import sys
import numpy as np

class MyMplCanvas(FigureCanvas):
    def __init__(self, parent=None, width=5.4, height=4, dpi=100):
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = self.fig.add_subplot(111)
        self.compute_initial_figure()

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

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

    def compute_initial_figure(self):
        pass

class MyStaticMplCanvas(MyMplCanvas):
    def compute_initial_figure(self):
        dat = np.random.uniform(0, 10, (20, 2))
        self.axes.scatter(dat[:, 0], dat[:, 1])

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        canvas = MyStaticMplCanvas()

        self.setCentralWidget(canvas)

def main():
    app = QtWidgets.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()