Welcome, guest | Sign In | My Account | Store | Cart

A simple recipe to show on a command line the histogram of a data distribution, using numpy to perform the histogram and the unicode bar characters to show the resulting plot

Python, 15 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import numpy as np

def cli_hist(data,bins=10):
    bars = u' ▁▂▃▄▅▆▇█'
    n,_ = np.histogram(data,bins=bins)
    n2=n*(len(bars)-1)/(max(n))
    res = u" ".join( bars[i] for i in n2 )
    return res

data = np.random.random(100)    

print cli_hist(data)
# ▆ ▄ ▃ ▅ █ ▄ ▅ ▁ ▅ ▇
print cli_hist(data,bins=5)
# ▆ ▅ █ ▄ ▇

I often need to get a quick look on how some data are distributed, but opening a GUI window sometimes look an overshoot. Some other time I'm working over an ssh connection, and the GUI interface is not available without difficulties.

2 comments

shoma 9 years, 1 month ago  # | flag

It's looks like https://github.com/kennethreitz/spark.py, but diff is interesting.

Enrico Giampieri (author) 9 years, 1 month ago  # | flag

Actually, spark (the original one https://github.com/holman/spark) is where I got the idea in the first place. I could't recall the name and didn't manage to find it again, so i wrote my own implementation.

Created by Enrico Giampieri on Thu, 18 Oct 2012 (MIT)
Python recipes (4591)
Enrico Giampieri's recipes (1)

Required Modules

Other Information and Tasks