Repository navigation
Expand file tree
/
Copy pathplot.py
More file actions
1562 lines (1355 loc) · 45.7 KB
/
Copy pathplot.py
File metadata and controls
1562 lines (1355 loc) · 45.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
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 -*-
"""
Created on Fri Oct 23 12:31:28 2020
@author: Xingyan Liu
"""
import logging
from typing import Union, Mapping, Sequence, Optional, Callable
from pathlib import Path
import networkx as nx
import numpy as np
import pandas as pd
from scipy import sparse
from sklearn import metrics
import scanpy as sc
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.colors as mcolors
import seaborn as sns
from . import _alluvial
"""
Example:
import utils_plot as uplt
uplt.heatmap(df)
"""
# In[]
def _save_with_adjust(fig, fpath=None, figsize=None, **kwds):
if figsize is not None:
fig.set_size_inches(*figsize)
if fpath is not None:
fig.savefig(fpath, bbox_inches='tight', **kwds)
print(f'figure has been saved into:\n\t{fpath}')
else:
fig.show()
plt.close()
def rotate_xticklabels(ax, angle=45, **kwargs):
ax.set_xticklabels(ax.get_xticklabels(), rotation=angle,
**kwargs)
def rotate_yticklabels(ax, angle=45, **kwargs):
ax.set_yticklabels(ax.get_yticklabels(), rotation=angle,
**kwargs)
# In[]
# colors
def view_color_map(cmap='viridis', n=None, figsize=(6, 2), s=150, k=20,
ax=None,
grid=False, **kwds):
"""
n: total number of colors
k: number of colors to be plotted on each line.
Examples
--------
>>> colors = ['Set1', 'viridis', 'Spectral']
>>> view_color_map(colors[-1], n=20)
>>> import scanpy as sc
>>> cmap = sc.pl.palettes.zeileis_26
>>> cmap = sc.pl.palettes.default_64
>>> view_color_map(cmap, k=16)
"""
if not isinstance(cmap, (np.ndarray, list)):
# from matplotlib import cm
cmp = mpl.cm.get_cmap(cmap, n)
n = 20 if n is None else n
cmp = [cmp(i) for i in range(n)]
else:
n = len(cmap) if n is None else n
cmp = cmap
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
for i in range(n):
ax.scatter(i % k, i // k, color=cmp[i], s=s)
plt.grid(b=grid, ) # axis='y')
plt.show()
return ax
def get_colors(cmap='Spectral', n=5, to_hex=True):
"""
fx.get_colors('Reds', 4)
fx.view_color_map('Reds', 4)
"""
# import matplotlib.colors as mcolors
cmp = plt.cm.get_cmap(cmap, n)
colors = [cmp(i) for i in range(n)]
if to_hex:
return [mcolors.to_hex(c) for c in colors]
else:
return colors
def diy_cmap_grey_bg(name_fg='RdPu', low=0.15, rm_high=0.01, n=100, bg='#d9d9d9'):
s = int(n * low)
t = max((1, int(n * rm_high)))
print((s, t))
candi_colors = [bg] * s + get_colors(name_fg, n)[s: -t]
cmap = mcolors.ListedColormap(candi_colors)
return cmap
# In[]
# Visualization of group correspondences on an alluvial plot
def _alluvial_dict_from_confusdf(
df: pd.DataFrame, vals_ignore=(0, np.nan), tag=''):
"""
Parameters
----------
df:
might be the confusion matrix
vals_ignore
tag: str
used to make avoid name collisions in each side
Returns
-------
"""
dct = {}
rowsum = df.sum(1)
for i, idx in enumerate(df.index):
# print(i, idx, type(rowsum[idx]), rowsum[idx])
if rowsum[idx] in vals_ignore:
continue
dct[idx] = {}
for col in df.columns:
val = df.loc[idx, col]
if val > 0:
# avoid name collisions in each side
dct[idx][col + tag] = val
return dct
def alluvial_plot(
confsdf: pd.DataFrame,
labels=['', ''], # ['true', 'predicted'],
label_shift=0, # -18
title='alluvial plot',
alpha=0.75,
cmap_name='tab20_r',
shuffle_colors=True,
fonsize_title=11,
figsize=(5, 5),
fname=None,
a_sort=None, b_sort=None,
**kwds):
""" visualizing confusion matrix using alluvial plot
a_sort, b_sort: sorted group names on the left and the right side
"""
input_dct = _alluvial_dict_from_confusdf(confsdf, tag=' ')
if b_sort is not None:
b_sort = [s + ' ' for s in b_sort]
cmap = mpl.cm.get_cmap(cmap_name)
ax = _alluvial.plot(input_dct, labels=labels,
label_shift=label_shift,
cmap=cmap, alpha=alpha,
shuffle_colors=shuffle_colors,
figsize=figsize,
a_sort=a_sort, b_sort=b_sort,
**kwds)
ax.set_title(title, fontsize=fonsize_title)
fig = ax.get_figure()
# fig.set_size_inches(*figsize)
plt.show()
_save_with_adjust(fig, fname, )
return ax
def plot_stacked_bar(
df, norm=True, figsize=(6, 4),
colors=None,
cmap: Union[str, Callable] = 'tab20b',
legend_loc=(1.02, 0.01),
):
""" helper function for visualizing the group compositions (e.g., in
each stage or condition).
Parameters
----------
df: pd.DataFrame
the values in each row will be display as one stacked bar.
norm: bool
whether to normalize each row to unit-sum.
figsize: tuple
colors: Sequence
cmap: Union[str, Callable]
color-map function or color-map name
legend_loc: tuple
the legend location
Returns
-------
ax
"""
if norm:
df = df.apply(lambda x: x / x.sum(), axis=1)
groups = list(df.columns)
x = list(df.index)
if colors is None:
if cmap is None:
cmap_func = plt.cm.get_cmap(cmap, len(groups))
elif hasattr(cmap, '__call__'):
cmap_func = cmap
else:
raise ValueError('cmap should be either Callable or str')
colors = [cmap_func(i) for i, _ in enumerate(groups)]
fig, ax = plt.subplots(figsize=figsize)
bott = df[groups[0]]
ax.bar(x, bott, label=groups[0], color=colors[0])
for i, c in enumerate(groups[1:]):
height = df[c].fillna(0.)
ax.bar(x, height, bottom=bott, label=c, color=colors[i + 1])
bott += height
ax.legend(loc=legend_loc)
return ax
# functions for plotting confusion or contingency matrix
def plot_contingency_mat(
y_true, y_pred,
norm_axis=1,
arrange: bool = True,
order_rows: bool = True,
order_cols: bool = False,
ax=None,
cmap='magma_r',
figsize: tuple = (4, 3),
fp: Union[Path, str, None] = None,
**kwds
):
"""function for plotting the contingency matrix"""
from .analyze import wrapper_contingency_mat
contmat = wrapper_contingency_mat(
y_true, y_pred, normalize_axis=norm_axis,
order_rows=order_rows, order_cols=order_cols, )
if arrange:
# align column- and row- names as possible
from .analyze import arrange_contingency_mat
contmat = arrange_contingency_mat(contmat)
ax = heatmap(contmat, figsize=figsize, ax=ax, fp=fp, cmap=cmap, **kwds)
return ax, contmat
def plot_confus_mat(y_true, y_pred, classes_on=None,
normalize='true',
linewidths=0.02, linecolor='grey',
figsize: tuple = (4, 3),
ax=None, fp=None,
**kwargs):
"""function for plotting the contingency matrix
by default, the values will be normalized by row (true classes)
"""
y_true = list(map(str, y_true))
y_pred = list(map(str, y_pred))
if classes_on is None:
classes_on = list(set(y_true).union(y_pred))
mat = metrics.confusion_matrix(y_true, y_pred, labels=classes_on,
normalize=normalize)
# return sns.heatmap(mat, linewidths=linewidths, linecolor=linecolor,
# xticklabels=classes_on, yticklabels=classes_on,
# **kwargs)
mat = pd.DataFrame(data=mat, index=classes_on, columns=classes_on)
ax = heatmap(mat, figsize=figsize, ax=ax, fp=fp,
linewidths=linewidths, linecolor=linecolor,
**kwargs)
return ax, mat
def plot_confus_multi_mats(ytrue_lists, ypred_lists, classes_on=None,
nrows=1, ncols=2, figsize=(8, 3),
vmax=1,
fname=None):
"""
combime multiple confusion matrix-plots into a single plot
"""
fig, axs = plt.subplots(nrows, ncols, sharey=True, figsize=figsize)
for k in range(len(ytrue_lists)):
if nrows == 1 or ncols == 1:
ax = axs[k]
else:
irow = k // ncols
icol = k % nrows
ax = axs[irow, icol]
plot_confus_mat(ytrue_lists[k], ypred_lists[k],
classes_on=classes_on,
square=True, # cbar=False,
vmax=vmax,
ax=ax,
)
_save_with_adjust(fig, fname)
return axs
# In[]
# plot functions (for inspecting training process)
def plot_line_list(ys, lbs=None,
ax=None, figsize=(4.5, 3.5),
tt=None, fp=None,
legend_loc=(1.05, 0),
**kwds):
"""
ys: a list of lists, each sub-list is a set of curve-points to be plotted.
"""
if lbs is None:
lbs = list(map(str, range(len(ys))))
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
for i, y in enumerate(ys):
ax.plot(y, label=lbs[i], **kwds)
ax.legend(loc=legend_loc)
if tt is not None:
ax.set_title(tt)
_save_with_adjust(ax.figure, fp, )
return ax
def plot_records_for_trainer(
trainer, record_names, start=0, end=None,
lbs=None, tt='training logs', fp=None,
**kwds):
if lbs is None:
lbs = record_names
if end is not None:
end = int(min([trainer._cur_epoch + 1, end]))
line_list = [getattr(trainer, nm)[start: end] for nm in record_names]
return plot_line_list(line_list, lbs=lbs, tt=tt, fp=fp, **kwds)
def venn_plot(sets, set_labels=None, regular=False,
tt='Venn plot', ax=None, fp=None, **kwds):
"""
sets: iterable
set_labels: list[str]
regular: bool, only for sets of strings!
whether to regularize the strings in sets
"""
from matplotlib_venn import venn2, venn3
if regular:
print('Regularizing strings in sets (UPPER case ignored)')
lowerStr = lambda x: [str(c).lower() for c in list(x)]
sets = list(map(set, map(lowerStr, sets)))
if not isinstance(sets[0], set):
# assure that each item in `sets` is a set object
sets = list(map(set, sets))
n = len(sets)
if set_labels is None:
set_labels = np.arange(n)
venn = {2: venn2, 3: venn3}[n]
if ax is None:
fig, ax = plt.subplots()
venn(sets, set_labels=set_labels, ax=ax, **kwds)
ax.set_title(tt)
_save_with_adjust(ax.figure, fp, )
# plt.show()
return ax
def heatmap(df_hmap: pd.DataFrame,
norm_method: Union[None, str] = None,
norm_axis=1,
order_row=False,
order_col=False,
figsize=(6, 6), # ignored if ax is not None
ax=None,
xlabel=None,
ylabel=None,
cmap='magma_r', # 'RdBu_r'
cbar=True,
cbar_kws={'shrink': 0.5},
fp=None,
xrotation=45,
yrotation=None,
**kwds):
""" wrapper of sns.heatmap()
Parameters
----------
norm_method: {None, 'zs', 'max', 'maxmin'}
normalization method
norm_axis: 0 or 1
0 for column-normalization and 1 for rows.
figsize: tuple
(6, 6) by default, ignored if ax is not None.
"""
# normalize values
if norm_method == 'max': # ALL non-negative values are required!
if (df_hmap < 0).any():
raise ValueError('Data with ALL non-negative values are required '
'for "max-normalization"')
df_hmap = df_hmap.apply(lambda x: x / x.max() if x.max() > 0 else x,
axis=norm_axis)
elif norm_method == 'maxmin':
eps = 1e-8
df_hmap = df_hmap.apply(
lambda x: (x - x.min()) / (x.max() - x.min() + eps),
axis=norm_axis)
elif norm_method == 'zs':
from .preprocess import zscore
if norm_axis == 0:
df_hmap = zscore(df_hmap) # column normalization
elif norm_axis == 1:
df_hmap = zscore(df_hmap.T).T
# re-order rows or columns
from .preprocess import order_contingency_mat
if order_col:
df_hmap = order_contingency_mat(df_hmap, axis=0)
if order_row:
df_hmap = order_contingency_mat(df_hmap, axis=1)
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
sns.heatmap(df_hmap,
# yticklabels=False,
cbar=cbar,
cbar_kws=cbar_kws,
ax=ax,
cmap=cmap,
# col_colors = cl_color_match,
**kwds)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if xrotation is not None:
ax.set_xticklabels(ax.get_xticklabels(), rotation=xrotation,
ha='right' if xrotation < 90 else 'center'
)
if yrotation is not None:
ax.set_yticklabels(ax.get_yticklabels(), rotation=yrotation)
if fp is not None:
_save_with_adjust(ax.figure, fp)
return ax
def heatmap_probas(
df_data, lbs, # sort_lbs=False,
name_label='Group',
cmap_heat='magma_r', cmap_lb='tab20',
figsize=(8, 4),
vmax=1, vmin=0,
xrotation=30,
fp=None):
""" Heatmap of the prediction probabilities
Parameters
----------
df_data
A DataFrame of shape ``(n_samples, n_ref_classes)``.
Note that the samples should be sorted by the (query) group labels,
i.e., ``lbs``.
lbs
the (query) group labels
name_label
the name of the group labels
cmap_heat
the color-map of the heatmap
cmap_lb
the color-map of the group labels (``lbs``).
figsize
the figure size
vmax, vmin
the maximum and the minimum of the heatmap
xrotation
rotation of the x-tick-labels
fp
file-path for saving the plot
Returns
-------
gs (gridspec)
"""
lbs = pd.Categorical(lbs, )
pix_lbs = np.vstack([lbs.codes] * 2)
fig = plt.figure(constrained_layout=False, figsize=figsize)
gs = fig.add_gridspec(
nrows=12, ncols=80, left=0.05, right=0.98,
hspace=0.25, wspace=2)
w_cbar = 2
ax1 = fig.add_subplot(gs[:-1, : -w_cbar])
ax11 = fig.add_subplot(gs[:-1, -w_cbar:])
ax2 = fig.add_subplot(gs[-1:, : -w_cbar])
im = ax1.imshow(df_data,
interpolation='nearest',
cmap=cmap_heat,
# origin='lower', #extent=[-3, 3, -3, 3],
aspect='auto',
vmax=1, vmin=0)
fig.colorbar(mpl.cm.ScalarMappable(
norm=mpl.colors.Normalize(vmin=vmin, vmax=vmax),
cmap=cmap_heat,
),
cax=ax11, )
# im = ax1.pcolor(df_data, cmap='magma_r', vmax=1, vmin=0)
colors = ['#1f77b4','#ff7f0e','#279e68','#d62728','#aa40fc','#8c564b','#e377c2']
custom_cmap = mcolors.LinearSegmentedColormap.from_list("custom_cmap", colors)
ax2.pcolor(pix_lbs, cmap=custom_cmap)
for _ax in [ax1, ax2, ]:
_ax.grid(False)
ax1.set_yticks(np.arange(df_data.shape[0]))
ax1.set_yticklabels(df_data.index)
ax1.set_xticks([])
ax2.set_yticks([1])
ax2.set_yticklabels([name_label])
# setting class-labels (x-ticks)
classes = pd.unique(lbs)
cut_loc = np.hstack(
[[0], np.flatnonzero(np.diff(lbs.codes)), [len(lbs)]])
x_loc = cut_loc[:-1] + np.diff(cut_loc) // 2
ax2.set_xticks(x_loc)
if xrotation:
ax2.set_xticklabels(classes, rotation=xrotation, ha='right')
else:
ax2.set_xticklabels(classes, )
for loc in ['right', 'top', 'bottom', 'left'][:-1]:
ax1.spines[loc].set_visible(False)
ax11.spines[loc].set_visible(False)
ax2.spines[loc].set_visible(False)
# _ax.set_axis_off()
if fp:
_save_with_adjust(fig, fp)
return gs
def grid_display_probas(
df,
labels,
classes=None,
figsize=(6, 5),
sharey=True,
ylim=(-0.1, 1.1),
):
""" violin plots of the distributions """
if classes is None:
classes = sorted(set(labels))
classes = [c for c in df.columns if c in classes] + [
c for c in classes if c not in df.columns]
labels = np.asarray(labels)
fig, axs = plt.subplots(
len(classes), 2, figsize=figsize,
sharex=True, sharey=sharey,
gridspec_kw={'hspace': 0.0, 'wspace': 0.}
)
for i, cl in enumerate(classes):
df_sub = df[labels == cl]
sns.violinplot(data=df_sub, ax=axs[i, 1], linewidth=.01, vmin=0)
y_mid = (ylim[0] + ylim[1]) / 2 - 0.2
axs[i, 1].set_ylim(*ylim)
axs[i, 0].text(df.shape[1] - 1, y_mid, cl, ha='right')
axs[i, 0].set_axis_off()
rotate_xticklabels(axs[-1, 1], ha='right')
return fig
def grid_bars_display_probas(
df,
labels,
classes=None,
figsize=(6, 5),
sharey=True,
ylim=(0.25, 1.05),
):
""" bar plots of the distributions """
if classes is None:
classes = sorted(set(labels))
classes = [c for c in df.columns if c in classes] + [
c for c in classes if c not in df.columns]
labels = np.asarray(labels)
fig, axs = plt.subplots(
len(classes), 2, figsize=figsize,
sharex=True, sharey=sharey,
gridspec_kw={'hspace': 0.0, 'wspace': 0.}
)
for i, cl in enumerate(classes):
df_sub = df[labels == cl]
sns.barplot(data=df_sub, ax=axs[i, 1])
ymin, ymax = ylim
axs[i, 1].set_ylim(*ylim)
axs[i, 1].set_yticks([])
y_mid = (ymax + ymin) / 2 - 0.2
axs[i, 0].text(df.shape[1] - 1, y_mid, cl, ha='right')
axs[i, 0].set_axis_off()
rotate_xticklabels(axs[-1, 1], ha='right')
return fig
def grid_bars_display_probas_transposed(
df,
labels,
classes=None,
figsize=(5, 6),
sharey=True,
xlim=(0.25, 1.05),
**kwargs
):
""" bar plots of the distributions (transposed) """
if classes is None:
classes = sorted(set(labels))
classes = [c for c in df.columns if c in classes] + [
c for c in classes if c not in df.columns]
labels = np.asarray(labels)
n_cl = len(classes)
fig, axs = plt.subplots(
2, len(classes), figsize=figsize,
sharex=True, sharey=sharey,
gridspec_kw={'hspace': 0.0, 'wspace': 0.}
)
for i, cl in enumerate(classes):
df_sub = df[labels == cl]
sns.barplot(data=df_sub, ax=axs[0, i], orient='h', **kwargs)
xmin, xmax = xlim
axs[0, i].set_xlim(xmin, xmax)
axs[0, i].set_xticks([])
x_mid = (xmax + xmin) / 2 - 0.2
axs[1, i].text(x_mid, -0.25, cl,
ha='right', va='top', rotation=30)
axs[1, i].set_axis_off()
return fig
def wrapper_heatmap_scores(
df_score: pd.DataFrame,
obs: pd.DataFrame,
col_label: str = 'celltype',
col_pred: str = 'predicted', # TODO: unnecessary, use argmax on scores
figsize: tuple = (5, 3),
n_subsample: Optional[int] = 50,
ignore_index: bool = False,
name_label='Cell type', # 'true label',
filter_null=True,
type_order_true: Sequence = None,
type_order_pred: Sequence = None,
fp=None,
**kwds
):
""" sort columns and rows, plot heatmap of cell-type scores
"""
cols_anno = [col_label, col_pred]
df_lbs = obs[cols_anno].copy()
if type_order_true is None:
type_order_true = sorted(set(df_lbs[col_label]))
type_order_true = dict(zip(type_order_true, range(len(type_order_true))))
if type_order_pred is None:
type_order_pred = sorted(set(df_lbs[col_pred]))
type_order_pred = dict(zip(type_order_pred, range(len(type_order_pred))))
if ignore_index:
df_lbs.index = df_score.index
df_lbs['lb_codes'] = df_lbs[col_label].map(type_order_true)
df_lbs['pred_codes'] = df_lbs[col_pred].map(type_order_pred)
# sort samples by labels
# df_lbs = df_lbs.sort_values(cols_anno)
df_lbs = df_lbs.sort_values(['lb_codes', 'pred_codes'])
if n_subsample:
from .base import subsample_each_group
indices = subsample_each_group(df_lbs[col_label], n_out=n_subsample)
else:
indices = df_lbs.index
if filter_null: # un-predicted types will not be displayed
cols_ordered = [c for c in type_order_pred.keys()
if c in df_score.columns]
else:
cols_ordered = list(type_order_pred.keys())
df_data = df_score.loc[indices, cols_ordered].copy()
lbs = df_lbs.loc[indices, col_label]
gs = heatmap_probas(
df_data.T, lbs, name_label=name_label,
figsize=figsize, fp=fp, **kwds
)
return gs
# scatter plots
def sorted_scatter(
x, y, v=None, s=1.5,
title=None,
ax=None, cmap='RdYlBu_r',
marker='.',
vmin=None, vmax=None,
xlabel=None, ylabel=None,
with_cbar=True,
fontsize_cbar=9,
fontsize_axlabels=9,
fontsize_title=9,
lim_margin=0.1,
**kwargs
):
""" scatter plot colored with continuous values, with points of the higher
values on the top.
Parameters
----------
x
the x coordinates
y
the y coordinates
v
the values for each point
s
the size of the scatters
Returns
-------
ax
"""
if v is not None:
# points with high values will be put on the top
x, y, v = list(zip(*sorted(zip(x, y, v), key=lambda xyv: xyv[-1])))
x, y, v = np.array(x), np.array(y), np.array(v)
if ax is None:
fig, ax = plt.subplots()
cax = ax.scatter(
x, y, c=v, s=s,
cmap=cmap, marker=marker,
vmax=vmax, vmin=vmin, **kwargs)
ax.grid(False)
x_margin = (max(x) - min(x)) * lim_margin
ax.set_xlim(min(x) - x_margin, max(x) + x_margin)
y_margin = (max(y) - min(y)) * lim_margin
ax.set_ylim(min(y) - y_margin, max(y) + y_margin)
# remove y and x ticks
ax.set_yticks([])
ax.set_xticks([])
if xlabel is not None:
ax.set_xlabel(xlabel, fontsize=fontsize_axlabels)
if ylabel is not None:
ax.set_ylabel(ylabel, fontsize=fontsize_axlabels)
if title:
ax.set_title(title, fontsize=fontsize_title)
ax.set_aspect('equal', adjustable='datalim')
if with_cbar and v is not None:
cbar = plt.colorbar(cax, ax=ax, pad=0.01, fraction=0.08, aspect=30, )
for t in cbar.ax.get_yticklabels():
t.set_fontsize(fontsize_cbar)
return ax
def embed_with_values(
xy: np.ndarray, values: Union[pd.Series, Mapping],
do_zscore: bool = False,
s: Union[int, None] = 1.5,
ncols=5, axscale=2.5,
name_xy='UMAP', with_cbar=True,
cmap='RdYlBu_r',
vmin=None, vmax=None,
**kwargs
):
""" Visualize the given x-y coordinates, colored by the given (dict of) values
Parameters
----------
xy: np.array
coordinates of each points, of shape (n_points, 2)
values: Mapping, pd.DataFrame or pd.Series
where the keys will be the title of subplots and each of the values
should be a vector of the length equal to xy.shape[0]
do_zscore
whether to calculate and display the z-scores instead of the original
values. (False)
s
the size of the scatters / points (1.5)
ncols
the number of columns for multiple-subplots (5)
axscale
adjust the size of the figures (2.5)
with_cbar
whether to display the color bars (True)
cmap
the colormap
vmin, vmax
the minimum and the maximum of the values
kwargs
Other Parameters for ``sorted_scatter``
"""
x, y = xy[:, 0], xy[:, 1]
if isinstance(values, pd.Series):
values = {values.name: list(values)}
elif do_zscore: # pd.DataFrame or Mapping[str, Sequence]
from sklearn.preprocessing import StandardScaler
keys = list(values.keys())
arr = np.array([list(values[k]) for k in keys])
values = pd.DataFrame(
StandardScaler(with_mean=True).fit_transform(arr).T, columns=keys)
cnames = values.keys()
n_plots = len(cnames)
if ncols >= n_plots:
nrows, ncols = 1, n_plots
else:
nrows = n_plots // ncols + min(n_plots % ncols, 1)
fig, axs = plt.subplots(
nrows, ncols, figsize=(ncols * axscale * 1.1, nrows * axscale),
subplot_kw=dict(aspect='equal'))
if name_xy is None:
xlabel = ylabel = ''
else:
xlabel = f'{name_xy}1'
ylabel = f'{name_xy}2'
if hasattr(axs, 'flatten'):
axs_flatten = axs.flatten()
else:
axs_flatten = np.array([axs])
s = 12000 / len(x) if s is None else s
for ax, cname in zip(axs_flatten, cnames):
v = list(values[cname])
sorted_scatter(x, y, v, s=s, ax=ax,
title=cname,
cmap=cmap,
vmin=vmin, vmax=vmax,
with_cbar=with_cbar,
xlabel=xlabel, ylabel=ylabel, **kwargs)
for ax in axs_flatten[n_plots:]:
ax.set_frame_on(False)
ax.grid(False)
# remove y and x ticks
ax.set_yticks([])
ax.set_xticks([])
return fig, axs
def adata_embed_with_values(
adata: sc.AnnData, values: Union[pd.Series, Mapping],
embed_key='UMAP', fp=None, figsize_save=None, **kwargs):
"""
This function can also be used to visualize the average expressions of some
cell types on gene embedding, in which case, each observation in
`adata` represents a genes.
Parameters
----------
adata
the ``AnnData`` object
values: Mapping, pd.DataFrame or pd.Series
where the keys will be the title of subplots and the values
should be of the length equal to adata.shape[0]
embed_key
the type of the embeddings, e.g., "UMAP" or "TSNE"
fp: Path or str
path to save figure
figsize_save: (int, int)
the figure size of the saved plot.
Returns
-------
fig, axs
"""
obsm_embed_key = 'X_{}'.format(embed_key.lower())
xy = adata.obsm[obsm_embed_key] # n_pts x 2
fig, axs = embed_with_values(xy, values, name_xy=embed_key, **kwargs)
if fp:
_save_with_adjust(fig, fp, figsize=figsize_save)
fig.show()
return fig, axs
# In[]
def _get_affine_mat(angle_x=30, angle_y=150):
""" rotate x and y axis to mock 3D projection
if angle_x=0, angle_y=90, an identity matrix will be returned.
"""
angle_x, angle_y = tuple(
map(lambda x: (x / 180) * np.pi, (angle_x, angle_y)))
_transmat = np.array([[np.cos(angle_x), np.sin(angle_x)],
[np.cos(angle_y), np.sin(angle_y)]
])
return _transmat
def _plot_edges(sids, tids,
xy1, xy2=None,
ax=None,
figsize=(4, 4), **kwds_edge):
"""
Parameters
----------
sids:
sequence of source ids, of shape (n_edges, )
tids:
sequence of target ids, of shape (n_edges, )
xy1:
x, y coordinates of source node (ids), of shape (n1, 2) or (n1+n2, 2)
xy2:
x, y coordinates of target node (ids)
"""
xy2 = xy1 if xy2 is None else xy2
if ax is None:
fig, ax = plt.subplots(figsize=figsize) # w*h
_kwds_edge = dict(c='gray', alpha=0.5, linewidth=0.08)
_kwds_edge.update(kwds_edge)
for pt1, pt2 in zip(xy1[sids], xy2[tids]):
ax.plot(*zip(pt1, pt2), **_kwds_edge)
return ax
def plot_edges_by_adj(adj: sparse.spmatrix, pos, ax=None, **kwds_edge):
""" adj: a sparse matrix, if None, nothing will be plotted"""
adj = sparse.triu(adj).tocoo()
sids, tids = adj.row, adj.col
return _plot_edges(sids, tids, xy1=pos, xy2=None, ax=ax, **kwds_edge)
def plot_mapped_graph(
xy1, xy2, mapping, adj1=None, adj2=None,
pt_color1=None, pt_color2=None,
cmap_pt='tab20',
angle_x=30, angle_y=150,
offset_scale=1.2,
yscale=1.,
pt_size=10,
style_name='default',
figsize=(5, 7),
fp=None,
**kwds_edge):
"""
pt_color1, pt_color2: RGB colors or numerical label sequence
"""
# style_name = ['dark_background', 'default'][1]
plt.style.use(style_name)
_kwds_edge = dict(c='white' if style_name == 'dark_background' else 'grey',
alpha=0.35, linewidth=0.08)
_kwds_edge.update(kwds_edge)
_transmat = _get_affine_mat(angle_x, angle_y)
xy1 = xy1.dot(_transmat)
xy2 = xy2.dot(_transmat)
x1, y1 = xy1[:, 0], xy1[:, 1]
x2, y2 = xy2[:, 0], xy2[:, 1]
y1 *= yscale
y2 *= yscale
y1 += max(y2) * offset_scale
fig, ax = plt.subplots(figsize=figsize) # w*h
if adj1 is not None:
plot_edges_by_adj(adj1, xy1, ax=ax, zorder=0.9, **_kwds_edge)
if adj2 is not None:
plot_edges_by_adj(adj2, xy2, ax=ax, zorder=0.9, **_kwds_edge)
plot_edges_by_adj(mapping, np.vstack([xy1, xy2]), ax=ax, zorder=1,
**_kwds_edge)
cmap_pt = cmap_pt if isinstance(cmap_pt, (list, tuple)) else [cmap_pt] * 2
ax.scatter(x1, y1, marker='.', c=pt_color1, s=pt_size, cmap=cmap_pt[0],
zorder=2.5)
ax.scatter(x2, y2, marker='.', c=pt_color2, s=pt_size, cmap=cmap_pt[1])
ax.set_axis_off()
_save_with_adjust(fig, fp, dpi=400)
plt.style.use('default')
return ax
def embedding_mock3d(
adata,
color: Optional[str] = 'module',
edges: bool = False,
neighbor_key: str = None,
pt_size: int = 10,
angle_x=30, angle_y=150,