Petro Verkhogliad @ Experiment Room 4

Matplotlib animation with PyQt4

written by Petro, on Nov 29, 2009 8:49:00 PM.

The code is fairly self-explanatory. We create a single line in the figure and then update it on every timer tick.

Edit: The code below is inspired by/borrowed from the new Matplotlib book by Sandro Tosi.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import sys
import random
from PyQt4 import QtGui

from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg \
        import FigureCanvasQTAgg as FigureCanvas

class Monitor(FigureCanvas):
    def __init__(self):
        self.fig = Figure()
        self.ax = self.fig.add_subplot(111)

        # initialize the figure canvas
        FigureCanvas.__init__(self, self.fig)

        # set up the display limits for the figure
        self.ax.set_xlim(0,30)
        self.ax.set_ylim(0,100)

        # turn off autoscaling
        self.ax.set_autoscale_on(False)

        # this is the value that will be updated
        self.value = []
        # this is the line that will be animated
        self.line_value, = self.ax.plot([], self.value, label="Values")

        # shwo the legend
        self.ax.legend()
        self.fig.canvas.draw()

        # start the Qt timer
        self.timerEvent(None)
        self.timer = self.startTimer(1000)


    def timerEvent(self, evt):
        """
        This code will be executed on every timer tick.
        """
        # get the new data value
        self.value.append(random.randrange(0,30))
        # update the line with the new values
        self.line_value.set_data(range(len(self.value)), self.value)

        # force the redraw of the canvas
        self.fig.canvas.draw()

        
if __name__ == "__main__":
    # set up the qt application
    app = QtGui.QApplication(sys.argv)
    # initialize the widget
    w = Monitor()
    # set the title of the window
    w.setWindowTitle('Updating in real time')
    # show the widged on the screen
    w.show()
    # start the main application loop
    sys.exit(app.exec_())

Comments

Leave a Reply