PyQt5嵌入matplotlib动画

时间:2021-02-01 23:02:05

PyQt5嵌入matplotlib动画

 1 # -*- coding: utf-8 -*-
 2 
 3 import sys
 4 from PyQt5 import QtWidgets
 5 
 6 import numpy as np
 7 from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
 8 from matplotlib.figure import Figure
 9 from matplotlib.animation import FuncAnimation
10 
11 class MyMplCanvas(FigureCanvas):
12     """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
13     def __init__(self, parent=None, width=5, height=4, dpi=100):
14         fig = Figure(figsize=(width, height), dpi=dpi)
15         self.axes = fig.add_subplot(111)
16         # We want the axes cleared every time plot() is called
17         self.axes.hold(False)
18 
19         self.compute_initial_figure()
20 
21         #
22         FigureCanvas.__init__(self, fig)
23         self.setParent(parent)
24 
25     def compute_initial_figure(self):
26         pass
27 
28 class AnimationWidget(QtWidgets.QWidget):
29     def __init__(self):
30         QtWidgets.QWidget.__init__(self)
31 
32         vbox = QtWidgets.QVBoxLayout()
33         self.canvas = MyMplCanvas(self, width=5, height=4, dpi=100)
34         vbox.addWidget(self.canvas)
35         
36         hbox = QtWidgets.QHBoxLayout()
37         self.start_button = QtWidgets.QPushButton("start", self)
38         self.stop_button = QtWidgets.QPushButton("stop", self)
39         self.start_button.clicked.connect(self.on_start)
40         self.stop_button.clicked.connect(self.on_stop)
41         hbox.addWidget(self.start_button)
42         hbox.addWidget(self.stop_button)
43         vbox.addLayout(hbox)
44         self.setLayout(vbox)
45         
46         self.x = np.linspace(0, 5*np.pi, 400)
47         self.p = 0.0
48         self.y = np.sin(self.x + self.p)
49         self.line, = self.canvas.axes.plot(self.x, self.y, animated=True, lw=2)
50         
51     def update_line(self, i):
52         self.p += 0.1
53         y = np.sin(self.x + self.p)
54         self.line.set_ydata(y)
55         return [self.line]
56         
57     def on_start(self):
58         self.ani = FuncAnimation(self.canvas.figure, self.update_line, 
59                                  blit=True, interval=25)
60     
61     def on_stop(self):
62         self.ani._stop()
63 
64 if __name__ == "__main__":
65     qApp = QtWidgets.QApplication(sys.argv)
66     aw = AnimationWidget()
67     aw.show()
68     sys.exit(qApp.exec_())

PyQt5嵌入matplotlib动画