-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathallBoxPlots.py
284 lines (255 loc) · 12 KB
/
allBoxPlots.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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import pandas as pd
import numpy as np
import argparse
import glob
import seaborn
from statannot import add_stat_annotation
import matplotlib.pyplot as plt
import itertools
import os
import warnings
warnings.filterwarnings('ignore')
def makeViolinPlot(file_lst, degpath, savepath):
li = []
intersection = False
for filename in file_lst:
temp = filename.split('/')[-1].replace('.', '_').split("_") #[2:-1]
print(temp)
# for genes unique to a specific experimental condition, ie. non-overlapping group
if len(temp) < 10:
# read bed file into dataframe
df = pd.read_csv(filename, sep="\t", names=['chr', 'start', 'end', 'gene_id', 'score', 'gene_name'])
n = str(len(df.index))
splitname = filename.split('/')[-1].replace('.', '_').split("_")
print(splitname)
# get file base name, shorter if embryo which is unsexed
if 'e' in splitname:
file1 = "_".join(splitname[1:-1])
else:
file1 = "_".join(splitname[1:-1])
# read csv with expression data into dataframe and get gene fold changes
mag_fold1 = pd.read_csv(degpath + '/' + file1 + ".csv")
print(mag_fold1.head())
mag_fold1 = mag_fold1[['log2FoldChange']].astype(float)
print(mag_fold1.head())
# add stuff into df
df['log2FoldChange'] = mag_fold1['log2FoldChange'].tolist()
df['dataset'] = file1
df['overlap'] = file1 + ' (n:' + n + ')'
# append dataframe to overall list for later visualization
li.append(df)
else: # for intersection of genes between two experimental conditions, ie. overlapping group
# read bed file into dataframe
intersection = True
splitname = filename.split('\\')[-1].replace('.', '_').split("_")
print(splitname)
# get base names of each files, shorter if embryo which is unsexed
if 'e' in temp:
fullfile = "_".join(splitname[1:7])
file1 = "_".join(splitname[1:4])
file2 = "_".join(splitname[4:7])
else:
fullfile = "_".join(splitname[1:9])
file1 = "_".join(splitname[1:5])
file2 = "_".join(splitname[5:9])
# read csv with expression data for first experimental condition into dataframe and get gene fold changes
df = pd.read_csv(filename, sep="\t", names=['chr', 'start', 'end', 'gene_id', 'score', 'gene_name'])
n = str(len(df.index))
mag_fold1 = pd.read_csv(degpath + '/' + file1 + ".csv")
mag_fold1 = mag_fold1[['log2FoldChange']].astype(float)
# add stuff to df
df['log2FoldChange'] = mag_fold1
df['dataset'] = file1
df['overlap'] = fullfile + ' (n:' + n + ')'
# append dataframe for first set to overall list for later visualization
li.append(df)
# read csv with expression data for first experimental condition into dataframe and get gene fold changes
df = pd.read_csv(filename, sep="\t", names=['chr', 'start', 'end', 'gene_id', 'score', 'gene_name'])
n = str(len(df.index))
mag_fold2 = pd.read_csv(degpath + '/' + file2 + ".csv")
mag_fold2 = mag_fold2[['log2FoldChange']].astype(float)
# add stuff to df
df['log2FoldChange'] = mag_fold2
df['dataset'] = file2
df['overlap'] = fullfile + ' (n:' + n + ')'
# append dataframe for first set to overall list for later visualization
li.append(df)
# concatenate list into single larger dataframe
frame = pd.concat(li, axis=0, ignore_index=True)
# generate empty plot
plt.figure(figsize=(9,5))
if not intersection:
unique_datasets = frame['dataset'].unique()
if len(unique_datasets) >= 2:
# determine up and down regulated gene sets
done_up = False
done_down = False
upreg_set = unique_datasets[0]
downreg_set = unique_datasets[1]
for d in unique_datasets:
if 'upreg' in d and not done_up:
upreg_set = d
done_up = True
elif 'downreg' in d and not done_down:
downreg_set = d
done_down = False
elif 'upreg' in d and done_up:
downreg_set = d
done_down = False
elif 'downreg' in d and done_down:
upreg_set = d
done_up = True
# set colors for different groups
my_pal = {upreg_set: "#af8dc3", downreg_set: "#7fbf7b"}
elif intersection:
unique_datasets = frame['overlap'].unique()
if len(unique_datasets) >= 2:
# determine up and down regulated gene sets
done_up = False
done_down = False
upreg_set = unique_datasets[0]
downreg_set = unique_datasets[1]
for d in unique_datasets:
if 'upreg' in d and not done_up:
upreg_set = d
done_up = True
elif 'downreg' in d and not done_down:
downreg_set = d
done_down = False
elif 'upreg' in d and done_up:
downreg_set = d
done_down = False
elif 'downreg' in d and done_down:
upreg_set = d
done_up = True
# my_pal = {"clampi_e_upreg (n:456)": "#af8dc3", "clampi_e_downreg (n:377)":"#7fbf7b"}
# my_pal = {"msl2i_A_m_upreg": "#af8dc3", "msl2i_A_m_downreg": "#7fbf7b"}
# set colors for different groups
my_pal = {upreg_set: "#af8dc3", downreg_set: "#7fbf7b"}
# get all unique datasets (experimental conditions) from dataframe, frame
unique_datasets = frame['dataset'].unique()
# create combinations of size 2
subsets3 = list(itertools.combinations(unique_datasets, 2))
print(subsets3)
# box_pairs_lst = []
# for pair in subsets3:
# tup1,tup2 = pair
# ds1,chr1 = tup1
# ds2,chr2 = tup2
# if ds1 == ds2 or chr1 == chr2:
# box_pairs_lst.append(pair)
box_pairs_lst = subsets3
# get all possible subsets of these combinations
all_ss = []
for L in range(1, len(box_pairs_lst)+1):
for ss in itertools.combinations(box_pairs_lst, L):
all_ss.append(list(ss))
# sort subsets for largest to smallest by length
all_ss_sorted = sorted(all_ss, key=len, reverse=True)
# for each of these subsets try to create the statistical significance bars between different groups
# using the Mann-Whitney test
for blabla in all_ss_sorted:
try:
if not intersection:
# make violin plot of dataset (experimental condition) vs log2FoldChange
plt.figure(figsize=(8,5))
g = seaborn.violinplot(x="dataset", y="log2FoldChange", data=frame, palette=my_pal)
# add significance bars
add_stat_annotation(g, data=frame, x="dataset", y="log2FoldChange",
box_pairs=blabla,
test='Mann-Whitney', text_format='star', loc='outside', verbose=2)
plt.tight_layout(pad=2)
plt.tick_params(axis='x', pad=17)
# add sample size (n: _) under each of the violin groups
nobs = frame.groupby(['dataset']).apply(lambda x: 'n: {}'.format(len(x)))
ymin,ymax = g.get_ylim()
for ax in plt.gcf().axes:
for tick, label in enumerate(ax.get_xticklabels()):
ax_dat = label.get_text()
x_offset = 0
num = nobs[ax_dat]
ax.text(tick + x_offset, ymin - abs(0.0686*(ymax-ymin)), num, #ymin - 0.25
horizontalalignment='center', size='medium', color='green', weight='semibold')
# get title and save figure
fig = g.get_figure()
# if 'e' in splitname:
# figtit = "_".join(splitname[2:5])
# else:
# figtit = "_".join(splitname[2:6])
figtit = "_".join(frame['dataset'].unique())
fig.savefig(savepath + '/overall_violin_'+figtit+'.png')
elif intersection:
# make violin plot of dataset (experimental condition) vs log2FoldChange
print(my_pal)
print(frame['overlap'].unique())
plt.figure(figsize=(9,5))
g = seaborn.violinplot(x="dataset", y="log2FoldChange", data=frame, hue="overlap", palette=my_pal)
plt.legend(title='Groups with Same Genes', bbox_to_anchor=(1.05,1), loc=2)
g.set_xticklabels(g.get_xticklabels(), rotation=15)
# add significance bars
add_stat_annotation(g, data=frame, x="dataset", y="log2FoldChange",
box_pairs=blabla,
test='Mann-Whitney', text_format='star', loc='outside', verbose=2)
plt.tight_layout(pad=2)
# get title and save figure
fig = g.get_figure()
# if 'e' in splitname:
# figtit = "_".join(splitname[1:-1])
# else:
# figtit = "_".join(splitname[1:-1])
titlst = []
for el in frame['overlap'].unique():
overlap_name = el.split(' ')[0]
titlst.append(overlap_name)
figtit = "_".join(titlst)
fig.savefig(savepath + '/overall_violin_'+figtit+'.png')
break
except ValueError:
continue
# plt.tight_layout(pad=2)
# plt.tick_params(axis='x', pad=17)
# # add sample size (n: _) under each of the violin groups
# medians = frame.groupby(['dataset'])['log2FoldChange'].median()
# mins = frame.groupby(['dataset'])['log2FoldChange'].min()
# nobs = frame.groupby(['dataset']).apply(lambda x: 'n: {}'.format(len(x)))
# ymin,ymax = g.get_ylim()
# for ax in plt.gcf().axes:
# for tick, label in enumerate(ax.get_xticklabels()):
# ax_dat = label.get_text()
# x_offset = 0
# min_val = mins[ax_dat]
# num = nobs[ax_dat]
# ax.text(tick + x_offset, ymin - abs(0.0686*(ymax-ymin)), num, #ymin - 0.25
# horizontalalignment='center', size='medium', color='green', weight='semibold')
# get title and save figure
# fig = g.get_figure()
# if 'e' in splitname:
# figtit = "_".join(splitname[2:5])
# else:
# figtit = "_".join(splitname[2:6])
# fig.savefig('overall_violin_'+figtit+'.png')
def main():
# create the command line parser
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--filepath", default='hello.bed', help="path to bed file to get basic gene data")
parser.add_argument("-d", "--degpath", default='hello.csv', help="path to csv file to get deg data")
parser.add_argument("-s", "--savepath", default='.', help="path to save figures")
args = parser.parse_args()
data = args.filepath
degpath = args.degpath
savepath = args.savepath
# get list of bed files with genes sets to compare
all_files = glob.glob(data + "/*.bed")
if not os.path.isdir(os.getcwd()+'/comparisons/overall_boxplots'):
os.mkdir(os.getcwd()+'/comparisons/overall_boxplots')
for idx,f in enumerate(all_files):
print(f)
makeViolinPlot([f], degpath, savepath)
remaining_files = all_files[idx+1:]
for f2 in remaining_files:
file_lst = [f,f2]
makeViolinPlot(file_lst, degpath, savepath)
# break
# break
if __name__ == "__main__":
main()