Skip to content

Commit c5c7142

Browse files
committed
Merge pull request glamp#17 from iiSeymour/refactor
Some refactoring
2 parents edb0c74 + 1cf7ddc commit c5c7142

File tree

4 files changed

+136
-106
lines changed

4 files changed

+136
-106
lines changed

bashplotlib/histogram.py

Lines changed: 56 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,23 @@
11
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
23

4+
"""
5+
Plotting terminal based histograms
6+
"""
7+
8+
import os
9+
import sys
310
import math
411
import optparse
5-
import os
612
from os.path import dirname
7-
import sys
8-
from utils.helpers import *
9-
from utils.commandhelp import hist
13+
from .utils.helpers import *
14+
from .utils.commandhelp import hist
15+
1016

1117
def calc_bins(n, min_val, max_val, h=None, binwidth=None):
12-
"calculate number of bins for the histogram"
18+
"""
19+
Calculate number of bins for the histogram
20+
"""
1321
if not h:
1422
h = max(10, math.log(n + 1, 2))
1523
if binwidth == 0:
@@ -22,15 +30,17 @@ def calc_bins(n, min_val, max_val, h=None, binwidth=None):
2230
else:
2331
yield b
2432

33+
2534
def read_numbers(numbers):
26-
"read the input data in the most optimal way"
35+
"""
36+
Read the input data in the most optimal way
37+
"""
2738
if isinstance(numbers, list):
28-
for n in numbers:
29-
n = str(n)
30-
yield float(n.strip())
39+
for number in numbers:
40+
yield float(str(number).strip())
3141
else:
32-
for n in open(numbers):
33-
yield float(n.strip())
42+
for number in open(numbers):
43+
yield float(number.strip())
3444

3545

3646
def run_demo():
@@ -53,8 +63,8 @@ def run_demo():
5363
plot_hist(demo_file)
5464
print "*" * 80
5565

56-
#with colors
57-
print "histogram with colors"
66+
#with colours
67+
print "histogram with colours"
5868
print "plot_hist('%s', colour='blue')" % demo_file
5969
print "hist -f %s -c blue" % demo_file
6070
plot_hist(demo_file, colour='blue')
@@ -74,10 +84,11 @@ def run_demo():
7484
plot_hist(demo_file, height=35.0, bincount=40)
7585

7686

77-
def plot_hist(f, height=20.0, bincount=None, binwidth=None, pch="o", colour="white", title="", xlab=None, showSummary=False, regular=False):
78-
"""make a histogram
87+
def plot_hist(f, height=20.0, bincount=None, binwidth=None, pch="o", colour="default", title="", xlab=None, showSummary=False, regular=False):
88+
"""
89+
Make a histogram
7990
80-
Keyword arguments:
91+
Arguments:
8192
height -- the height of the histogram in # of lines
8293
bincount -- number of bins in the histogram
8394
binwidth -- width of bins in the histogram
@@ -88,28 +99,25 @@ def plot_hist(f, height=20.0, bincount=None, binwidth=None, pch="o", colour="whi
8899
showSummary -- boolean value for whether or not to display a summary
89100
regular -- boolean value for whether or not to start y-labels at 0
90101
"""
91-
92102
if pch is None:
93103
pch = "o"
94104

95-
colour = get_colour(colour)
96-
97105
min_val, max_val = None, None
98-
n, mean = 0., 0.
106+
n, mean = 0.0, 0.0
107+
99108
for number in read_numbers(f):
100109
n += 1
101-
102-
if (min_val is None) or (number < min_val):
110+
if min_val is None or number < min_val:
103111
min_val = number
104-
if (max_val is None) or (number > max_val):
112+
if max_val is None or number > max_val:
105113
max_val = number
106114
mean += number
115+
107116
mean /= n
108117

109118
bins = list(calc_bins(n, min_val, max_val, bincount, binwidth))
110-
hist = {}
111-
for i in range(len(bins)):
112-
hist[i] = 0
119+
hist = {i: 0 for i in range(len(bins))}
120+
113121
for number in read_numbers(f):
114122
for i, b in enumerate(bins):
115123
if number <= b:
@@ -122,6 +130,7 @@ def plot_hist(f, height=20.0, bincount=None, binwidth=None, pch="o", colour="whi
122130

123131
start = max(min_y, 1)
124132
stop = max_y + 1
133+
125134
if regular:
126135
start = 1
127136

@@ -138,6 +147,7 @@ def plot_hist(f, height=20.0, bincount=None, binwidth=None, pch="o", colour="whi
138147
if title:
139148
print box_text(title, max(len(hist)*2, len(title)), nlen)
140149
print
150+
141151
used_labs = set()
142152
for y in ys:
143153
ylab = str(int(y))
@@ -151,67 +161,63 @@ def plot_hist(f, height=20.0, bincount=None, binwidth=None, pch="o", colour="whi
151161

152162
for i in range(len(hist)):
153163
if int(y) <= hist[i]:
154-
printcolor(pch, True, colour)
164+
printcolour(pch, True, colour)
155165
else:
156-
printcolor(" ", True, colour)
166+
printcolour(" ", True, colour)
157167
print
158168
xs = hist.keys() * 2
159169

160-
print " "*(nlen+1) + "-"*len(xs)
161-
170+
print " " * (nlen+1) + "-" * len(xs)
162171

163172
if xlab:
164173
xlen = len(str(float((max_y)/height) + max_y))
165174
for i in range(0, xlen):
166-
printcolor(" "*(nlen+1), True, colour)
175+
printcolour(" " * (nlen+1), True, colour)
167176
for x in range(0, len(hist)):
168177
num = str(bins[x])
169-
if x%2==0:
178+
if x % 2 == 0:
170179
print " ",
171180
elif i < len(num):
172181
print num[i],
173182
else:
174183
print " ",
175184
print
185+
176186
center = max(map(len, map(str, [n, min_val, mean, max_val])))
177187
center += 15
178188

179189
if showSummary:
180190
print
181-
print "-"*(2 + center)
191+
print "-" * (2 + center)
182192
print "|" + "Summary".center(center) + "|"
183-
print "-"*(2 + center)
193+
print "-" * (2 + center)
184194
summary = "|" + ("observations: %d" % n).center(center) + "|\n"
185195
summary += "|" + ("min value: %f" % min_val).center(center) + "|\n"
186196
summary += "|" + ("mean : %f" % mean).center(center) + "|\n"
187197
summary += "|" + ("max value: %f" % max_val).center(center) + "|\n"
188-
summary += "-"*(2 + center)
198+
summary += "-" * (2 + center)
189199
print summary
190200

191201

192202
def main():
193203

194204
parser = optparse.OptionParser(usage=hist['usage'])
195205

196-
parser.add_option('-f', '--file', help='a file containing a column of numbers',
197-
default=None, dest='f')
198-
parser.add_option('-t', '--title', help='title for the chart',
199-
default="", dest='t')
200-
parser.add_option('-b', '--bins', help='number of bins in the histogram',
201-
type='int', default=None, dest='b')
202-
parser.add_option('-w', '--binwidth', help='width of bins in the histogram',
203-
type='float', default=None, dest='binwidth')
204-
parser.add_option('-s', '--height', help='height of the histogram (in lines)',
205-
type='int', default=None, dest='h')
206+
parser.add_option('-f', '--file', help='a file containing a column of numbers', default=None, dest='f')
207+
parser.add_option('-t', '--title', help='title for the chart', default="", dest='t')
208+
parser.add_option('-b', '--bins', help='number of bins in the histogram', type='int', default=None, dest='b')
209+
parser.add_option('-w', '--binwidth', help='width of bins in the histogram', type='float', default=None, dest='binwidth')
210+
parser.add_option('-s', '--height', help='height of the histogram (in lines)', type='int', default=None, dest='h')
206211
parser.add_option('-p', '--pch', help='shape of each bar', default='o', dest='p')
207212
parser.add_option('-x', '--xlab', help='label bins on x-axis', default=None, action="store_true", dest='x')
208-
parser.add_option('-c', '--colour', help='colour of the plot (%s)' % ", ".join([c for c in bcolours.keys() if c != 'ENDC']),
209-
default='white', dest='colour')
213+
parser.add_option('-c', '--colour', help='colour of the plot (%s)' % colour_help, default='default', dest='colour')
210214
parser.add_option('-d', '--demo', help='run demos', action='store_true', dest='demo')
211215
parser.add_option('-n', '--nosummary', help='hide summary', action='store_false', dest='showSummary', default=True)
212-
parser.add_option('-r', '--regular', help='use regular y-scale (0 - maximum y value), instead of truncated y-scale (minimum y-value - maximum y-value)', default=False, action="store_true", dest='regular')
216+
parser.add_option('-r', '--regular',
217+
help='use regular y-scale (0 - maximum y value), instead of truncated y-scale (minimum y-value - maximum y-value)',
218+
default=False, action="store_true", dest='regular')
213219

214-
(opts, args) = parser.parse_args()
220+
opts, args = parser.parse_args()
215221

216222
if opts.f is None:
217223
if len(args) > 0:
@@ -227,5 +233,5 @@ def main():
227233
print "nothing to plot!"
228234

229235

230-
if __name__=="__main__":
236+
if __name__ == "__main__":
231237
main()

bashplotlib/scatterplot.py

Lines changed: 24 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
11
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
"""
5+
Plotting terminal based scatterplots
6+
"""
27

38
import csv
4-
import optparse
59
import sys
6-
from utils.helpers import *
7-
from utils.commandhelp import scatter
10+
import optparse
11+
from .utils.helpers import *
12+
from .utils.commandhelp import scatter
813

914

1015
def get_scale(series, is_y=False, steps=20):
@@ -20,10 +25,12 @@ def get_scale(series, is_y=False, steps=20):
2025
scaled_series.reverse()
2126
return scaled_series
2227

28+
2329
def plot_scatter(f, xs, ys, size, pch, colour, title):
24-
"""Form a complex number.
30+
"""
31+
Form a complex number.
2532
26-
Arguments:
33+
Arguments:
2734
f -- comma delimited file w/ x,y coordinates
2835
xs -- if f not specified this is a file w/ x coordinates
2936
ys -- if f not specified this is a filew / y coordinates
@@ -44,14 +51,12 @@ def plot_scatter(f, xs, ys, size, pch, colour, title):
4451
xs = [float(str(row).strip()) for row in open(xs)]
4552
ys = [float(str(row).strip()) for row in open(ys)]
4653

47-
colour = get_colour(colour)
48-
4954
plotted = set()
5055

5156
if title:
5257
print box_text(title, 2*len(get_scale(xs, False, size))+1)
5358

54-
print "-"*(2*len(get_scale(xs, False, size))+2)
59+
print "-" * (2*len(get_scale(xs, False, size))+2)
5560
for y in get_scale(ys, True, size):
5661
print "|",
5762
for x in get_scale(xs, False, size):
@@ -67,30 +72,24 @@ def plot_scatter(f, xs, ys, size, pch, colour, title):
6772
point = "|"
6873
elif y==0:
6974
point = "-"
70-
printcolor(point, True, colour)
75+
printcolour(point, True, colour)
7176
print "|"
7277
print "-"*(2*len(get_scale(xs, False, size))+2)
7378

7479

7580
def main():
7681

7782
parser = optparse.OptionParser(usage=scatter['usage'])
78-
parser.add_option('-f', '--file', help='a csv w/ x and y coordinates',
79-
default=None, dest='f')
80-
parser.add_option('-t', '--title', help='title for the chart',
81-
default="", dest='t')
82-
parser.add_option('-x', help='x coordinates',
83-
default=None, dest='x')
84-
parser.add_option('-y', help='y coordinates',
85-
default=None, dest='y')
86-
parser.add_option('-s', '--size',help='y coordinates',
87-
default=20, dest='size', type='int')
88-
parser.add_option('-p', '--pch',help='shape of point',
89-
default="x", dest='pch')
90-
parser.add_option('-c', '--colour', help='colour of the plot (%s)' % ", ".join(bcolours.keys()),
91-
default='white', dest='colour')
92-
93-
(opts, args) = parser.parse_args()
83+
84+
parser.add_option('-f', '--file', help='a csv w/ x and y coordinates', default=None, dest='f')
85+
parser.add_option('-t', '--title', help='title for the chart', default="", dest='t')
86+
parser.add_option('-x', help='x coordinates', default=None, dest='x')
87+
parser.add_option('-y', help='y coordinates', default=None, dest='y')
88+
parser.add_option('-s', '--size',help='y coordinates', default=20, dest='size', type='int')
89+
parser.add_option('-p', '--pch',help='shape of point', default="x", dest='pch')
90+
parser.add_option('-c', '--colour', help='colour of the plot (%s)' % colour_help, default='default', dest='colour')
91+
92+
opts, args = parser.parse_args()
9493

9594
if opts.f is None and (opts.x is None or opts.y is None):
9695
opts.f = sys.stdin.readlines()

bashplotlib/utils/commandhelp.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,28 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
"""
5+
Usage messages for bashplotlib system commands
6+
"""
17

28
hist = {
39
"usage": """hist is a command for making histograms. it accepts a series of values in one of the following formats:
410
1) txt file w/ 1 column of numbers
5-
2) standard in piped from another command line cat or curl
6-
11+
2) standard in piped from another command line cat or curl
12+
713
for some examples of how to use hist, you can type the command:
814
hist --demo
915
or visit https://github.com/glamp/bashplotlib/blob/master/examples/sample.sh
1016
"""
1117
}
1218

1319
scatter = {
14-
"usage": """scatterplot is a command for making xy plots. it accepts a series of x values and a series of y values in the
20+
"usage": """scatterplot is a command for making xy plots. it accepts a series of x values and a series of y values in the
1521
following formats:
1622
1) a txt file or standard in value w/ 2 comma seperated columns of x,y values
1723
2) 2 txt files. 1 w/ designated x values and another with designated y values.
18-
24+
1925
scatter -x <xcoords> -y <ycoords>
2026
cat <file_with_x_and_y_coords> | scatter
21-
2227
"""
2328
}
24-

0 commit comments

Comments
 (0)