-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinCollector_analysis_Andreas.py
368 lines (251 loc) · 12.2 KB
/
BinCollector_analysis_Andreas.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
import os
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
import seaborn as sns
import numpy as np
import sys
SMALL_SIZE = 8
MEDIUM_SIZE = 12
BIGGER_SIZE = 16
LARGE_SIZE = 20
plt.rc('font', size=BIGGER_SIZE) # controls default text sizes
plt.rc('axes', titlesize=LARGE_SIZE) # fontsize of the axes title
plt.rc('axes', labelsize=BIGGER_SIZE) # fontsize of the x and y labels
plt.rc('xtick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels
plt.rc('ytick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels
plt.rc('legend', fontsize=BIGGER_SIZE) # legend fontsize
plt.rc('figure', titlesize=LARGE_SIZE) # fontsize of the figure title
# plt.rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
plt.rc('font', family='sans-serif') # Specify a different font family
# def BinCollector_plot(input_file, plot_title):
# df = pd.read_csv(input_file, sep='\t', header=0)
# new_df = pd.DataFrame()
# new_df = pd.concat([df[col].apply(lambda x: int(col) if x != 0 else 0) for col in df.columns], axis=1)
# df1 = df.applymap(lambda x: 1 if x != 0 else x)
# df1['RowSum'] = df1.sum(axis=1)
# df['RowSum'] = new_df.sum(axis=1)
# multi = [r * one for r, one in zip(df['RowSum'].tolist(), df1['RowSum'].tolist())]
# df['RowSum'] = multi
# # Reorder the DataFrame by the sum of row values
# df = df.sort_values(['RowSum'], ascending=True)
# # Remove the 'RowSum' column if desired
# df = df.drop('RowSum', axis=1)
# bars = [df[column].sum() for column in df]
# # Create the figure and axes
# fig, (ax_bar, ax_heatmap) = plt.subplots(2, 1, figsize=(8, 12), gridspec_kw={'height_ratios': [1, 6]}, sharex = True)
# # Create the bar chart
# x = range(len(bars))
# bar_width = 0.9
# ax_bar.bar([i + bar_width/2 for i in x], bars, width=bar_width)
# # Remove the top and right spines from the bar chart
# ax_bar.spines['top'].set_visible(False)
# ax_bar.spines['right'].set_visible(False)
# # Set the desired frequency of tick labels
# tick_frequency = 10
# # Get the number of columns in the DataFrame
# num_columns = len(df.columns)
# # Compute the step value to skip ticks
# step = max(1, num_columns // tick_frequency)
# # Set the x-axis tick positions
# x_ticks = np.arange(0, num_columns, step)
# # Set the x-axis tick labels based on the column names at the chosen positions
# x_tick_labels = df.columns[x_ticks]
# # Set the x-axis ticks and labels for the bar chart
# ax_bar.set_xticks(x_ticks + bar_width / 2)
# ax_bar.set_xticklabels(x_tick_labels, rotation=90)
# # Remove the first tick (zero value) on the y-axis of the bar chart
# ax_bar.set_yticks(ax_bar.get_yticks()[1:])
# ax_bar.set_yticklabels(ax_bar.get_yticks())
# # Create the heatmap
# if len(df) < 100:
# sns.heatmap(df, cmap='YlGnBu', cbar=False, ax=ax_heatmap, yticklabels=True)
# else:
# sns.heatmap(df, cmap='YlGnBu', cbar=False, ax=ax_heatmap, yticklabels=False)
# # Add colorbar next to the heatmap
# cbar_ax = fig.add_axes([0.92, 0.35, 0.02, 0.1]) # Define the position and size of the colorbar
# fig.colorbar(ax_heatmap.get_children()[0], cax=cbar_ax) # Add the colorbar to the specified position
# # Adjust the spacing between subplots
# plt.subplots_adjust(hspace=0)
# # Set the overall title
# plt.suptitle(plot_title)
# # Show the plot
# plt.show()
# def BinCollector_plot(input_file, plot_title):
# df = pd.read_csv(input_file, sep='\t', header=0)
# new_df = pd.DataFrame()
# new_df = pd.concat([df[col].apply(lambda x: int(col) if x != 0 else 0) for col in df.columns], axis=1)
# df1 = df.applymap(lambda x: 1 if x != 0 else x)
# df1['RowSum'] = df1.sum(axis=1)
# df['RowSum'] = new_df.sum(axis=1)
# multi = [r * one for r, one in zip(df['RowSum'].tolist(), df1['RowSum'].tolist())]
# df['RowSum'] = multi
# # Reorder the DataFrame by the sum of row values
# df = df.sort_values(['RowSum'], ascending=True)
# # Remove the 'RowSum' column if desired
# df = df.drop('RowSum', axis=1)
# bars = [df[column].sum() for column in df]
# # Create the figure and axes
# fig, (ax_bar, ax_heatmap) = plt.subplots(2, 1, figsize=(8, 12), gridspec_kw={'height_ratios': [1, 6]}, sharex=True)
# # Set the desired frequency of tick labels
# tick_frequency = 10
# # Get the number of columns in the DataFrame
# num_columns = len(df.columns)
# # Compute the step value to skip ticks
# step = max(1, num_columns // tick_frequency)
# # Set the x-axis tick positions
# x_ticks = np.arange(0, num_columns, step)
# # Set the x-axis tick labels based on the column names at the chosen positions
# x_tick_labels = [df.columns[i] for i in x_ticks]
# # Create the bar chart
# x = range(len(bars))
# bar_width = 0.9
# ax_bar.bar([i + bar_width/2 for i in x], bars, width=bar_width)
# # Remove the top and right spines from the bar chart
# ax_bar.spines['top'].set_visible(False)
# ax_bar.spines['right'].set_visible(False)
# # Set the x-axis ticks and labels for the bar chart
# ax_bar.set_xticks([i + bar_width/2 for i in x_ticks])
# ax_bar.set_xticklabels(x_tick_labels, rotation=90)
# # Remove the first tick (zero value) on the y-axis of the bar chart
# ax_bar.set_yticks(ax_bar.get_yticks()[1:])
# ax_bar.set_yticklabels(ax_bar.get_yticks())
# # Create the heatmap
# if len(df) < 100:
# sns.heatmap(df, cmap='YlGnBu', cbar=False, ax=ax_heatmap, yticklabels=True)
# else:
# sns.heatmap(df, cmap='YlGnBu', cbar=False, ax=ax_heatmap, yticklabels=False)
# # Add colorbar next to the heatmap
# cbar_ax = fig.add_axes([0.92, 0.35, 0.02, 0.1]) # Define the position and size of the colorbar
# fig.colorbar(ax_heatmap.get_children()[0], cax=cbar_ax) # Add the colorbar to the specified position
# # Adjust the spacing between subplots
# plt.subplots_adjust(hspace=0)
# # Set the overall title
# plt.suptitle(plot_title)
# # Show the plot
# plt.show()
# def BinCollector_plot(input_file, plot_title, figure_folder, figure_file_name):
# df = pd.read_csv(input_file, sep='\t', header=0)
# # top200 = pd.read_csv(TPMPW_file, sep = '\t', header = 0)['Gene'].tolist()[:200]
# # df = df[df.index.isin(top200)]
# new_df = pd.DataFrame()
# new_df = pd.concat([df[col].apply(lambda x: int(col) if x != 0 else 0) for col in df.columns], axis=1)
# df1 = df.applymap(lambda x: 1 if x != 0 else x)
# df1['RowSum'] = df1.sum(axis=1)
# df['RowSum'] = new_df.sum(axis=1)
# multi = [r * one for r, one in zip(df['RowSum'].tolist(), df1['RowSum'].tolist())]
# df['RowSum'] = multi
# # Reorder the DataFrame by the sum of row values
# df = df.sort_values(['RowSum'], ascending=True)
# # Remove the 'RowSum' column if desired
# df = df.drop('RowSum', axis=1)
# bars = [df[column].sum() for column in df]
# # Create the figure and axes
# fig, (ax_bar, ax_heatmap) = plt.subplots(2, 1, figsize=(8, 12), gridspec_kw={'height_ratios': [1, 6]}, sharex=True)
# # Create the bar chart
# x = range(len(bars))
# bar_width = 0.9
# ax_bar.bar([i + bar_width/2 for i in x], bars, width=bar_width)
# # Remove the top and right spines from the bar chart
# ax_bar.spines['top'].set_visible(False)
# ax_bar.spines['right'].set_visible(False)
# # Set the x-axis ticks and labels for the bar chart
# x_ticks = range(len(df.columns))
# ax_bar.set_xticks(x_ticks)
# ax_bar.set_xticklabels(df.columns, rotation=90)
# # Adjust the visibility of x-axis tick labels
# tick_frequency = 10 # Show every 10th tick label
# for i, label in enumerate(ax_bar.xaxis.get_ticklabels()):
# if i % tick_frequency != 0:
# label.set_visible(False)
# # Remove the first tick (zero value) on the y-axis of the bar chart
# ax_bar.set_yticks(ax_bar.get_yticks()[1:])
# ax_bar.set_yticklabels(ax_bar.get_yticks())
# # Create the heatmap
# if len(df) < 100:
# sns.heatmap(df, cmap='YlGnBu', cbar=False, ax=ax_heatmap, yticklabels=True)
# else:
# sns.heatmap(df, cmap='YlGnBu', cbar=False, ax=ax_heatmap, yticklabels=False)
# ax_heatmap.tick_params(axis='y', labelsize=10)
# # Add colorbar next to the heatmap
# cbar_ax = fig.add_axes([0.92, 0.35, 0.02, 0.1]) # Define the position and size of the colorbar
# fig.colorbar(ax_heatmap.get_children()[0], cax=cbar_ax) # Add the colorbar to the specified position
# # Adjust the spacing between subplots
# plt.subplots_adjust(hspace=0)
# # Set the overall title
# plt.suptitle(plot_title)
# # Show the plot
# plt.savefig(os.path.join(figure_folder, figure_file_name + '.pdf'), bbox_inches='tight')
# plt.show()
# plt.close()
def BinCollector_plot(input_file, plot_title, figure_folder, figure_file_name, genes_file):
df = pd.read_csv(input_file, sep='\t', header=0)
genes_df = pd.read_csv(genes_file, sep = '\t', names = ['gene'])
genes_df = genes_df[genes_df.index <= 100]
df['root'] = [i.split('.')[0] for i in df.index.values.tolist()]
df = df[df['root'].isin(genes_df['gene'].tolist())]
df = df.drop('root', axis = 1)
row_values = [i for i in range(1, int((len(df.columns) + 2) / 2))]
row_values = row_values + row_values[::-1]
new_df = pd.DataFrame()
for i in range(len(row_values)):
new_df[i] = [-n * row_values[i] for n in df[f'{i + 1}'].tolist()]
# Ensure that the indices of df and new_df match
new_df.index = df.index
df['RowSum2'] = new_df.sum(axis=1)
df1 = df.applymap(lambda x: 1 if x != 0 else x)
df['RowSum1'] = df1.sum(axis=1)
# Reorder the DataFrame by the sum of row values
df = df.sort_values(['RowSum2'], ascending=True)
# Remove the 'RowSum' column if desired
df = df.drop('RowSum1', axis=1)
df = df.drop('RowSum2', axis=1)
# if 'liaG.1' in df.index.values.tolist():
# print('lia yes')
# else:
# print('lia no')
# if 'pghB.2' in df.index.values.tolist():
# print('pghB yes')
# else:
# print('pghB no')
df = df[0:100]
bars = [df[column].sum() for column in df]
# Create the figure and axes
fig, (ax_bar, ax_heatmap) = plt.subplots(2, 1, figsize=(8, 12), gridspec_kw={'height_ratios': [1, 6]}, sharex=True)
# Create the bar chart
x = range(len(bars))
bar_width = 0.9
ax_bar.bar([i + bar_width/2 for i in x], bars, width=bar_width)
# Remove the top and right spines from the bar chart
ax_bar.spines['top'].set_visible(False)
ax_bar.spines['right'].set_visible(False)
# Set the x-axis ticks and labels for the bar chart
x_ticks = range(len(df.columns))
ax_bar.set_xticks(x_ticks)
ax_bar.set_xticklabels(df.columns, rotation=90)
# Adjust the visibility of x-axis tick labels
tick_frequency = 10 # Show every 10th tick label
for i, label in enumerate(ax_bar.xaxis.get_ticklabels()):
if i % tick_frequency != 0:
label.set_visible(False)
# Remove the first tick (zero value) on the y-axis of the bar chart
ax_bar.set_yticks(ax_bar.get_yticks()[1:])
ax_bar.set_yticklabels(ax_bar.get_yticks())
# # Create the heatmap
# if len(df) < 100:
# sns.heatmap(df, cmap='YlGnBu', cbar=False, ax=ax_heatmap, yticklabels=True)
# else:
# sns.heatmap(df, cmap='YlGnBu', cbar=False, ax=ax_heatmap, yticklabels=False)
sns.heatmap(df, cmap='YlGnBu', cbar=False, ax=ax_heatmap, yticklabels=True)
ax_heatmap.tick_params(axis='y', labelsize=10)
# Add colorbar next to the heatmap
cbar_ax = fig.add_axes([0.92, 0.35, 0.02, 0.1]) # Define the position and size of the colorbar
fig.colorbar(ax_heatmap.get_children()[0], cax=cbar_ax) # Add the colorbar to the specified position
# Adjust the spacing between subplots
plt.subplots_adjust(hspace=0)
# Set the overall title
plt.suptitle(plot_title)
# Show the plot
plt.savefig(os.path.join(figure_folder, figure_file_name + '.pdf'), bbox_inches='tight')
plt.show()
plt.close()