如何在 pyqt 中嵌入 matplotlib
- 2025-01-15 08:45:00
- admin 原创
- 84
问题描述:
我想在 pyqt4 用户界面中嵌入一个图形。我不明白人们如何在我找到的示例中进行嵌入 -这个(在底部) 和那个。
有人可以发布一步一步的解释,或者至少发布一个非常小、非常简单的代码,例如在一个 pyqt4 GUI 中创建一个图形和一个按钮。
解决方案 1:
其实并没有那么复杂。相关的 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()
解决方案 2:
以下是之前代码的改编,适用于PyQt5和Matplotlib 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_())
解决方案 3:
对于那些寻找动态解决方案以将 Matplotlib 嵌入 PyQt5(甚至使用拖放绘制数据)的人来说。在 PyQt5 中,您需要在主窗口类上使用 super 来接受拖放。dropevent 函数可用于获取文件名,其余的很简单:
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
对于初学者来说,参考完整代码给出以下输出:
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD