01# -*- coding: utf-8 -*-
02
03import sys, os, random
04from PyQt4 import QtGui, QtCore
05
06import numpy as np
07from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
08from matplotlib.figure import Figure
09from matplotlib.animation import FuncAnimation
10
11class 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
28class AnimationWidget(QtGui.QWidget):
29 def __init__(self):
30 QtGui.QWidget.__init__(self)
31
32 vbox = QtGui.QVBoxLayout()
33 self.canvas = MyMplCanvas(self, width=5, height=4, dpi=100)
34 vbox.addWidget(self.canvas)
35
36 hbox = QtGui.QHBoxLayout()
37 self.start_button = QtGui.QPushButton("start", self)
38 self.stop_button = QtGui.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
64if __name__ == "__main__":
65 qApp = QtGui.QApplication(sys.argv)
66 aw = AnimationWidget()
67 aw.show()
68 sys.exit(qApp.exec_())
loading...