forked from lpryszcz/bin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plot.py
executable file
·184 lines (165 loc) · 7.25 KB
/
plot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
#!/usr/bin/env python
desc="""Plot histogram
"""
epilog="""Author:
l.p.pryszcz+git@gmail.com
Barcelona, 29/11/2012
"""
import argparse, os, sys, random
from datetime import datetime
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from scipy.stats import stats, wilcoxon, ranksums
def group_values(x, y):
"""Group values in y to seperate lists using x"""
key2group = {}
for k, v in zip(x, y):
if k not in key2group:
key2group[k] = []
key2group[k].append(v)
return [v for k, v in sorted(key2group.iteritems())]
def pairwise_wilcoxon(x, y, bootstrapping=10, ranksums=ranksums):
"""Return pairwise wilcoson stats"""
setx = set(x)
sety = set(y)
if len(setx)<20:
values = group_values(x, y)
elif len(sety)<20:
values = group_values(y, x)
else:
return
# 1 vs rest
first = values[0]
second = [i for items in values[1:] for i in items]
t, p = ranksums(first, second)
print " mean first: %s +/- %s\n mean the_rest: %s +/- %s"%(np.mean(first), np.std(first), np.mean(second), np.std(second))
print "Wilcoxon first-vs-the_rest (N=%s vs N=%s): T=%s p=%s" % ((len(first), len(second), t, p))
# first -vs - second
second = values[1]
t, p = ranksums(first, second)
print " mean first: %s +/- %s\n mean seond: %s +/- %s"%(np.mean(first), np.std(first), np.mean(second), np.std(second))
print "Wilcoxon first-vs-second (N=%s vs N=%s): T=%s p=%s" % ((len(first), len(second), t, p))
'''for i in range(bootstrapping):
sfirst = random.sample(first, len(rest))
t, p = wilcoxon(sfirst, rest)
print "%s Wilcoxon (1st-vs-rest): T=%s p=%s" % (i+1, t, p)'''
def plot(handle, out, cols, names, bins, title, xlab, ylab, xlog, ylog, \
vmax, vmin, vMinSum, collapse, normed, alpha, legendLoc, colors,\
verbose, dlimit=1):
"""
"""
if verbose:
sys.stderr.write( "Parsing data...\n" )
x = [[] for i in range(len(cols))]
for l in handle:
try:
ldata = l[:-1].split('\t')
vals = []
for col in cols:
if col>=len(ldata) or not ldata[col]:
continue
v=float(ldata[col])
if vmin<v<vmax:
vals.append(v)
#skip entire line if one value out of bounds
# or if sum of values below threshold
if len(vals)!=len(cols) or sum(vals)<vMinSum:
continue
for i, v in enumerate(vals):
x[i].append(v)
except:
sys.stderr.write("[Error] Cannot parse line: %s\n" % ",".join(l.split('\t')))
if verbose:
sys.stderr.write( " %s values loaded.\n" % len(x) )
fig = plt.figure()
#http://matplotlib.org/users/customizing.html
#mpl.rcParams['figure.subplot.wspace'] = 0.3
'''mpl.rcParams['figure.subplot.hspace'] = 0.5
mpl.rcParams['axes.titlesize'] = 8
mpl.rcParams['axes.labelsize'] = 6
mpl.rcParams['xtick.labelsize'] = 5
mpl.rcParams['ytick.labelsize'] = 5'''
#add subplots
plt.rc('axes', color_cycle=colors) #['c', 'm', 'y', 'k']
#plot
x, y = x
# get correlation
print "%s points\n mean X: %s +/- %s\n mean Y: %s +/- %s"%(len(x), np.mean(x), np.std(x), np.mean(y), np.std(y))
print "Pearson: r=%s p=%s" % stats.pearsonr(x, y)
print "Spearman: r=%s p=%s" % stats.spearmanr(x, y)
print "Wilcoxon: T=%s p=%s" % ranksums(x, y) # wilcoxon(x, y)
pairwise_wilcoxon(x, y)
ax = fig.add_subplot(111)
ax.plot(x, y, 'b.', alpha=0.5)
#add title
ax.set_title(title)
#add subplots labels
ax.set_xlabel(xlab)#, fontsize=30)
ax.set_ylabel(ylab)#, fontsize=30)
#plot legend only if collapsed
if xlog:
ax.set_xscale('log')
if ylog:
ax.set_yscale('log', nonposy='clip')
ax.grid(True)
#save or show
if type(out) is file and out.name=='<stdout>':
plt.show()
else:
fpath = out #handle.name+".png"
fformat = fpath.split('.')[-1]
plt.savefig(fpath, dpi=300, format=fformat, orientation='landscape', transparent=False)
sys.stderr.write("Figure written to: %s\n" % fpath)
def main():
usage = "%(prog)s [options] -v"
parser = argparse.ArgumentParser( usage=usage,description=desc,epilog=epilog )
parser.add_argument("-v", "--verbose", default=False, action="store_true", help="verbose")
parser.add_argument('--version', action='version', version='1.0')
parser.add_argument("-i", "--input", default=sys.stdin, type=file,
help="input [stdin]")
parser.add_argument("-o", "--output", default=sys.stdout,
help="input [stdout]")
parser.add_argument("-b", "--bins", default=100, type=int,
help="number of bins [%(default)s]")
parser.add_argument("-c", "--col", default=[1, 2], nargs="+", type=int,
help="columns to use [%(default)s]")
parser.add_argument("-n", "--names", default="", nargs="+",
help="column names [%(default)s]")
parser.add_argument("-t", "--title", default="Histogram",
help="histogram title [%(default)s]")
parser.add_argument("-x", "--xlab", default="",
help="x-axis label [%(default)s]")
parser.add_argument("-y", "--ylab", default="",
help="y-axis label [%(default)s]")
parser.add_argument("--ylog", "--log", default=False, action="store_true",
help="log Y scale")
parser.add_argument("--xlog", default=False, action="store_true",
help="log X scale")
parser.add_argument("--max", default=float('inf'), type=float,
help="max value [%(default)s]")
parser.add_argument("--min", default=float('-inf'), type=float,
help="min value [%(default)s]")
parser.add_argument("--vMinSum", default=float('-inf'), type=float,
help="min Sum of values [%(default)s]")
parser.add_argument("--collapse", default=False, action="store_true",
help="collapse into single subplot")
parser.add_argument("--normed", default=0, choices=(0, 1), type=int,
help="normalise values")
parser.add_argument("--alpha", default=0.75, type=float,
help="plot alpha [%(default)s]")
parser.add_argument("--colors", nargs="+", default=['b', 'grey', 'r', 'y', 'g'],
help="plot alpha [%(default)s]")
parser.add_argument("--legendLoc", default=1, choices=(1, 2, 3, 4), type=int,
help="legend location (1=top right, 2=top left, 3=bottom left, 4=bottom right")
o = parser.parse_args()
if o.verbose:
sys.stderr.write( "Options: %s\n" % str(o) )
plot(o.input, o.output, o.col, o.names, o.bins, o.title, o.xlab, o.ylab, \
o.xlog, o.ylog, o.max, o.min, o.vMinSum, o.collapse, o.normed, o.alpha, o.legendLoc, \
o.colors, o.verbose)
if __name__=='__main__':
t0 = datetime.now()
main()
dt = datetime.now()-t0
sys.stderr.write( "#Time elapsed: %s\n" % dt )