说明
在pyqt5中使用matplotlib步骤:
1、引入plt
2、引入FigureCanvas
3、生成figure
4、取得FigureCanvas
5、将FigureCanvas加入容器中
6、调用plt函数来绘图
代码
import sys
# 1、引入plt
import matplotlib.pyplot as plt
import numpy as np
# 2、引入FigureCanvas
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from PyQt5.QtWidgets import QApplication, QVBoxLayout, QHBoxLayout, QWidget, QPushButtonclass MyApp(QWidget):def __init__(self):super().__init__()self.resize(1400, 800)self.setWindowTitle('PyQt5 绘制matplot图像')# 创建一个按钮,点击时更新图像self.button1 = QPushButton(self)self.button1.setText('画图')self.button1.clicked.connect(self.draw)# layout1self.layout1 = QVBoxLayout()self.layout1.addWidget(self.button1)# 3、生成figureself.fig = plt.figure(figsize=(6, 4), dpi=300)# layout2self.layout2 = QHBoxLayout()self.layout = QVBoxLayout(self) # 至少主布局要在UI界面上,最好每个子布局也在,因此继承自selfself.layout.addLayout(self.layout1)self.layout.addLayout(self.layout2)# 4、FigureCanvasself.canvas = FigureCanvas(self.fig)# 5、加入容器self.layout2.addWidget(self.canvas)def draw(self):# 6、绘图plt.clf()x = np.linspace(0, 4 * np.pi, 1000)y = np.sin(x)plt.plot(x, y)self.canvas.draw()if __name__ == "__main__":app = QApplication(sys.argv)window = MyApp()window.show()sys.exit(app.exec_())