Package trunk :: Package BIP :: Package Viz :: Module asciihist
[hide private]

Source Code for Module trunk.BIP.Viz.asciihist

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