Deep Dream » Blog Archive » Matplotlib and PyGTK, live plotting
I’ve been two days with this to get it working. It’s just a simple Matplotlib plot, using PyGTK to integrate it with a GUI, seems quite simple huh?
Well, it’s my first time using this library, and I’m not good at mathemathics, that’s the excuse. But I’m not the only person asking for this. It’s not clear on the matplotlib documentation how you can do this and there is no examples on the net (surprisingly!)
So, I made this for all the people who needs an example of how to do a matplotlib live plot intergated in GTK using PyGTK.import matplotlib.pyplot as pltimport gtk from matplotlib.backends.backend_gtk import FigureCanvasGTK as FigureCanvas from matplotlib.figure import Figure import random import time import gobject # We set a simple GTK window (not GTKAgg) win = gtk.Window() win.connect("destroy", lambda x: gtk.main_quit()) win.set_default_size(400,300) win.set_title("Prueba de Matplot") # We create the Figure and the plot f = Figure(figsize=(5,4), dpi=72) a = f.add_subplot(111) # We stablish the values for X (representig time) x = 0 t =  # We stablish the values for Y (representing any signal) y = 0 ard1 =  # Create a plot and set some parameters a.plot(t, ard1 , '-') a.grid(True) a.set_xlabel('Time') a.set_ylabel('Value') # This is the function that waits 1 second to redraw, then sets a random # value for y and adds it to the 'ard1' array. For 't' we add 1 to the x # value so it will simulate seconds. def counter(): x = 0 while True: time.sleep(1) y = random.randint(0,1024) t.append(x) ard1.append(y) x += 1 if x == 60: x = 0 print x,y a.plot(t, ard1) f.canvas.draw() # Create the widget, a FigureCanvas containing our Figure canvas = FigureCanvas(f) win.add(canvas) # This gobject tells GTK to run the function while idle gobject.idle_add(counter) # And here we go! win.show_all() gtk.main()I think it’s well commented, but if you have any questions you can mail me at pizted-at-gmail-dot-com