Python-如何在pyqt中嵌入matplotlib-for-Dummies

Python-如何在pyqt中嵌入matplotlib-for-Dummies,第1张

Python-如何在pyqt中嵌入matplotlib-for-Dummies

我目前正在尝试将要绘制的图形嵌入我设计的pyqt4用户界面中。因为我几乎完全不熟悉编程,所以我不了解人们在我发现的示例中的嵌入方式- 这个(在底部) 和那个。

如果有人可以发布分步说明,或者至少在一个pyqt4 GUI中仅创建例如图形和按钮的至少非常小而非常简单的代码,那将是非常棒的。实际上并不是那么复杂。相关的Qt小部件位于中

matplotlib.backends.backend_qt4agg
FigureCanvasQTAgg
NavigationToolbar2QT
通常你需要什么。这些是常规的Qt小部件。你将它们视为其他任何小部件。下面是一个很简单的例子有
Figure
Navigation
和一个按钮,吸引了一些随机数据。我添加了评论来解释事情。

import sysfrom PyQt4 import QtGuifrom matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvasfrom matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbarfrom matplotlib.figure import Figureimport randomclass 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()


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5508898.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存