📌  相关文章
📜  如何在 PyQt5 中嵌入 Matplotlib 图形?

📅  最后修改于: 2022-05-13 01:54:30.797000             🧑  作者: Mango

如何在 PyQt5 中嵌入 Matplotlib 图形?

在本文中,我们将看到如何使用 matplotlib 在 PyQt5 窗口中绘制图形。
Matplotlib是Python中用于数组二维图的惊人可视化库。 Matplotlib 是一个基于 NumPy 数组构建的多平台数据可视化库,旨在与更广泛的 SciPy 堆栈配合使用。它是由 John Hunter 在 2002 年推出的。
PyQt5是跨平台的 GUI 工具包,一组用于 Qt v5 的Python绑定。由于该库提供的工具和简单性,人们可以非常轻松地开发交互式桌面应用程序。 GUI 应用程序由前端和后端组成。

入门

为了在 PyQt5 中使用 Matplotlib 绘制图形,我们需要 FigureCanvasQTAgg 和 NavigationToolbar2QT 这些类似于嵌入的 PyQt5 小部件。

  • NavigationToolbar2QT :它将为图形提供工具栏,可以在下面给出的命令的帮助下导入
  • FigureCanvasQTAgg :它将为图形提供画布,可以借助下面给出的命令导入

下面是 FigureCanvasQTAgg 和 NavigationToolbar2QT 的样子——

下面是实现

Python3
# importing various libraries
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
  
# main window
# which inherits QDialog
class Window(QDialog):
      
    # constructor
    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')
          
        # adding action to the button
        self.button.clicked.connect(self.plot)
  
        # creating a Vertical Box layout
        layout = QVBoxLayout()
          
        # adding tool bar to the layout
        layout.addWidget(self.toolbar)
          
        # adding canvas to the layout
        layout.addWidget(self.canvas)
          
        # adding push button to the layout
        layout.addWidget(self.button)
          
        # setting layout to the main window
        self.setLayout(layout)
  
    # action called by the push button
    def plot(self):
          
        # random data
        data = [random.random() for i in range(10)]
  
        # clearing old figure
        self.figure.clear()
  
        # create an axis
        ax = self.figure.add_subplot(111)
  
        # plot data
        ax.plot(data, '*-')
  
        # refresh canvas
        self.canvas.draw()
  
# driver code
if __name__ == '__main__':
      
    # creating apyqt5 application
    app = QApplication(sys.argv)
  
    # creating a window object
    main = Window()
      
    # showing the window
    main.show()
  
    # loop
    sys.exit(app.exec_())


输出 :