Skip to content

Instantly share code, notes, and snippets.

@zaxtax
Last active June 5, 2017 17:56
Show Gist options
  • Save zaxtax/ca5103c9c20d7c71de457eca6de636ff to your computer and use it in GitHub Desktop.
Save zaxtax/ca5103c9c20d7c71de457eca6de636ff to your computer and use it in GitHub Desktop.
Histogram from the command line
#!/usr/bin/env python3
import click
import numpy as np
import sys
class IntOrStr(click.ParamType):
name = 'int/str'
def convert(self, value, param, ctx):
try:
return int(value)
except ValueError:
return value
@click.command()
@click.option('--bins',
default="fd",
type=IntOrStr(),
help="""
Number of bins to use, or
a binning strategy (fd, sturges, sqrt, etc.)
""")
@click.option('--width', default=50, help='Max width for histogram.')
def hist(bins, width):
data = np.fromiter(sys.stdin.readlines(), np.float)
h = np.histogram(data, bins=bins)
scale = max(h[0]) / width
for i in range(len(h[0])):
print("{0: 0.2f}".format(h[1][i]), "="*int(h[0][i] // scale))
if __name__ == '__main__':
hist()
@zaxtax
Copy link
Author

zaxtax commented May 26, 2017

An example usage might look like

% python3 -c "import numpy; {print(i) for i in numpy.random.normal(0,1,1000)}" | python3 hist.py
-3.35
-3.10
-2.85 =
-2.60 ==
-2.35 ==
-2.10 =========
-1.85 =========
-1.60 ==================
-1.35 =================
-1.10 ========================
-0.85 =================================
-0.60 ========================================
-0.35 =============================================
-0.10 =================================================
 0.14 =================================================
 0.39 ==========================================
 0.64 ========================
 0.89 ==========================
 1.14 ==================
 1.39 =================
 1.64 =========
 1.89 =====
 2.14 ===
 2.39
 2.64
 2.89

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment