1
2
3
4 from Tkinter import *
5
6 import math, random
7
8 GREY = "grey"
9 GREEN = "green"
10 WHITE = "white"
11 BLACK = "black"
12
13
14
15
16 def jitterplot(canvas, bbox, data):
17 "Draw a jitter plot"
18
19
20 lo, hi = min(data), max(data)
21 avg = sum(data)/float(len(data))
22 var = sum(map(lambda a,m=avg:(a-m)*(a-m), data))
23 sd = math.sqrt(var / float(len(data)-1))
24
25
26 ystep = (bbox[1] - bbox[3]) / (hi - lo)
27 ybase = bbox[3]
28
29 x = (bbox[2] + bbox[0]) / 2
30
31 y0 = lo*ystep+ybase
32 y1 = hi*ystep+ybase
33 sd = sd * ystep
34
35
36 y = (y0 + y1) / 2
37 canvas.create_oval(x - sd, y0, x + sd, y1, fill=GREY, outline="")
38 canvas.create_oval(x - sd, y - sd, x + sd, y + sd, fill=WHITE, outline="")
39
40
41 y = avg*ystep+ybase
42 w = 10
43 canvas.create_line(x-w, y, x+w, y, fill=BLACK, width=3)
44 canvas.create_line(x, y0, x, y1, fill=BLACK, width=3)
45 canvas.create_line(x-w, y0, x+w, y0, fill=BLACK, width=3)
46 canvas.create_line(x-w, y1, x+w, y1, fill=BLACK, width=3)
47
48
49 for y in map(lambda y,ys=ystep,yb=ybase:y*ys+yb, data):
50 j = x + (y1 - y0) * 0.1 * (random.random() - 0.5)
51 canvas.create_oval(j-2, y-2, j+2, y+2, fill=WHITE)
52
53
54
55
56 data = map(lambda a:random.random(), range(200))
57
58
59
60 root = Tk()
61
62 Label(text="Jitter Plot Example").pack()
63 canv = Canvas(root, height=500, width=500, bg=WHITE)
64 canv.pack()
65
66
67
68
69
70
71 Button(text="Dismiss", command=root.quit).pack(side=LEFT)
72
73
74
75
76 bbox = 20, 20, 480, 480
77
78 jitterplot(canv, bbox, data)
79
80 root.mainloop()
81