-
Notifications
You must be signed in to change notification settings - Fork 114
/
plot.py
1599 lines (1474 loc) · 56.6 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
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import operator
import sys
import warnings
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms
import numpy as np
import pandas as pd
import scipy.cluster.hierarchy as sch
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.category import UnitData
from matplotlib.colors import Normalize
from matplotlib.figure import Figure
from matplotlib.lines import Line2D
from matplotlib.ticker import MaxNLocator
from gseapy.scipalette import SciPalette
class MidpointNormalize(Normalize):
def __init__(self, vmin=None, vmax=None, vcenter=None, clip=False):
self.vcenter = vcenter
Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
# Note also that we must extrapolate beyond vmin/vmax
x, y = [self.vmin, self.vcenter, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y, left=-np.inf, right=np.inf))
def inverse(self, value):
y, x = [self.vmin, self.vcenter, self.vmax], [0, 0.5, 1]
return np.interp(value, x, y, left=-np.inf, right=np.inf)
def zscore(data2d: pd.DataFrame, axis: Optional[int] = 0):
"""Standardize the mean and variance of the data axis Parameters.
:param data2d: DataFrame to normalize.
:param axis: int, Which axis to normalize across. If 0, normalize across rows,
if 1, normalize across columns. If None, don't change data
:Returns: Normalized DataFrame. Normalized data with a mean of 0 and variance of 1
across the specified axis.
"""
if axis is None:
# normalized to mean and std using entire matrix
# z_scored = (data2d - data2d.values.mean()) / data2d.values.std(ddof=1)
return data2d
assert axis in [0, 1]
z_scored = data2d.apply(
lambda x: (x - x.mean()) / x.std(ddof=1), axis=operator.xor(1, axis)
)
return z_scored
class Heatmap(object):
def __init__(
self,
df: pd.DataFrame,
z_score: Optional[int] = None,
title: Optional[str] = None,
figsize: Tuple[float, float] = (5, 5),
cmap: Optional[str] = None,
xticklabels: bool = True,
yticklabels: bool = True,
ofname: Optional[str] = None,
**kwargs,
):
self.title = "" if title is None else title
self.figsize = figsize
self.xticklabels = xticklabels
self.yticklabels = yticklabels
self.ofname = ofname
# scale dataframe
df = df.astype(float)
df = zscore(df, axis=z_score)
df = df.iloc[::-1]
self.data = df
self.cbar_title = "Norm.Exp" if z_score is None else "Z-Score"
self.cmap = cmap
if cmap is None:
self.cmap = SciPalette.create_colormap() # navyblue2darkred
self._zscore = z_score
def _skip_ticks(self, labels, tickevery):
"""Return ticks and labels at evenly spaced intervals."""
n = len(labels)
if tickevery == 0:
ticks, labels = [], []
elif tickevery == 1:
ticks, labels = np.arange(n) + 0.5, labels
else:
start, end, step = 0, n, tickevery
ticks = np.arange(start, end, step) + 0.5
labels = labels[start:end:step]
return ticks, labels
def _auto_ticks(self, ax, labels, axis):
transform = ax.figure.dpi_scale_trans.inverted()
bbox = ax.get_window_extent().transformed(transform)
size = [bbox.width, bbox.height][axis]
axis = [ax.xaxis, ax.yaxis][axis]
(tick,) = ax.xaxis.set_ticks([0])
fontsize = tick.label1.get_size()
max_ticks = int(size // (fontsize / 72))
if max_ticks < 1:
tickevery = 1
else:
tickevery = len(labels) // max_ticks + 1
return tickevery
def get_ax(self):
if hasattr(sys, "ps1") and (self.ofname is None):
fig = plt.figure(figsize=self.figsize)
else:
fig = Figure(figsize=self.figsize)
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
self.fig = fig
return ax
def draw(self):
df = self.data
ax = self.get_ax()
vmin = np.percentile(df, 2)
vmax = np.percentile(df, 98)
if self._zscore is None:
norm = Normalize(vmin=vmin, vmax=vmax)
cbar_locator = MaxNLocator(nbins=5, integer=True)
else:
norm = MidpointNormalize(vmin=vmin, vmax=vmax, vcenter=0)
cbar_locator = MaxNLocator(nbins=3, symmetric=True) # symmetric=True
matrix = ax.pcolormesh(
df.values,
cmap=self.cmap,
norm=norm,
rasterized=True,
)
xstep = self._auto_ticks(ax, df.columns.values, 0)
ystep = self._auto_ticks(ax, df.index.values, 1)
xticks, xlabels = self._skip_ticks(df.columns.values, tickevery=xstep)
yticks, ylabels = self._skip_ticks(df.index.values, tickevery=ystep)
ax.set_ylim([0, len(df)])
ax.set(xticks=xticks, yticks=yticks)
ax.set_xticklabels(
xlabels if self.xticklabels else "", fontsize=14, rotation=90
)
ax.set_yticklabels(ylabels if self.yticklabels else "", fontsize=14)
ax.set_title(self.title, fontsize=20, fontweight="bold")
ax.tick_params(
axis="both", which="both", bottom=False, top=False, right=False, left=False
)
# cax=fig.add_axes([0.93,0.25,0.05,0.20])
cbar = self.fig.colorbar(matrix, shrink=0.3, aspect=10) # ticks=[-1, 0, 1]
cbar.ax.yaxis.set_tick_params(
color="white", direction="in", left=True, right=True
)
# Add colorbar, make sure to specify tick locations to match desired ticklabels
cbar.locator = cbar_locator # LinearLocator(3)
cbar.update_ticks()
cbar.ax.set_title(self.cbar_title, loc="left", fontweight="bold")
for key, spine in cbar.ax.spines.items():
spine.set_visible(False)
# cbar = colorbar(matrix)
for side in ["top", "right", "left", "bottom"]:
ax.spines[side].set_visible(False)
# cbar.ax.spines[side].set_visible(False)
return ax
def heatmap(
df: pd.DataFrame,
z_score: Optional[int] = None,
title: str = "",
figsize: Tuple[float, float] = (5, 5),
cmap: Optional[str] = None,
xticklabels: bool = True,
yticklabels: bool = True,
ofname: Optional[str] = None,
**kwargs,
):
"""Visualize the dataframe.
:param df: DataFrame from expression table.
:param z_score: 0, 1, or None. z_score axis{0, 1}. If None, not scale.
:param title: figure title.
:param figsize: heatmap figsize.
:param cmap: matplotlib colormap. e.g. "RdBu_r".
:param xticklabels: bool, whether to show xticklabels.
:param xticklabels: bool, whether to show xticklabels.
:param ofname: output file name. If None, don't save figure
"""
ht = Heatmap(df, z_score, title, figsize, cmap, xticklabels, yticklabels, ofname)
ax = ht.draw()
if ofname is None:
return ax
# canvas.print_figure(ofname, bbox_inches='tight', dpi=300)
ht.fig.savefig(ofname, bbox_inches="tight", dpi=300)
class GSEAPlot(object):
def __init__(
self,
term: str,
tag: Sequence[int],
runes: Sequence[float],
nes: float,
pval: float,
fdr: float,
rank_metric: Optional[Sequence[float]] = None,
pheno_pos: str = "",
pheno_neg: str = "",
color: Optional[str] = None,
figsize: Tuple[float, float] = (6, 5.5),
cmap: str = "seismic",
ofname: Optional[str] = None,
ax: Optional[plt.Axes] = None,
**kwargs,
):
"""
:param term: gene_set name
:param tag: hit indices of rank_metric.index presented in gene set S.
:param runes: running enrichment scores.
:param nes: Normalized enrichment scores.
:param pval: nominal p-value.
:param fdr: false discovery rate.
:param rank_metric: pd.Series for rankings, rank_metric.values.
:param pheno_pos: phenotype label, positive correlated.
:param pheno_neg: phenotype label, negative correlated.
:param figsize: matplotlib figsize.
:param ofname: output file name. If None, don't save figure
"""
# dataFrame of ranked matrix scores
self.color = "#88C544" if color is None else color
self._x = np.arange(len(runes))
self.rankings = None
self._zero_score_ind = None
self._z_score_label = None
if rank_metric is not None:
self.rankings = np.asarray(rank_metric)
self._zero_score_ind = np.abs(self.rankings).argmin()
self._z_score_label = "Zero score at " + str(self._zero_score_ind)
self.RES = np.asarray(runes)
self.figsize = figsize
self.term = term
self.cmap = cmap
self.ofname = ofname
self._pos_label = pheno_pos
self._neg_label = pheno_neg
self._hit_indices = tag
self.module = "tmp" if ofname is None else ofname.split(".")[-2]
if self.module == "ssgsea":
self._nes_label = "ES: " + "{:.3f}".format(float(nes))
self._pval_label = "Pval: invliad for ssgsea"
self._fdr_label = "FDR: invalid for ssgsea"
else:
self._nes_label = "NES: " + "{:.3f}".format(float(nes))
self._pval_label = "Pval: " + "{:.3e}".format(float(pval))
self._fdr_label = "FDR: " + "{:.3e}".format(float(fdr))
# output truetype
plt.rcParams.update({"pdf.fonttype": 42, "ps.fonttype": 42})
# in most case, we will have many plots, so do not display plots
# It's also usefull to run this script on command line.
# GSEA Plots
if ax is None:
if hasattr(sys, "ps1") and (self.ofname is None):
# working inside python console, show figure
self.fig = plt.figure(figsize=self.figsize, facecolor="white")
else:
# If working on command line, don't show figure
self.fig = Figure(figsize=self.figsize, facecolor="white")
self._canvas = FigureCanvas(self.fig)
else:
self.fig = ax.figure
self.fig.suptitle(self.term, fontsize=16, wrap=True, fontweight="bold")
def axes_rank(self, rect):
"""
rect : sequence of float
The dimensions [left, bottom, width, height] of the new axes. All
quantities are in fractions of figure width and height.
"""
# Ranked Metric Scores Plot
ax1 = self.fig.add_axes(rect)
if self.module == "ssgsea":
ax1.fill_between(self._x, y1=np.log(self.rankings), y2=0, color="#C9D3DB")
ax1.set_ylabel("log ranked metric", fontsize=16, fontweight="bold")
else:
ax1.fill_between(self._x, y1=self.rankings, y2=0, color="#C9D3DB")
ax1.set_ylabel("Ranked metric", fontsize=16, fontweight="bold")
ax1.text(
0.05,
0.9,
self._pos_label,
color="red",
horizontalalignment="left",
verticalalignment="top",
transform=ax1.transAxes,
)
ax1.text(
0.95,
0.05,
self._neg_label,
color="Blue",
horizontalalignment="right",
verticalalignment="bottom",
transform=ax1.transAxes,
)
# the x coords of this transformation are data, and the y coord are axes
trans1 = transforms.blended_transform_factory(ax1.transData, ax1.transAxes)
ax1.vlines(
self._zero_score_ind,
0,
1,
linewidth=0.5,
transform=trans1,
linestyles="--",
color="grey",
)
hap = self._zero_score_ind / max(self._x)
if hap < 0.25:
ha = "left"
elif hap > 0.75:
ha = "right"
else:
ha = "center"
ax1.text(
hap,
0.5,
self._z_score_label,
horizontalalignment=ha,
verticalalignment="center",
transform=ax1.transAxes,
fontsize=14,
)
ax1.set_xlabel("Gene Rank", fontsize=16, fontweight="bold")
ax1.spines["top"].set_visible(False)
ax1.tick_params(
axis="both", which="both", top=False, right=False, left=False, labelsize=14
)
ax1.locator_params(axis="y", nbins=5)
ax1.yaxis.set_major_formatter(
plt.FuncFormatter(lambda tick_loc, tick_num: "{:.1f}".format(tick_loc))
)
def axes_hits(self, rect, bottom: bool = False):
"""
rect : sequence of float
The dimensions [left, bottom, width, height] of the new axes. All
quantities are in fractions of figure width and height.
"""
# gene hits
ax2 = self.fig.add_axes(rect)
# the x coords of this transformation are data, and the y coord are axes
trans2 = transforms.blended_transform_factory(ax2.transData, ax2.transAxes)
# to make axes shared with same x cooridincates, make the vlines same ranges to x
ax2.vlines(
[self._x[0], self._x[-1]],
0,
1,
linewidth=0.5,
transform=trans2,
color="white",
alpha=0,
) # alpha 0 to transparency
# add hits line
ax2.vlines(
self._hit_indices, 0, 1, linewidth=0.5, transform=trans2, color="black"
)
ax2.tick_params(
axis="both",
which="both",
bottom=bottom,
top=False,
right=False,
left=False,
labelbottom=bottom,
labelleft=False,
)
if bottom:
ax2.set_xlabel("Gene Rank", fontsize=16, fontweight="bold")
ax2.spines["bottom"].set_visible(True)
def axes_cmap(self, rect):
"""
rect : sequence of float
The dimensions [left, bottom, width, height] of the new axes. All
quantities are in fractions of figure width and height.
"""
# center color map at midpoint = 0
mat = self.rankings
if self.rankings is None:
mat = self.RES
vmin = np.percentile(mat.min(), 2)
vmax = np.percentile(mat.max(), 98)
midnorm = MidpointNormalize(vmin=vmin, vcenter=0, vmax=vmax)
# colormap
ax3 = self.fig.add_axes(rect)
ax3.pcolormesh(
mat[np.newaxis, :],
rasterized=True,
norm=midnorm,
cmap=self.cmap,
) # cm.coolwarm
ax3.spines["bottom"].set_visible(False)
ax3.tick_params(
axis="both",
which="both",
bottom=False,
top=False,
right=False,
left=False,
labelbottom=False,
labelleft=False,
)
def axes_stat(self, rect):
"""
rect : sequence of float
The dimensions [left, bottom, width, height] of the new axes. All
quantities are in fractions of figure width and height.
"""
# Enrichment score plot
ax4 = self.fig.add_axes(rect)
ax4.plot(self._x, self.RES, linewidth=4, color=self.color)
ax4.text(0.1, 0.1, self._fdr_label, transform=ax4.transAxes, fontsize=14)
ax4.text(0.1, 0.2, self._pval_label, transform=ax4.transAxes, fontsize=14)
ax4.text(0.1, 0.3, self._nes_label, transform=ax4.transAxes, fontsize=14)
# the y coords of this transformation are data, and the x coord are axes
trans4 = transforms.blended_transform_factory(ax4.transAxes, ax4.transData)
ax4.hlines(0, 0, 1, linewidth=1, transform=trans4, color="grey")
ax4.set_ylabel("Enrichment Score", fontsize=16, fontweight="bold")
# ax4.set_xlim(min(self._x), max(self._x))
ax4.tick_params(
axis="both",
which="both",
bottom=False,
top=False,
right=False,
labelbottom=False,
labelsize=14,
)
ax4.locator_params(axis="y", nbins=5)
# FuncFormatter need two argument, I don't know why. this lambda function used to format yaxis tick labels.
ax4.yaxis.set_major_formatter(
plt.FuncFormatter(lambda tick_loc, tick_num: "{:.1f}".format(tick_loc))
)
self.ax = ax4
def add_axes(self):
"""
Please check matplotlib docs about how to `add_axes` to figure.
Here is a more flexible way to create a new gseaplot.
For example, don't show ranking and merge hits and colormap together
just used:
self.axes_stat([0.1,0.2,0.8,0.8]) # axes_stat should be called first
self.axes_cmap([0.1,0.1,0.8,0.1])
self.axes_hits([0.1,0.1,0.8,0.1])
"""
left = 0.1
width = 0.8
bottom = 0.1
height = 0
stat_height_ratio = 0.4
hits_height_ratio = 0.05
cmap_height_ratio = 0.05
rank_height_ratio = 0.3
## make stat /hits height ratio const
if self.rankings is None:
rank_height_ratio = 0
cmap_height_ratio = 0
base = 0.8 / (
stat_height_ratio
+ hits_height_ratio
+ cmap_height_ratio
+ rank_height_ratio
)
# for i, hit in enumerate(self.hits):
# height = hits_height_ratio * base
if self.rankings is not None:
height = rank_height_ratio * base
self.axes_rank([left, bottom, width, height])
bottom += height
height = cmap_height_ratio * base
self.axes_cmap([left, bottom, width, height])
bottom += height
height = hits_height_ratio * base
self.axes_hits(
[left, bottom, width, height], bottom=False if bottom > 0.1 else True
)
bottom += height
height = stat_height_ratio * base
self.axes_stat([left, bottom, width, height])
# self.fig.subplots_adjust(hspace=0)
# self.fig.tight_layout()
def savefig(self, bbox_inches="tight", dpi=300):
# if self.ofname is not None:
if hasattr(sys, "ps1") and (self.ofname is not None):
self.fig.savefig(self.ofname, bbox_inches=bbox_inches, dpi=dpi)
elif self.ofname is None:
return
else:
self._canvas.print_figure(self.ofname, bbox_inches=bbox_inches, dpi=300)
return
def gseaplot(
term: str,
hits: Sequence[int],
nes: float,
pval: float,
fdr: float,
RES: Sequence[float],
rank_metric: Optional[Sequence[float]] = None,
pheno_pos: str = "",
pheno_neg: str = "",
color: str = "#88C544",
figsize: Tuple[float, float] = (6, 5.5),
cmap: str = "seismic",
ofname: Optional[str] = None,
**kwargs,
) -> Optional[List[plt.Axes]]:
"""This is the main function for generating the gsea plot.
:param term: gene_set name
:param hits: hits indices of rank_metric.index presented in gene set S.
:param nes: Normalized enrichment scores.
:param pval: nominal p-value.
:param fdr: false discovery rate.
:param RES: running enrichment scores.
:param rank_metric: pd.Series for rankings, rank_metric.values.
:param pheno_pos: phenotype label, positive correlated.
:param pheno_neg: phenotype label, negative correlated.
:param color: color for RES and hits.
:param figsize: matplotlib figsize.
:param ofname: output file name. If None, don't save figure
return matplotlib.Figure.
"""
g = GSEAPlot(
term,
hits,
RES,
nes,
pval,
fdr,
rank_metric,
pheno_pos,
pheno_neg,
color,
figsize,
cmap,
ofname,
)
g.add_axes()
if ofname is None:
return g.fig.axes
g.savefig()
class DotPlot(object):
def __init__(
self,
df: pd.DataFrame,
x: Optional[str] = None,
y: str = "Term",
hue: str = "Adjusted P-value",
dot_scale: float = 5.0,
x_order: Optional[List[str]] = None,
y_order: Optional[List[str]] = None,
thresh: float = 0.05,
n_terms: int = 10,
title: str = "",
figsize: Tuple[float, float] = (6, 5.5),
cmap: str = "viridis_r",
ofname: Optional[str] = None,
**kwargs,
):
"""Visualize GSEApy Results with categorical scatterplot
When multiple datasets exist in the input dataframe, the `x` argument is your friend.
:param df: GSEApy DataFrame results.
:param x: Categorical variable in `df` that map the x-axis data. Default: None.
:param y: Categorical variable in `df` that map the y-axis data. Default: Term.
:param hue: Grouping variable that will produce points with different colors.
Can be either categorical or numeric
:param x_order: bool, array-like list. Default: False.
If True, peformed hierarchical_clustering on X-axis.
or input a array-like list of `x` categorical levels.
:param x_order: bool, array-like list. Default: False.
If True, peformed hierarchical_clustering on Y-axis.
or input a array-like list of `y` categorical levels.
:param title: Figure title.
:param thresh: Terms with `column` value < cut-off are shown. Work only for
("Adjusted P-value", "P-value", "NOM p-val", "FDR q-val")
:param n_terms: Number of enriched terms to show.
:param dot_scale: float, scale the dot size to get proper visualization.
:param figsize: tuple, matplotlib figure size.
:param cmap: Matplotlib colormap for mapping the `column` semantic.
:param ofname: Output file name. If None, don't save figure
:param marker: The matplotlib.markers. See https://matplotlib.org/stable/api/markers_api.html
"""
self.marker = "o"
if "marker" in kwargs:
self.marker = kwargs["marker"]
self.y = y
self.x = x
self.x_order = x_order
self.y_order = y_order
self.hue = str(hue)
self.colname = str(hue)
self.figsize = figsize
self.cmap = cmap
self.ofname = ofname
self.scale = dot_scale
self.title = title
self.n_terms = n_terms
self.thresh = thresh
self.data = self.process(df)
plt.rcParams.update({"pdf.fonttype": 42, "ps.fonttype": 42})
def isfloat(self, x):
try:
float(x)
except:
return False
else:
return True
def process(self, df: pd.DataFrame):
# check if any values in `df[colname]` can't be coerced to floats
can_be_coerced = df[self.colname].map(self.isfloat).sum()
if can_be_coerced < df.shape[0]:
msg = "some value in %s could not be typecast to `float`" % self.colname
raise ValueError(msg)
# subset
mask = df[self.colname] <= self.thresh
if self.colname in ["Combined Score", "NES", "ES", "Odds Ratio"]:
mask.loc[:] = True
df = df.loc[mask]
if df.shape[0] < 1:
msg = "Warning: No enrich terms when cutoff = %s" % self.thresh
raise ValueError(msg)
self.cbar_title = self.colname
# clip GSEA lower bounds
# if self.colname in ["NOM p-val", "FDR q-val"]:
# df[self.colname].clip(1e-5, 1.0, inplace=True)
# sorting the dataframe for better visualization
colnd = {
"Adjusted P-value": "FDR",
"P-value": "Pval",
"NOM p-val": "Pval",
"FDR q-val": "FDR",
}
## impute the 0s in pval, fdr for visualization purpose
if self.colname in ["Adjusted P-value", "P-value", "NOM p-val", "FDR q-val"]:
# if all values are zeros, raise error
if not any(df[self.colname].abs() > 0):
raise ValueError(
f"Can not detetermine colormap. All values in {self.colname} are 0s"
)
df = df.sort_values(by=self.colname)
df[self.colname].replace(
0, method="bfill", inplace=True
) ## asending order, use bfill
df = df.assign(p_inv=np.log10(1 / df[self.colname].astype(float)))
_t = colnd[self.colname]
self.colname = "p_inv"
self.cbar_title = r"$\log_{10} \frac{1}{ " + _t + " }$"
# get top terms; sort ascending
if (
(self.x is not None)
and (self.x in df.columns)
and (not all(df[self.x].map(self.isfloat)))
):
# if x is numeric column
# get top term of each group
df = (
df.groupby(self.x)
.apply(lambda _x: _x.sort_values(by=self.colname).tail(self.n_terms))
.reset_index(drop=True)
)
else:
df = df.sort_values(by=self.colname).tail(self.n_terms) # acending
# get scatter area
if df.columns.isin(["Overlap", "Tag %"]).any():
ol = df.columns[df.columns.isin(["Overlap", "Tag %"])]
temp = (
df[ol].squeeze(axis=1).str.split("/", expand=True).astype(int)
) # axis=1, in case you have only 1 row
df = df.assign(Hits_ratio=temp.iloc[:, 0] / temp.iloc[:, 1])
else:
df = df.assign(Hits_ratio=1.0) # if Overlap column missing
return df
def _hierarchical_clustering(self, mat, method, metric) -> List[int]:
# mat.shape -> [n_sample, m_features]
Y0 = sch.linkage(mat, method=method, metric=metric)
Z0 = sch.dendrogram(
Y0,
orientation="left",
# labels=mat.index,
no_plot=True,
distance_sort="descending",
)
idx = Z0["leaves"][::-1] # reverse the order to make the view better
return idx
def get_x_order(
self, method: str = "single", metric: str = "euclidean"
) -> List[str]:
"""See scipy.cluster.hierarchy.linkage()
Perform hierarchical/agglomerative clustering.
Return categorical order.
"""
if hasattr(self.x_order, "__len__"):
return self.x_order
mat = self.data.pivot(
index=self.y,
columns=self.x,
values=self.colname, # [self.colname, "Hits_ratio"],
).fillna(0)
idx = self._hierarchical_clustering(mat.T, method, metric)
return list(mat.columns[idx])
def get_y_order(
self, method: str = "single", metric: str = "euclidean"
) -> List[str]:
"""See scipy.cluster.hierarchy.linkage()
Perform hierarchical/agglomerative clustering.
Return categorical order.
"""
if hasattr(self.y_order, "__len__"):
return self.y_order
mat = self.data.pivot(
index=self.y,
columns=self.x,
values=self.colname, # [self.colname, "Hits_ratio"],
).fillna(0)
idx = self._hierarchical_clustering(mat, method, metric)
return list(mat.index[idx])
def get_ax(self):
"""
setup figure axes
"""
# create fig
if hasattr(sys, "ps1") and (self.ofname is None):
# working inside python console, show figure
fig = plt.figure(figsize=self.figsize)
else:
# If working on commandline, don't show figure
fig = Figure(figsize=self.figsize)
_canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
self.fig = fig
return ax
def set_x(self):
"""
set x-axis's value
"""
x = self.x
xlabel = ""
# set xaxis values, so you could get dotplot
if (x is not None) and (x in self.data.columns):
xlabel = x
elif "Combined Score" in self.data.columns:
xlabel = "Combined Score"
x = xlabel
elif "Odds Ratio" in self.data.columns:
xlabel = "Odds Ratio"
x = xlabel
elif "NES" in self.data.columns:
xlabel = "NES"
x = xlabel
else:
# revert back to p_inv
x = self.colname
xlabel = self.cbar_title
return x, xlabel
def scatter(
self,
outer_ring: bool = False,
):
"""
build scatter
"""
# scatter colormap range
# df = df.assign(colmap=self.data[self.colname].round().astype("int"))
# make area bigger to better visualization
# area = df["Hits_ratio"] * plt.rcParams["lines.linewidth"] * 100
df = self.data.assign(
area=(
self.data["Hits_ratio"] * self.scale * plt.rcParams["lines.markersize"]
).pow(2)
)
colmap = df[self.colname].astype(int)
vmin = np.percentile(colmap.min(), 2)
vmax = np.percentile(colmap.max(), 98)
# vmin = np.percentile(df.colmap.min(), 2)
# vmax = np.percentile(df.colmap.max(), 98)
ax = self.get_ax()
# if self.x is None:
x, xlabel = self.set_x()
y = self.y
# if x axis is numberic, prettifiy the plot with the numberic order
if all(df[x].map(self.isfloat)):
df = df.sort_values(by=x)
# set x, y order if set
xunits = UnitData(self.get_x_order()) if self.x_order else None
yunits = UnitData(self.get_y_order()) if self.y_order else None
# outer ring
if outer_ring:
smax = df["area"].max()
# TODO:
# Matplotlib BUG: when setting edge colors,
# there's the center of scatter could not aligned.
# Must set backend to TKcario... to fix it
# Instead, I just add more dots in the plot to get the ring
blk_sc = ax.scatter(
x=x,
y=y,
s=smax * 1.6,
edgecolors="none",
c="black",
data=df,
marker=self.marker,
xunits=xunits, # set x categorical order
yunits=yunits, # set y categorical order
zorder=0,
)
wht_sc = ax.scatter(
x=x,
y=y,
s=smax * 1.3,
edgecolors="none",
c="white",
data=df,
marker=self.marker,
xunits=xunits, # set x categorical order
yunits=yunits, # set y categorical order
zorder=1,
)
# data = np.array(rg.get_offsets()) # get data coordinates
# inner circle
sc = ax.scatter(
x=x,
y=y,
data=df,
s="area",
edgecolors="none",
c=self.colname,
cmap=self.cmap,
vmin=vmin,
vmax=vmax,
marker=self.marker,
xunits=xunits, # set x categorical order
yunits=yunits, # set y categorical order
zorder=2,
)
ax.set_xlabel(xlabel, fontsize=14, fontweight="bold")
ax.xaxis.set_tick_params(labelsize=14)
ax.yaxis.set_tick_params(labelsize=16)
ax.set_axisbelow(True) # set grid blew other element
ax.grid(axis="y", zorder=-1) # zorder=-1.0
ax.margins(x=0.25)
# We change the fontsize of minor ticks label
# ax.tick_params(axis='y', which='major', labelsize=16)
# ax.tick_params(axis='both', which='minor', labelsize=14)
# scatter size legend
# we use the *func* argument to supply the inverse of the function
# used to calculate the sizes from above. The *fmt* ensures to string you want
handles, labels = sc.legend_elements(
prop="sizes",
num=3, #
fmt="{x:.2f}",
color="gray",
func=lambda s: np.sqrt(s) / plt.rcParams["lines.markersize"] / self.scale,
)
ax.legend(
handles,
labels,
title="% Genes\nin set",
bbox_to_anchor=(1.02, 0.9),
loc="upper left",
frameon=False,
labelspacing=2,
)
ax.set_title(self.title, fontsize=20, fontweight="bold")
self.add_colorbar(sc)
return ax
def add_colorbar(self, sc):
"""
:param sc: matplotlib.Scatter
"""
# colorbar
# cax = fig.add_axes([1.0, 0.20, 0.03, 0.22])
cbar = self.fig.colorbar(
sc,
shrink=0.25,
aspect=10,
anchor=(0.0, 0.2), # (0.0, 0.2),
location="right",
# cax=cax,
)
# cbar.ax.tick_params(direction='in')
cbar.ax.yaxis.set_tick_params(
color="white", direction="in", left=True, right=True
)
cbar.ax.set_title(self.cbar_title, loc="left", fontweight="bold")
for key, spine in cbar.ax.spines.items():
spine.set_visible(False)
def _parse_colors(self, color=None):
"""
parse colors for groups
"""
# map color to group
if isinstance(color, dict):
return list(color.values())
# get default color cycle
if (not isinstance(color, str)) and hasattr(color, "__len__"):
_colors = list(color)
else:
# get current matplotlib color cycle
prop_cycle = plt.rcParams["axes.prop_cycle"]
_colors = prop_cycle.by_key()["color"]
return _colors
def barh(self, color=None, group=None, ax=None):
"""
Barplot
"""
if ax is None:
ax = self.get_ax()
x, xlabel = self.set_x()
bar = self.data.plot.barh(
x=self.y, y=self.colname, alpha=0.75, fontsize=16, ax=ax
)
if self.hue in ["Adjusted P-value", "P-value", "FDR q-val", "NOM p-val"]:
xlabel = r"$- \log_{10}$ (%s)" % self.hue
else:
xlabel = self.hue
bar.set_xlabel(xlabel, fontsize=16, fontweight="bold")
bar.set_ylabel("")
bar.set_title(self.title, fontsize=24, fontweight="bold")
bar.xaxis.set_major_locator(MaxNLocator(nbins=5, integer=True))
#
_colors = self._parse_colors(color=color)
colors = _colors
# remove old legend first
bar.legend_.remove()
if (group is not None) and (group in self.data.columns):
num_grp = self.data[group].value_counts(sort=False)
# set colors for each bar (groupby hue) using full length
colors = []
legend_elements = []
for i, n in enumerate(num_grp):
# cycle _colors if num_grp > len(_colors)
c = _colors[i % len(_colors)]