Package BIP :: Package Viz :: Module ascii
[hide private]
[frames] | no frames]

Source Code for Module BIP.Viz.ascii

  1  """ 
  2  This module contains code to generate ascii representations 
  3  of statistical objects 
  4  """ 
  5  from __future__ import division 
  6  from numpy import histogram, ceil 
  7  __author__="fccoelho" 
  8  __date__ ="$12/10/2009 14:25:05$" 
  9  __docformat__ = "restructuredtext en" 
 10   
 11   
 12   
13 -class Histogram(object):
14 """ 15 Ascii histogram 16 """
17 - def __init__(self, data, bins=10):
18 """ 19 Class constructor 20 21 :Parameters: 22 - `data`: array like object 23 """ 24 self.data = data 25 self.bins = bins 26 self.h = histogram(self.data, bins=self.bins)
27 - def horizontal(self, height=4, character ='|'):
28 """Returns a multiline string containing a 29 a horizontal histogram representation of self.data 30 31 :Parameters: 32 - `height`: Height of the histogram in characters 33 - `character`: Character to use 34 35 >>> d = normal(size=1000) 36 >>> h = Histogram(d,bins=25) 37 >>> print h.horizontal(5,'|') 38 106 ||| 39 ||||| 40 ||||||| 41 |||||||||| 42 ||||||||||||| 43 -3.42 3.09 44 """ 45 his = """""" 46 bars = self.h[0]/max(self.h[0])*height 47 for l in reversed(range(1,height+1)): 48 line = "" 49 if l == height: 50 line = '%s '%max(self.h[0]) #histogram top count 51 else: 52 line = ' '*(len(str(max(self.h[0])))+1) #add leading spaces 53 for c in bars: 54 if c >= ceil(l): 55 line += character 56 else: 57 line += ' ' 58 line +='\n' 59 his += line 60 his += '%.2f'%self.h[1][0] + ' '*(self.bins) +'%.2f'%self.h[1][-1] + '\n' 61 return his
62 - def vertical(self,height=20, character ='|'):
63 """ 64 Returns a Multi-line string containing a 65 a vertical histogram representation of self.data 66 67 :Parameters: 68 - `height`: Height of the histogram in characters 69 - `character`: Character to use 70 71 >>> d = normal(size=1000) 72 >>> Histogram(d,bins=10) 73 >>> print h.vertical(15,'*') 74 236 75 -3.42: 76 -2.78: 77 -2.14: *** 78 -1.51: ********* 79 -0.87: ************* 80 -0.23: *************** 81 0.41 : *********** 82 1.04 : ******** 83 1.68 : * 84 2.32 : 85 """ 86 his = """""" 87 xl = ['%.2f'%n for n in self.h[1]] 88 lxl = [len(l) for l in xl] 89 bars = self.h[0]/max(self.h[0])*height 90 his += ' '*(max(bars)+2+max(lxl))+'%s\n'%max(self.h[0]) 91 for i,c in enumerate(bars): 92 line = xl[i] +' '*(max(lxl)-lxl[i])+': '+ character*c+'\n' 93 his += line 94 return his
95 96 97 98 if __name__ == "__main__": 99 from numpy.random import normal 100 d = normal(size=1000) 101 h = Histogram(d,bins=10) 102 print h.vertical(15) 103 print h.horizontal(5) 104