Skip to content

Commit 767c14f

Browse files
author
Michael Wang
committed
bug fix for scatterplot: 1). add delimiter, default to tab; 2). default scatter colour to None to remove strange characters in pipe output; 3). fix broken pipe during piping
1 parent 83410e9 commit 767c14f

File tree

2 files changed

+52
-65
lines changed

2 files changed

+52
-65
lines changed

bashplotlib/scatterplot.py

Lines changed: 44 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,15 @@
1212
from .utils.helpers import *
1313
from .utils.commandhelp import scatter
1414

15+
from signal import signal, SIGPIPE, SIG_DFL
16+
signal(SIGPIPE,SIG_DFL)
17+
1518

1619
def get_scale(series, is_y=False, steps=20):
1720
min_val = min(series)
1821
max_val = max(series)
1922
scaled_series = []
20-
for x in drange(min_val, max_val, (max_val - min_val) / steps,
21-
include_stop=True):
23+
for x in drange(min_val, max_val, (max_val - min_val) / steps):
2224
if x > 0 and scaled_series and max(scaled_series) < 0:
2325
scaled_series.append(0.0)
2426
scaled_series.append(x)
@@ -28,61 +30,58 @@ def get_scale(series, is_y=False, steps=20):
2830
return scaled_series
2931

3032

31-
def _plot_scatter(xs, ys, size, pch, colour, title, cs):
32-
plotted = set()
33-
34-
if title:
35-
print(box_text(title, 2 * len(get_scale(xs, False, size)) + 1))
36-
37-
print("-" * (2 * len(get_scale(xs, False, size)) + 2))
38-
for y in get_scale(ys, True, size):
39-
print("|", end=' ')
40-
for x in get_scale(xs, False, size):
41-
point = " "
42-
for (i, (xp, yp)) in enumerate(zip(xs, ys)):
43-
if xp <= x and yp >= y and (xp, yp) not in plotted:
44-
point = pch
45-
plotted.add((xp, yp))
46-
if cs:
47-
colour = cs[i]
48-
printcolour(point, True, colour)
49-
print(" |")
50-
print("-" * (2 * len(get_scale(xs, False, size)) + 2))
51-
52-
def plot_scatter(f, xs, ys, size, pch, colour, title):
33+
def plot_scatter(f, xs, ys, size, pch, colour, title, delimiter):
5334
"""
5435
Form a complex number.
5536
5637
Arguments:
57-
f -- comma delimited file w/ x,y coordinates
38+
f -- delimited (by delimiter) file w/ x,y coordinates
5839
xs -- if f not specified this is a file w/ x coordinates
5940
ys -- if f not specified this is a filew / y coordinates
6041
size -- size of the plot
6142
pch -- shape of the points (any character)
6243
colour -- colour of the points
6344
title -- title of the plot
6445
"""
65-
cs = None
46+
6647
if f:
6748
if isinstance(f, str):
68-
with open(f) as fh:
69-
data = [tuple(line.strip().split(',')) for line in fh]
70-
else:
71-
data = [tuple(line.strip().split(',')) for line in f]
72-
xs = [float(i[0]) for i in data]
73-
ys = [float(i[1]) for i in data]
74-
if len(data[0]) > 2:
75-
cs = [i[2].strip() for i in data]
76-
elif isinstance(xs, list) and isinstance(ys, list):
77-
pass
49+
f = open(f)
50+
51+
data = [tuple(map(float, line.strip().split(delimiter))) for line in f]
52+
xs = [i[0] for i in data]
53+
ys = [i[1] for i in data]
7854
else:
79-
with open(xs) as fh:
80-
xs = [float(str(row).strip()) for row in fh]
81-
with open(ys) as fh:
82-
ys = [float(str(row).strip()) for row in fh]
55+
xs = [float(str(row).strip()) for row in open(xs)]
56+
ys = [float(str(row).strip()) for row in open(ys)]
8357

84-
_plot_scatter(xs, ys, size, pch, colour, title, cs)
85-
58+
plotted = set()
59+
60+
if title:
61+
print(box_text(title, 2 * len(get_scale(xs, False, size)) + 1))
62+
63+
print("-" * (2 * len(get_scale(xs, False, size)) + 2))
64+
for y in get_scale(ys, True, size):
65+
print("|", end=' ')
66+
for x in get_scale(xs, False, size):
67+
point = " "
68+
for (i, (xp, yp)) in enumerate(zip(xs, ys)):
69+
if xp <= x and yp >= y and (xp, yp) not in plotted:
70+
point = pch
71+
#point = str(i)
72+
plotted.add((xp, yp))
73+
if x == 0 and y == 0:
74+
point = "o"
75+
elif x == 0:
76+
point = "|"
77+
elif y == 0:
78+
point = "-"
79+
if colour:
80+
printcolour(point, True, colour)
81+
else:
82+
print(point, end='')
83+
print("|")
84+
print("-" * (2 * len(get_scale(xs, False, size)) + 2))
8685

8786

8887
def main():
@@ -94,17 +93,18 @@ def main():
9493
parser.add_option('-x', help='x coordinates', default=None, dest='x')
9594
parser.add_option('-y', help='y coordinates', default=None, dest='y')
9695
parser.add_option('-s', '--size', help='y coordinates', default=20, dest='size', type='int')
96+
parser.add_option('-d', '--delimiter', help='delimiter', default="\t", dest='delimiter')
9797
parser.add_option('-p', '--pch', help='shape of point', default="x", dest='pch')
9898
parser.add_option('-c', '--colour', help='colour of the plot (%s)' %
99-
colour_help, default='default', dest='colour')
99+
colour_help, default=None, dest='colour')
100100

101101
opts, args = parser.parse_args()
102102

103103
if opts.f is None and (opts.x is None or opts.y is None):
104104
opts.f = sys.stdin.readlines()
105105

106106
if opts.f or (opts.x and opts.y):
107-
plot_scatter(opts.f, opts.x, opts.y, opts.size, opts.pch, opts.colour, opts.t)
107+
plot_scatter(opts.f, opts.x, opts.y, opts.size, opts.pch, opts.colour, opts.t, opts.delimiter)
108108
else:
109109
print("nothing to plot!")
110110

bashplotlib/utils/helpers.py

Lines changed: 8 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -20,30 +20,29 @@
2020
"grey": '\033[90m',
2121
"black": '\033[30m',
2222
"default": '\033[39m',
23+
"none": '',
2324
"ENDC": '\033[39m',
2425
}
2526

2627
colour_help = ', '.join([colour for colour in bcolours if colour != "ENDC"])
2728

2829

29-
def get_colour(colour, default="default"):
30+
def get_colour(colour):
3031
"""
3132
Get the escape code sequence for a colour
3233
"""
33-
return bcolours.get(colour, bcolours[default])
34+
return bcolours.get(colour, bcolours['ENDC'])
3435

3536

36-
def printcolour(text, sameline=False, colour="default"):
37+
def printcolour(text, sameline=False, colour=get_colour("ENDC")):
3738
"""
3839
Print color text using escape codes
3940
"""
40-
sep = '' if sameline else '\n'
41-
42-
# If no colour set, do not print color ESC characters
43-
if get_colour(colour) == get_colour("ENDC"):
44-
sys.stdout.write(text + sep)
41+
if sameline:
42+
sep = ''
4543
else:
46-
sys.stdout.write(get_colour(colour) + text + get_colour("ENDC") + sep)
44+
sep = '\n'
45+
sys.stdout.write(get_colour(colour) + text + bcolours["ENDC"] + sep)
4746

4847

4948
def drange(start, stop, step=1.0, include_stop=False):
@@ -66,18 +65,6 @@ def drange(start, stop, step=1.0, include_stop=False):
6665
r = round(r, 10)
6766

6867

69-
def abbreviate(labels, rfill=' '):
70-
"""
71-
Abbreviate labels without introducing ambiguities.
72-
"""
73-
max_len = max(len(l) for l in labels)
74-
for i in range(1, max_len):
75-
abbrev = [l[:i].ljust(i, rfill) for l in labels]
76-
if len(abbrev) == len(set(abbrev)):
77-
break
78-
return abbrev
79-
80-
8168
def box_text(text, width, offset=0):
8269
"""
8370
Return text inside an ascii textbox

0 commit comments

Comments
 (0)