-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_scripts.py
More file actions
374 lines (330 loc) · 10.7 KB
/
Copy pathplot_scripts.py
File metadata and controls
374 lines (330 loc) · 10.7 KB
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
369
370
371
372
373
374
from typing import Sequence
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from scipy import stats
def replace_legend_items(legend, mapping):
for txt in legend.texts:
for k, v in mapping.items():
if txt.get_text() == str(k):
txt.set_text(v)
def set_significance_bars(
sig_data: Sequence[pd.DataFrame],
ax: plt.Axes,
test_type: str,
val_col: str,
group: int = None,
yshift_c: float = None,
font_ylim: float = None,
font_size: str = "small",
font_ndigits: int = 3,
) -> None:
"""Set up significance bars on a plot.
NOTE: this is inplace op to the axes obj.
"""
# set up the significance bars
ls = list(range(len(sig_data)))
combinations = [
(ls[x], ls[x + y]) for y in reversed(ls) for x in range((len(ls) - y))
]
significance_combinations = []
for combination in combinations:
if combination[0] == combination[1]:
continue
data1 = sig_data[combination[0]][val_col]
data2 = sig_data[combination[1]][val_col]
if test_type == "ttest_ind":
t, p = stats.ttest_ind(
data1,
data2,
equal_var=False,
nan_policy="omit",
alternative="two-sided",
)
elif test_type == "mannwhitneyu":
U, p = stats.mannwhitneyu(
data1, data2, alternative="two-sided", nan_policy="omit"
)
significance_combinations.append([combination, p])
bottom, top = ax.get_ylim()
top *= 0.97
y_range = top - bottom
if font_ylim is not None:
y_range = top - font_ylim
for i, significant_combination in enumerate(significance_combinations):
# Columns corresponding to the datasets of interest
if group is not None:
x1 = group - 0.25
x2 = group + 0.25
else:
x1 = significant_combination[0][0]
x2 = significant_combination[0][1]
if x1 == x2:
continue
# What level is this bar among the bars above the plot?
level = len(significance_combinations) - i
# Plot the bar
# yshift = y_range * 0.1 * level
yshift = y_range / (len(combinations) + 1) * level
yshift *= 1.1 + (1 / len(combinations)) # add some padding
if yshift_c is not None:
yshift = yshift_c
# Get height for the bars
bar_height = top - yshift
bar_tips = bar_height - (y_range * 0.02)
ax.plot(
[x1, x1, x2, x2],
[bar_tips, bar_height, bar_height, bar_tips],
lw=1.5,
c="k",
)
# Significance level
p = significant_combination[1]
sig_symbol = str(round(p, ndigits=font_ndigits))
if p < 0.001:
# sig_symbol = "*** p=" + sig_symbol
sig_symbol = "***"
elif p < 0.01:
# sig_symbol = "**" + sig_symbol
sig_symbol = "**"
elif p < 0.05:
# sig_symbol = "* p=" + sig_symbol
sig_symbol = "*"
else:
# sig_symbol = "ns p=" + sig_symbol
sig_symbol = "ns"
text_height = bar_height + 0.0005 # (y_range * 0.025)
ax.text(
(x1 + x2) * 0.5,
text_height,
sig_symbol,
ha="center",
va="bottom",
c="k",
# size=font_size,
size=16,
)
def plot_swarm(
ax: plt.Axes,
data: pd.DataFrame,
group_col: str,
val_col: str,
palette: str,
hue_col: str = None,
hline: str = "mean",
markersize: int = 5,
test_type: str = "mannwhitneyu",
add_boxplot: bool = True,
set_sig_bars: bool = True,
):
assert hline in ["mean", "median", None]
assert test_type in ["mannwhitneyu", "ttest_ind", "chisquare"]
datas_by_group = [
data.loc[data[group_col] == u] for u in sorted(data[group_col].unique())
]
n_groups = len(datas_by_group)
# compute the means/medians
if hline is not None:
if hue_col is not None:
means = data.groupby([group_col, hue_col]).agg(
{val_col: hline},
)[val_col]
else:
means = data.groupby(group_col).agg(
{val_col: hline},
)[val_col]
dd = data.reset_index(drop=True).set_index(group_col)
tidy = dd[[val_col]]
tidy = tidy.stack()
tidy = tidy.reset_index()
tidy = tidy.rename(
columns={
group_col: group_col.replace("_", " ").title(),
"level_1": "Attribute",
0: val_col.replace("_", " ").title(),
}
)
if hue_col is not None:
hue = dd[[hue_col]]
hue = hue.stack()
hue = hue.reset_index()
hue = hue.rename(
columns={
hue_col: hue_col.replace("_", " ").title(),
"level_1": "Attribute 2",
0: hue_col.replace("_", " ").title(),
}
)
tidy = pd.concat([tidy, hue], axis=1).drop(columns=["Attribute 2"])
if hline is not None:
if hue_col is not None:
mean_colors = list(
sns.color_palette(
f"{palette}_r",
n_colors=len(tidy[hue_col.replace("_", " ").title()].unique()),
).as_hex()
) * len(tidy[group_col.replace("_", " ").title()].unique())
else:
mean_colors = sns.color_palette(palette, n_colors=len(means)).as_hex()
feat_vals = tidy[val_col.replace("_", " ").title()]
if set_sig_bars:
ymax_multiplier = 1.30 if hue_col is None else n_groups * 0.6
ax.set(
ylim=(
max(feat_vals.min() - feat_vals.std() * 2.5, 0 - feat_vals.std()),
(feat_vals.max() + feat_vals.std() * 2.5) * ymax_multiplier,
)
)
hue = group_col.replace("_", " ").title()
if hue_col is not None:
hue = hue_col.replace("_", " ").title()
ax = sns.swarmplot(
ax=ax,
data=tidy,
y=val_col.replace("_", " ").title(),
x=group_col.replace("_", " ").title(),
hue=hue,
size=markersize,
orient="v",
legend="auto" if hue_col is not None else False,
warn_thresh=0.99,
palette=palette if hue_col is None else f"{palette}_r",
alpha=0.5,
order=sorted(data[group_col].unique()),
hue_order=sorted(data[group_col].unique()) if hue_col is None else None,
dodge=True if hue_col is not None else False,
)
if hline is not None:
if hue_col is not None:
prev_group = ""
xpos = 0
for i, (k1, k2) in enumerate(sorted(means.keys())):
if k1 == prev_group:
xmin = xpos
xmax = xpos + 0.4
xpos += 1
else:
xmin = xpos - 0.4
xmax = xpos
ax.hlines(
means[k1, k2],
color=mean_colors[i],
xmin=xmin + 0.25,
xmax=xmax - 0.25,
linestyle="--",
linewidth=2,
)
prev_group = k1
else:
for i, k in enumerate(sorted(means.keys())):
ax.hlines(
means[k],
color=mean_colors[i],
xmin=i - 0.5 + 0.25,
xmax=i + 1 - 0.5 - 0.25,
linestyle="--",
linewidth=2,
)
bottom, top = ax.get_ylim()
# set up the significance bars
if set_sig_bars:
set_significance_bars(
datas_by_group,
ax,
test_type,
val_col=val_col,
font_ylim=feat_vals.max(),
)
if hue_col is not None:
for i, dataset in enumerate(datas_by_group):
sig_data_hue = [
dataset.loc[dataset[hue_col] == u]
for u in sorted(dataset[hue_col].unique())
]
if len(sig_data_hue) > 1:
set_significance_bars(
sig_data_hue,
ax,
test_type,
val_col=val_col,
group=i,
yshift_c=top - (feat_vals.max() + feat_vals.std() * 1.2),
)
# Annotate sample size below each box
# y_range = top - bottom
# for i, dataset in enumerate(datas_by_group):
# sample_size = len(dataset)
# ax.text(
# i,
# bottom + (0.005 * y_range),
# rf"$n = {sample_size}$",
# ha="center",
# # size="x-small",
# size=16,
# )
if add_boxplot:
ax = sns.boxplot(
ax=ax,
data=data,
x=group_col,
y=val_col,
showfliers=False,
color="black",
linewidth=1.5,
width=0.2,
order=sorted(data[group_col].unique()),
fill=False,
whis=1.0,
showcaps=False,
)
if hue_col is not None:
ax.legend(loc="center left", bbox_to_anchor=(1, 0.5))
return ax
def plot_distss(
data: pd.DataFrame,
group_col: str,
val_col: str,
palette: str,
hue_col: str = None,
figsize: tuple = (14, 7),
out_fname: str = None,
test_type: str = "mannwhitneyu",
hline: str = "mean",
title: str = None,
fontsize: int = 18,
add_boxplot: bool = True,
rotate_xticks: bool = False,
set_sig_bars: bool = True,
ylab: str = None,
):
fig, ax = plt.subplots(1, 1, figsize=figsize)
# replace legend using handles and labels from above
ax = plot_swarm(
ax=ax,
data=data,
group_col=group_col,
val_col=val_col,
palette=palette,
hline=hline,
hue_col=hue_col,
test_type=test_type,
add_boxplot=add_boxplot,
set_sig_bars=set_sig_bars,
)
if rotate_xticks:
ax.set_xticklabels(ax.get_xticklabels(), rotation=35)
# ax.set_xlabel(group_col.replace("_", " ").title(), fontsize=18)
ax.set_xlabel("")
# ax.set_yticks([])
# ax.set_ylabel("")
ax.set_xticklabels([label.get_text().split()[-1] for label in ax.get_xticklabels()])
print([tick for tick in ax.get_yticks()])
ax.set_yticks([tick for tick in ax.get_yticks() if 0.0 <= tick <= 1.1])
ax.set_yticklabels([f"{tick:.1f}" for tick in ax.get_yticks()])
ax.set_ylabel(ylab, fontsize=18)
ax.tick_params(labelsize=16)
if title is not None:
fig.suptitle(title, fontsize=fontsize)
if out_fname is not None:
fig.savefig(out_fname)
return ax