Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将matplotlib嵌入pyqt-for Dummies_Python_Matplotlib_Pyqt4 - Fatal编程技术网

Python 如何将matplotlib嵌入pyqt-for Dummies

Python 如何将matplotlib嵌入pyqt-for Dummies,python,matplotlib,pyqt4,Python,Matplotlib,Pyqt4,我目前正在尝试在我设计的pyqt4用户界面中嵌入一个要绘制的图形。因为我对编程几乎完全陌生——我不知道人们是如何在我发现的示例中嵌入的——以及 如果任何人都能发布一个逐步的解释,或者至少是一个非常小、非常简单的代码,比如在一个pyqt4 GUI中创建一个图形和一个按钮,那就太棒了 其实没那么复杂。相关的Qt小部件在中FigureCanvasQTAgg和导航工具栏2qt通常是您需要的。这些是常规的Qt小部件。您可以将它们视为任何其他小部件。下面是一个非常简单的示例,其中有一个图,导航,以及一个绘制

我目前正在尝试在我设计的pyqt4用户界面中嵌入一个要绘制的图形。因为我对编程几乎完全陌生——我不知道人们是如何在我发现的示例中嵌入的——以及


如果任何人都能发布一个逐步的解释,或者至少是一个非常小、非常简单的代码,比如在一个pyqt4 GUI中创建一个图形和一个按钮,那就太棒了

其实没那么复杂。相关的Qt小部件在中
FigureCanvasQTAgg
导航工具栏2qt
通常是您需要的。这些是常规的Qt小部件。您可以将它们视为任何其他小部件。下面是一个非常简单的示例,其中有一个
导航
,以及一个绘制一些随机数据的按钮。我添加了注释来解释事情

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更改

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

对于那些寻找在PyQt5中嵌入Matplotlib的动态解决方案的人(甚至使用拖放打印数据)。在PyQt5中,需要在主窗口类上使用super来接受删除。dropevent函数可用于获取文件名,rest很简单:

def dropEvent(self,e):
        """
        This function will enable the drop file directly on to the 
        main window. The file location will be stored in the self.filename
        """
        if e.mimeData().hasUrls:
            e.setDropAction(QtCore.Qt.CopyAction)
            e.accept()
            for url in e.mimeData().urls():
                if op_sys == 'Darwin':
                    fname = str(NSURL.URLWithString_(str(url.toString())).filePathURL().path())
                else:
                    fname = str(url.toLocalFile())
            self.filename = fname
            print("GOT ADDRESS:",self.filename)
            self.readData()
        else:
            e.ignore() # just like above functions  
对于启动器,参考完成给出以下输出:

注意,根据这一点,嵌入时不应导入pyplot。它可以用自己的主循环运行自己的GUI。在embeddingI上有一个错误:MatplotlibDeprecationWarning:这个类在1.4中被弃用了,因为它在
导航工具栏2qt上没有其他功能。请将您的代码更改为使用
NavigationToolbar2QT
而不是mpldeprection)@gs_developer\u user3605534将
navigationtoolbar2qtag
替换为
NavigationToolbar2QT
终止消息当我使用此代码时,它会创建两个窗口,一个Qt主窗口和一个matplotlib图形。我如何避免这样的情况,使它只创建一个Qt主窗口?我使用python 3.4 32位、matplotlib 1.5.3和PyQt4(我还必须将
NavigationToolbar2QTAgg
更改为
NavigationToolbar2QT
)。我发现一个解决方案是使用IPythonI,我用它在主窗口中放置一个
QVBoxLayout
。有没有办法让画布和图形填充一个高矩形(大约是宽矩形的1.5倍高)?非常有用的更新,运行良好!您能为
ax.hold
被弃用提供参考吗?另外,为什么不使用
ax.clear
重用Axis实例呢?我认为在将matplotlib嵌入pyqt时导入
matplotlib.pyplot
不是最佳做法(如果我在这个问题上出错,请纠正我)。如果我是正确的,我在这篇SO文章中使用此方法嵌入了matplotlib,这篇文章不导入pyplot:如何在画布上打印图像?