Jitterplot

   1 # File: jitterplot.py -- draw a jitter diagram (after XLispStat)
   2 # Fredrik Lundh
   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 # Draw jitterplot (should turn this into a compound widget instead)
  15 
  16 def jitterplot(canvas, bbox, data):
  17     "Draw a jitter plot"
  18 
  19     # get min/max and average
  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     # calculate scale
  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     # draw "cloud"
  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     # draw min/max and average bars
  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     # draw markers
  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 # create some random data
  55 
  56 data = map(lambda a:random.random(), range(200))
  57 
  58 # create a drawing canvas
  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 # a few commands
  67 
  68 ##def printcanvas():
  69 ##    os.popen("lpr", "w").write(canv.postscript())
  70 
  71 Button(text="Dismiss", command=root.quit).pack(side=LEFT)
  72 ##Button(text="Print", command=printcanvas).pack(side=LEFT)
  73 
  74 # draw the diagram
  75 
  76 bbox = 20, 20, 480, 480
  77 
  78 jitterplot(canv, bbox, data)
  79 
  80 root.mainloop()
  81 

tkinter: Jitterplot (last edited 2011-07-08 00:52:59 by newacct)