Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import Tkinter as tk
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
def main():
root = tk.Tk()
app = Application(root)
tk.mainloop()
class Application(object):
def __init__(self, root, delay=25, max_samples=25):
self.parent = root
self.frame = tk.Frame(root)
self.delay = delay
self.max_samples = max_samples
self.fig, self.canvas = self.setup_figure()
self.ax = self.setup_axes()
self.artists = self.setup_plot()
self.frame.pack(expand=True)
self.canvas.show()
self.parent.after(self.delay, self.timer_loop)
def timer_loop(self):
self.grab_data_and_update()
self.parent.after(self.delay, self.timer_loop)
def setup_figure(self):
fig = Figure(figsize=(8, 6))
canvas = FigureCanvasTkAgg(fig, master=self.frame)
widget = canvas.get_tk_widget()
widget.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
# Workaround for minor bug in older versions of matplotlib
widget.config(borderwidth=0, highlightthickness=0)
# Make the figure's background color the same as the Tk Frame.
rgb = widget.winfo_rgb(widget['bg'])
rgb = [(item // 256) / 255.0 for item in rgb]
fig.patch.set_facecolor(rgb)
return fig, canvas
def setup_axes(self):
ax = self.fig.add_subplot(111)
ax.set(xlabel='Number of Samples', ylabel='Values')
ax.margins(0.05)
return ax
def setup_plot(self):
lines = []
colors = ['lightblue', 'salmon', 'lightgray']
for color in colors:
line, = self.ax.plot([], [], lw=2, color=color)
lines.append(line)
return lines
def update(self, data):
for line, y in zip(self.artists, data):
y = np.atleast_1d(y)
ydata = np.concatenate([line.get_ydata(), y])
xdata = line.get_xdata()
if len(xdata) == 0:
xdata = np.array([0])
else:
new = xdata[-1] + np.arange(y.size) + 1
xdata = np.concatenate([xdata, new])
if ydata.size > self.max_samples:
xdata = xdata[-self.max_samples:]
ydata = ydata[-self.max_samples:]
line.set_data(xdata, ydata)
self.ax.relim()
self.ax.autoscale_view()
self.canvas.draw()
def grab_data_and_update(self):
data = []
for i in range(3):
value = np.random.normal(0, 1)
last = self.artists[i].get_ydata()
last = 0 if len(last) == 0 else last[-1]
data.append(last + value)
self.update(data)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.