Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
got rid of optparse
  • Loading branch information
austinogilvie committed Sep 14, 2015
commit 93318472807c9510b46c75e34ca381f246ad1cd6
61 changes: 47 additions & 14 deletions bashplotlib/cli/scatter.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,53 @@
scatter = {
"usage": """scatterplot is a command for making xy plots. it accepts a series of x values and a series of y values in the
following formats:
1) a txt file or standard in value w/ 2 comma seperated columns of x,y values
2) 2 txt files. 1 w/ designated x values and another with designated y values.

scatter -x <xcoords> -y <ycoords>
cat <file_with_x_and_y_coords> | scatter
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""scatter

"""
}
Usage:
scatter ((FILE | -f FILENAME) | (-X XDATA -y YDATA)) [-t TITLE -s SIZE -p MARKERSHAPE -c COLOUR] [-h -H]

Arguments:
FILE Csv with 2 columns for x and y [default: ]
-f --file FILENAME Same as FILE but shorter and less explicit [default: ]
-X --xs-file XDATA Text file with 1 column for the X values [default: ]
-y --ys-file YDATA Text file with 1 column for the y values [default: ]
-t --title TITLE Title for the chart [default: ]
-s --size SIZE Height of the histogram in lines [default: 20.0]
-p --pch MARKERSHAPE Shape of each bar [default: x]
-c --colour COLOUR Colour of the plot (Pink, blue, green, red, white, aqua, grey, yellow) [default: white]
-H --skip-header Skip the first row in FILENAME, XDATA, and YDATA [default: False]

# SCATTER_DOCSTRING = """scatter - construct a scatter plot from your terminal
Options:
-h --help Show this screen

# Usage:
# scatter [X Y]
Examples:
$ scatter2 -X data/exp.txt -y data/exp.txt

"""
from docopt import docopt
from bashplotlib.cli.helpers import read_stdin_or_timeout

# """
def parse_args():
"""takes __doc__ for given cmd. Returns parsed args using docopt.
"""
args = docopt(__doc__)
for k, v in args.iteritems():
if v == 'None':
args[k] = None
if args['--file'] is None and (args['--xs-file'] is None or args['--ys-file'] is None):
print __doc__
sys.exit(1)
if args['FILE'] is not None or args['--file'] is not None:
if args['FILE'] and args['FILE'] != args['--file']:
args['--file'] = args['FILE']
if args['--file'] == 'stdin':
args['--file'] = read_stdin_or_timeout()
plot_params = {
'filename': args['--file'],
'xs': args['--xs-file'],
'ys': args['--ys-file'],
'size': float(args['--size']),
'pch': args['--pch'],
'colour': args['--colour'],
'title': args['--title'],
}
return {k: v for k,v in plot_params.items() if v is not None and v != ""}
93 changes: 0 additions & 93 deletions bashplotlib/cli/scatter2.py

This file was deleted.

110 changes: 110 additions & 0 deletions bashplotlib/core/helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""core/helpers.py
"""
import os
import sys
import collections

bcolours = {
"white": '\033[97m',
"aqua": '\033[96m',
"pink": '\033[95m',
"blue": '\033[94m',
"yellow": '\033[93m',
"green": '\033[92m',
"red": '\033[91m',
"grey": '\033[90m',
"ENDC": '\033[0m'
}

def isiterable(obj):
"""
Return True if you can loop over obj otherwise False
"""
return isinstance(obj, collections.Iterable)

def get_colour(colour):
return bcolours.get(colour, bcolours['white'])

def printcolour(text, sameline=False, colour=get_colour("ENDC")):
"""
Print color text using escape codes
"""
if sameline:
sep = ''
else:
sep = '\n'
sys.stdout.write(get_colour(colour) + text + bcolours["ENDC"] + sep)

printcolor = printcolour

def drange(start, stop, step=1.0):
"generate between 2 numbers w/ optional step"
if step==0:
step = 0.01
r = start
while r < stop:
yield r
r += step

def box_text(text, width, offset=0):
box = " "*offset + "-"*(width+2) + "\n"
box += " "*offset + "|"+ text.center(width) + "|" + "\n"
box += " "*offset + "-"*(width+2)
return box

def try_cast_str_to_number(number_str, verbose=False):
"takes txt and tries to coerce it to float"
try:
return float(number_str.strip())
except Exception, err:
if verbose:
sys.stderr.write(err.message)
sys.stderr.flush()
return None

def read_xy_pairs_from_csv(filename, X=0, y=1, sep=',', header=False):
"""Grab 2 columns from a csv file by name or col index

Arguments:
filename Name of the csv file to read
X Index of the X column in the file [default: 0]
y Index of the y column in the file [default: 0]
sep Delimiter of the file [default: ,]
header Does the file have headers in row #1 [default: False]

"""
with open(filename, 'r') as f:
data = [line.strip() for line in f.readlines()]
data = [line.split(sep) for line in data]
data = [map(str.strip, row) for row in data]

if isinstance(X, int) and isinstance(y, int):
X_idx, y_idx = X, y
elif isinstance(X, basestring) and isinstance(y, basestring) \
and X.strip().isdigit() and y.strip().isdigit():
X_idx = int(try_cast_str_to_number(X))
y_idx = int(try_cast_str_to_number(y))
else:
X_idx, y_idx = None, None
X_y_pairs = []
for i, row in enumerate(data):
if i == 0 and header:
for j, col in enumerate(row):
if col.strip().lower() == X.strip().lower():
X_idx = j
if col.strip().lower() == y.strip().lower():
y_idx = j
if (X_idx is None or y_idx is None):
raise Exception("Column not found.")
try:
row = [try_cast_str_to_number(item) for item in row]
if row[0] and row[1]:
X_y_pairs.append(row)
except Exception, err:
pass
return X_y_pairs



19 changes: 8 additions & 11 deletions bashplotlib/core/histogram.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
#!/usr/bin/python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""histogram.py
"""
import math
import sys, os
from bashplotlib.utils import helpers
import collections
import sys
import os
from bashplotlib.core import helpers

def calc_bins(n, min_val, max_val, h=None):
"calculate number of bins for the histogram"
Expand All @@ -23,13 +26,12 @@ def read_numbers(numbers):
numbers = [line for line in open(numbers, 'r') if line.strip()]
except Exception, err:
pass
if isinstance(numbers, collections.Iterable):
if helpers.isiterable(numbers):
for number in numbers:
number = helpers.try_cast_str_to_number(number)
if number:
yield number


def plot_hist(data, height=20.0, bincount=None, pch="o", colour="white", title="", xlab=None, showSummary=False):
"""make a histogram for continuous variable.

Expand Down Expand Up @@ -57,7 +59,6 @@ def plot_hist(data, height=20.0, bincount=None, pch="o", colour="white", title="
max_val = number
mean += number
mean /= n

bins = list(calc_bins(n, min_val, max_val, bincount))
hist = {}
for i in range(len(bins)):
Expand Down Expand Up @@ -96,10 +97,7 @@ def plot_hist(data, height=20.0, bincount=None, pch="o", colour="white", title="
helpers.printcolor(" ", True, colour)
print
xs = hist.keys() * 2

print " "*(nlen+1) + "-"*len(xs)


if xlab:
for i in range(0, nlen):
helpers.printcolor(" "*(nlen+1), True, colour)
Expand All @@ -112,7 +110,6 @@ def plot_hist(data, height=20.0, bincount=None, pch="o", colour="white", title="
print
center = max(map(len, map(str, [n, min_val, mean, max_val])))
center += 15

if showSummary:
print
print "-"*(2 + center)
Expand Down
Loading