-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmpl_cookbook.py
More file actions
1438 lines (1170 loc) · 52.6 KB
/
Copy pathmpl_cookbook.py
File metadata and controls
1438 lines (1170 loc) · 52.6 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
"""
Plotting functions and other utilities for having and easier time with
matplotlib and seaborn
"""
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.cm as mplcm
import seaborn as sns
import pandas as pd
import numpy as np
import scipy as sp
import re
from scipy.stats import gaussian_kde
from Bio import pairwise2
from collections import OrderedDict
# Custom colormaps
# Solar extra (aka the Jason classic)
solar_extra_colors = ['#3361A5', '#248AF3', '#14B3FF', '#88CEEF', '#C1D5DC', '#EAD397', '#FDB31A','#E42A2A','#A31D1D']
solar_extra = mpl.colors.LinearSegmentedColormap.from_list('CustomMap', solar_extra_colors)
solar_extra_r = mpl.colors.LinearSegmentedColormap.from_list('CustomMap', solar_extra_colors[::-1])
# 'Sunrise' (aka chromatin viridis)
sunrise_colors = ['#352A86', '#343DAE', '#0262E0', '#1389D2', '#2DB7A3', '#A5BE6A', '#F8BA43','#F6DA23','#F8FA0D']
sunrise = mpl.colors.LinearSegmentedColormap.from_list('CustomMap', sunrise_colors)
sunrise_r = mpl.colors.LinearSegmentedColormap.from_list('CustomMap', sunrise_colors[::-1])
# Samba Night
samba_colors = ['#1873CC', '#1798E5', '#00BFFF', '#4AC596', '#00CC00', '#A2E700', '#FFFF00','#FFD200','#FFA500']
samba_night = mpl.colors.LinearSegmentedColormap.from_list('CustomMap', samba_colors)
samba_night_r = mpl.colors.LinearSegmentedColormap.from_list('CustomMap', samba_colors[::-1])
# Fireworks
fireworks_colors = ['#ffffff', '#2488F0', '#7F3F98', '#E22929', '#FCB31A']
fireworks = mpl.colors.LinearSegmentedColormap.from_list('CustomMap', fireworks_colors)
fireworks_r = mpl.colors.LinearSegmentedColormap.from_list('CustomMap', fireworks_colors[::-1])
# Temperature (see: https://github.com/matplotlib/cmocean/blob/master/cmocean/rgb/thermal.py)
temperature_colors = ['#042333','#0d3165','#35339c','#5e3f9a','#7e4e90','#9f5a88','#c1647a','#e17262','#f78b46','#fcae3c','#f6d347','#e8fa5b']
temperature = mpl.colors.LinearSegmentedColormap.from_list('CustomMap', temperature_colors)
temperature_r = mpl.colors.LinearSegmentedColormap.from_list('CustomMap', temperature_colors[::-1])
# Utility functions
def rev_comp(seq, complement_dict={'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}, missing='N'):
# Reverse complement a sequence
return "".join(complement_dict.get(base, missing) for base in reversed(seq))
def texttoint(text):
# Convert string integers to true integers, if possible
return int(text) if text.isdigit() else text
def natural_keys(text):
# Custom key for sorting values that are strings, but contain integers
# Sorts based on the integer identified in a larger string
return [texttoint(c) for c in re.split('(\d+)', text)]
# R in kcal / mol*K
def dG_to_Kd(dG, temp=37, R=0.0019858775):
# Returns the Kd value in M
return (1/np.exp(-dG/(R*(temp + 273))))
def Kd_to_dG(Kd, temp=37, R=0.0019858775):
# Returns the dG value in kcal/mol, assuming Kd is in M
return (R*(temp + 273)*np.log(Kd))
def convert_dG_to_kT(dG, temp=37):
# k is the boltzman constant:
# k = 0.0019872 kcal / mol * K
# by default, dG is in kcal/mol
return dG / (0.0019872*(273 + temp))
# Plotting functions
"""
Generic plotting
These plotting functions are more general for exploring new data
"""
def show_colormaps(category=None, cmap_to_show=None):
"""
==================
Colormap reference
==================
Reference for colormaps included with Matplotlib.
This reference example shows all colormaps included with Matplotlib. Note that
any colormap listed here can be reversed by appending "_r" (e.g., "pink_r").
These colormaps are divided into the following categories:
Sequential:
These colormaps are approximately monochromatic colormaps varying smoothly
between two color tones---usually from low saturation (e.g. white) to high
saturation (e.g. a bright blue). Sequential colormaps are ideal for
representing most scientific data since they show a clear progression from
low-to-high values.
Diverging:
These colormaps have a median value (usually light in color) and vary
smoothly to two different color tones at high and low values. Diverging
colormaps are ideal when your data has a median value that is significant
(e.g. 0, such that positive and negative values are represented by
different colors of the colormap).
Qualitative:
These colormaps vary rapidly in color. Qualitative colormaps are useful for
choosing a set of discrete colors. For example::
color_list = plt.cm.Set3(np.linspace(0, 1, 12))
gives a list of RGB colors that are good for plotting a series of lines on
a dark background.
Miscellaneous:
Colormaps that don't fit into the categories above.
"""
# Have colormaps separated into categories:
# http://matplotlib.org/examples/color/colormaps_reference.html
cmaps = [('Perceptually Uniform Sequential', [
'viridis', 'plasma', 'inferno', 'magma']),
('Sequential', [
'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']),
('Sequential (2)', [
'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink',
'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',
'hot', 'afmhot', 'gist_heat', 'copper']),
('Diverging', [
'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic']),
('Qualitative', [
'Pastel1', 'Pastel2', 'Paired', 'Accent',
'Dark2', 'Set1', 'Set2', 'Set3',
'tab10', 'tab20', 'tab20b', 'tab20c']),
('Miscellaneous', [
'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg', 'hsv',
'gist_rainbow', 'rainbow', 'jet', 'nipy_spectral', 'gist_ncar'])]
nrows = max(len(cmap_list) for cmap_category, cmap_list in cmaps)
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
def plot_color_gradients(cmap_category, cmap_list, nrows):
fig, axes = plt.subplots(nrows=nrows)
fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99)
axes[0].set_title(cmap_category + ' colormaps', fontsize=14)
for ax, name in zip(axes, cmap_list):
ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name))
pos = list(ax.get_position().bounds)
x_text = pos[0] - 0.01
y_text = pos[1] + pos[3]/2.
fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10)
# Turn off *all* ticks & spines, not just the ones with colormaps.
for ax in axes:
ax.set_axis_off()
if category:
for cmap_category, cmap_list in cmaps:
if cmap_category == category:
plot_color_gradients(cmap_category, cmap_list, nrows)
else:
for cmap_category, cmap_list in cmaps:
plot_color_gradients(cmap_category, cmap_list, nrows)
plt.show()
def get_colors(cmap_name, num_colors):
"""
Get a number of evenly spaced colors from a provided colormap
Inputs:
cmap (str) -- name of colormap
num_colors (int) -- number of colors to get
Outputs:
colors (list) -- list of RGBA tuples
"""
cmap = mplcm.get_cmap(cmap_name)
return [cmap(x) for x in np.linspace(0,1,num_colors)]
def plot_cdf(ax, x, kwargs={}):
"""
Plot a CDF of array-like data x
Inputs:
ax (matplotlib axes class) -- The Axes instance on which to plot
x (array-like) -- values from which to generate CDF
Output:
ax (matplotlib axes class) -- returns the modified axes object
"""
cleaned_x = [i for i in x if np.isfinite(i)]
sorted_x = sorted(cleaned_x)
cumulative_fraction = np.linspace(0,1,len(sorted_x))
ax.plot(sorted_x, cumulative_fraction, **kwargs)
ax.set_ylim(0, 1.05)
return ax
def plot_histogram(ax, x, bins=50, log=False, remove_outliers=False, kwargs={}):
"""
Plot a histogram of values provided values
Inputs:
ax (matplotlib axes class) -- The Axes instance on which to plot
x (array-like) -- values from which to plot histogram
bins (int) -- number of bins for histogram
log (bool) -- should the histogram be plotted in log space? (log10)
remove_outliers (bool or numeric) -- Should outliers be removed? (uses
a sigma of 3 by default, but other values may be provided)
Outputs:
ax (matplotlib axes class) -- The modified axes object
"""
cleaned_x = [i for i in x if np.isfinite(i)]
if remove_outliers:
# Remove outliers by sigma cutoff
if isinstance(remove_outliers, int) or isinstance(remove_outliers, float):
cutoff = remove_outliers
else:
cutoff = 3.0
if log:
mean = np.mean(np.log10(cleaned_x))
std = np.std(np.log10(cleaned_x))
else:
mean = np.mean(cleaned_x)
std = np.std(np.log10(cleaned_x))
cut_high = mean + cutoff*std
cut_low = mean - cutoff*std
cleaned_x = [i for i in x if (i < cut_high) & (i > cut_low)]
if log:
ax.hist(x=cleaned_x, bins=np.logspace(np.log10(min(cleaned_x)), np.log10(max(cleaned_x)), bins), **kwargs)
ax.set_xscale("log")
else:
ax.hist(x=cleaned_x, bins=bins, **kwargs)
return ax
def reg_scatter(ax, x, y,
showR2=False, showRMSE=False, square=False,
eqLine=None, linFit=None, splineFit=None, label_loc=None, kwargs={}):
"""
Create a linear scatter plot with points colored by gaussian density
Inputs:
ax (matplotlib axes class) -- The Axes instance on which to plot
x (array-like) -- values to plot on x axis
y (array-like) -- values to plot on y axis (must be same length as x)
square (bool) -- should axis be forced to be equal?
eqLine (Dict/bool) -- plotting parameters for a one to one line (i.e. x=y line)
linFit (Dict/bool) -- plotting parameters for a linear regression line
splineFit (Dict/bool) -- plotting parameters for a smoothing spline
kwargs (Dict) -- keyword arguments to be passed to the scatter plot function
Output:
ax (matplotlib axes class) -- returns the modified axes object
"""
# Adjust line parameters if necessary
default_line_params = {"ls": "--", "c": "black", "linewidth": 3}
eq_params = default_line_params.copy()
lin_params = default_line_params.copy()
spl_params = default_line_params.copy()
for curr_params, new_params in zip([eq_params, lin_params, spl_params],[eqLine, linFit, splineFit]):
if type(new_params) is dict:
for key, val in new_params.items():
curr_params[key] = val
# Check data first for correct data
if len(x) != len(y):
raise ValueError("x and y are not of same length")
# Scrub missing values
nonans = [xy for xy in zip(x, y) if all(np.isfinite(xy))]
x, y = [np.array(i) for i in zip(*nonans)]
# Get pearson correlation
xy_pcorr = sp.stats.pearsonr(x, y)
# default R2
r2 = xy_pcorr[0]**2
# default RMSE:
xy_rmse = np.sqrt(np.mean((x - y)**2))
# Make plot:
ax.scatter(x, y, zorder=4, **kwargs)
xmin, xmax = ax.get_xlim()
ymin, ymax = ax.get_ylim()
# Optional plot additions
if square:
xmin, ymin = [min([xmin, ymin])]*2
xmax, ymax = [max([xmax, ymax])]*2
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
# make x ticks and y ticks equal
xticks = ax.get_xticks()
ax.set_yticks(xticks[1:-1])
ax.set_aspect(1)
if eqLine:
# draw a diagonal line:
ax.plot([xmin, xmax], [ymin, ymax], ls=eq_params["ls"], c=eq_params["c"], linewidth=eq_params["linewidth"], zorder=1)
# R2 doesn't change
# xy_rmse doesn't change
if linFit:
# get linear regression of y on x
linreg = sp.stats.linregress(x, y)
plotx = np.array(ax.get_xlim())
ploty = plotx*linreg[0] + linreg[1]
newy = x*linreg[0] + linreg[1]
ax.plot(plotx, ploty, ls=lin_params["ls"], c=lin_params["c"], linewidth=lin_params["linewidth"], zorder=2)
r2 = linreg[2]**2
xy_rmse = np.sqrt(np.mean((y - newy)**2))
if splineFit:
# get natural cubic spline
# (spline function requires sorted x values)
x, y = zip(*sorted(zip(x,y), key=lambda tup: tup[0]))
# Need to also handle duplicate x-values?
prev_x = None
new_x = []
new_y = []
for x, y in zip(x,y):
if x == prev_x:
continue
else:
new_x.append(x)
new_y.append(y)
prev_x = x
x = np.array(new_x)
y = np.array(new_y)
cs = sp.interpolate.UnivariateSpline(x, y)
xs = np.arange(min(x), max(x), (max(x)-min(x))/100)
newy = cs(xs)
ax.plot(xs, newy, ls=spl_params["ls"], c=spl_params["c"], linewidth=spl_params["linewidth"], zorder=3)
# R^2 = 1 - RSS/TSS
RSS = sum((y - cs(x))**2)
TSS = sum((y - np.mean(y))**2)
r2 = 1 - RSS/TSS
xy_rmse = np.sqrt(np.mean((y - cs(x))**2))
label_txt = None
if showR2 and showRMSE:
label_txt = "$R^2 = {:0.3f} $\n$ RMSE = {:0.3f}$".format(r2, xy_rmse)
elif showR2:
label_txt = "$R^2 = {:0.3f}$".format(r2)
elif showRMSE:
label_txt = "$RMSE = {:0.3f}$".format(xy_rmse)
if label_txt:
if label_loc=="bottom_right":
ax.text(0.95, 0.05, label_txt, transform=ax.transAxes,
verticalalignment='bottom', horizontalalignment='right',
bbox={'facecolor': ax.get_facecolor(), 'alpha': 1.0, 'pad': 10, 'edgecolor':'none'})
else:
ax.text(0.05, 0.95, label_txt, transform=ax.transAxes,
verticalalignment='top', horizontalalignment='left',
bbox={'facecolor': ax.get_facecolor(), 'alpha': 1.0, 'pad': 10, 'edgecolor':'none'})
return ax
def density_scatter(ax, x, y,
showR2=False, showRMSE=False, square=False,
eqLine=None, linFit=None, splineFit=None, cmap="viridis", kwargs={}):
"""
Create a linear scatter plot with points colored by gaussian density
Inputs:
ax (matplotlib axes class) -- The Axes instance on which to plot
x (array-like) -- values to plot on x axis
y (array-like) -- values to plot on y axis (must be same length as x)
square (bool) -- should axis be forced to be equal?
eqLine (Dict/bool) -- plotting parameters for a one to one line (i.e. x=y line)
linFit (Dict/bool) -- plotting parameters for a linear regression line
splineFit (Dict/bool) -- plotting parameters for a smoothing spline
kwargs (Dict) -- keyword arguments to be passed to the scatter plot function
Output:
ax (matplotlib axes class) -- returns the modified axes object
"""
# Adjust line parameters if necessary
default_line_params = {"ls": "--", "c": "black", "linewidth": 3}
eq_params = default_line_params.copy()
lin_params = default_line_params.copy()
spl_params = default_line_params.copy()
for curr_params, new_params in zip([eq_params, lin_params, spl_params],[eqLine, linFit, splineFit]):
if type(new_params) is dict:
for key, val in new_params.items():
curr_params[key] = val
# Check data first for correct data
if len(x) != len(y):
raise ValueError("x and y are not of same length")
# Scrub missing values
nonans = [xy for xy in zip(x, y) if all(np.isfinite(xy))]
x, y = [np.array(i) for i in zip(*nonans)]
# Calculate point density
xy = np.vstack([x,y])
z = gaussian_kde(xy)(xy)
# Note that gaussian_kde returns a kernel function--
# calling it as above evaluates that kernel function (the estimated pdf) for a set of provided points
# sort points by density
idx = z.argsort()
x, y, z = x[idx], y[idx], z[idx]
# Get pearson correlation
xy_pcorr = sp.stats.pearsonr(x, y)
# default R2
r2 = xy_pcorr[0]**2
# default RMSE:
xy_rmse = np.sqrt(np.mean((x - y)**2))
# Make plot:
ax.scatter(x, y, c=z, cmap=cmap, edgecolors='', zorder=4, **kwargs)
xmin, xmax = ax.get_xlim()
ymin, ymax = ax.get_ylim()
# Optional plot additions
if square:
xmin, ymin = [min([xmin, ymin])]*2
xmax, ymax = [max([xmax, ymax])]*2
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
ax.set_aspect(1)
if eqLine:
# draw a diagonal line:
ax.plot([xmin, xmax], [ymin, ymax], ls=eq_params["ls"], c=eq_params["c"], linewidth=eq_params["linewidth"], zorder=1)
# R2 doesn't change
# xy_rmse doesn't change
if linFit:
# get linear regression of y on x
linreg = sp.stats.linregress(x, y)
plotx = np.array(ax.get_xlim())
ploty = plotx*linreg[0] + linreg[1]
newy = x*linreg[0] + linreg[1]
ax.plot(plotx, ploty, ls=lin_params["ls"], c=lin_params["c"], linewidth=lin_params["linewidth"], zorder=2)
r2 = linreg[2]**2
xy_rmse = np.sqrt(np.mean((y - newy)**2))
if splineFit:
# get natural cubic spline
# (spline function requires sorted x values)
x, y = zip(*sorted(zip(x,y), key=lambda tup: tup[0]))
# Need to also handle duplicate x-values?
prev_x = None
new_x = []
new_y = []
for x, y in zip(x,y):
if x == prev_x:
continue
else:
new_x.append(x)
new_y.append(y)
prev_x = x
x = np.array(new_x)
y = np.array(new_y)
cs = sp.interpolate.UnivariateSpline(x, y)
xs = np.arange(min(x), max(x), (max(x)-min(x))/100)
newy = cs(xs)
ax.plot(xs, newy, ls=spl_params["ls"], c=spl_params["c"], linewidth=spl_params["linewidth"], zorder=3)
# R^2 = 1 - RSS/TSS
RSS = sum((y - cs(x))**2)
TSS = sum((y - np.mean(y))**2)
r2 = 1 - RSS/TSS
xy_rmse = np.sqrt(np.mean((y - cs(x))**2))
if showR2 and showRMSE:
label_txt = "$R^2 = {:0.3f} $\n$ RMSE = {:0.3f}$".format(r2, xy_rmse)
ax.text(0.7, 0.15, label_txt, transform=ax.transAxes, verticalalignment='top', fontsize=14,
bbox={'facecolor': ax.get_facecolor(), 'alpha': 1.0, 'pad': 10, 'edgecolor':'none'})
elif showR2:
label_txt = "$R^2 = {:0.3f}$".format(r2)
ax.text(0.05, 0.95, label_txt, transform=ax.transAxes, verticalalignment='top', fontsize=12,
bbox={'facecolor': ax.get_facecolor(), 'alpha': 1.0, 'pad': 10, 'edgecolor':'none'})
elif showRMSE:
label_txt = "$RMSE = {:0.3f}$".format(xy_rmse)
ax.text(0.05, 0.95, label_txt, transform=ax.transAxes, verticalalignment='top', fontsize=12,
bbox={'facecolor': ax.get_facecolor(), 'alpha': 1.0, 'pad': 10, 'edgecolor':'none'})
return ax
"""
Ago project plotting
These plotting functions are more specific to the Ago projects Winston and I
have been working on. Be warned that some of them may have functionality that
is fairly specific to those kinds of data.
"""
### Annotation Corrections ###
def get_inverted_annotations(annot_series, wt_seq, annot_col="annotation"):
"""
Wrapper to get an inverted annotation series from an uninverted annotation series.
(Right now only works for point-mutant annotation styles)
"""
wt_base_labels = list(wt_seq)
return annot_series.apply(lambda x: invert_annot_numbering(x, len(wt_base_labels)))
def invert_annot_numbering(annot, max_num):
"""
Specific to Ago libraries. Original library annotations were target-focused.
Often times, you want to think about things from the guide persepctive.
This function alters the mutation position numbering to be guide-focused.
"""
context, swaps = annot.split('_')
all_swaps = swaps.split(',')
new_swaps = []
for swap in all_swaps:
num, text = re.split('(\d+)', swap)[1:]
new_swaps.append(str(max_num + 1 - int(num)) + text)
return context + '_' + ','.join(new_swaps)
######################################
### Double Mutant Heatmap Plotting ###
######################################
def parse_point_mut_annot(annotation, out='swaps', get_flank=False):
"""
Pull out the individual mutations from a point mutant annotation.
Return these point mutations as a list.
"""
flank, swaps = annotation.split('_')
individual_swaps = swaps.split(',')
if out=='swaps':
if get_flank:
return flank, individual_swaps
return individual_swaps
if out=='pos':
positions = []
for swap in individual_swaps:
num, text = re.split('(\d+)', swap)[1:]
positions.append(int(num))
if get_flank:
return flank, sorted(positions)
return sorted(positions)
def construct_double_mut_df(dm_df, value, annot_col="annotation"):
"""
Construct a square data frame for a set of double mutants
Inputs:
dm_df (DataFrame) -- A dataframe of double mutants to be formatted into
the square dataframe. Must contain a column of 'Ago-style' double
mutant annotations.
value (str) -- the column name indicating which value should be put in
the square double mutant dataframe.
annot_col (str) -- the annotation column name
Outputs:
new_frame (DataFrame) -- a square dataframe containing the indicated
value at double mutant coordinate positions. This dataframe will
be symmetric across the BL-TR diagonal.
"""
# split mutations annotations and get value of interest:
list_data = dm_df.apply(lambda x: \
parse_point_mut_annot(x[annot_col]) + [x[value]],
axis=1).tolist()
df_data = pd.DataFrame(list_data)
df_data.columns = ['first_mut', 'second_mut', 'value']
# Get a sorted list of all possible base swaps:
keys = sorted(list(set([x[0] for x in list_data] + [x[1] for x in list_data])),
key=natural_keys)
# Fill in square dataframe with desired double mutant values
new_frame = pd.DataFrame(index=keys[::-1], columns=keys)
def fill_in_dm_frame(row, df_to_fill):
# Apply function for filling in a square dataframe
mut1 = row['first_mut']
mut2 = row['second_mut']
value = row['value']
df_to_fill.loc[mut1, mut2] = value
df_to_fill.loc[mut2, mut1] = value
df_data.apply(lambda x: fill_in_dm_frame(x, new_frame), axis=1)
return new_frame
def add_singles_to_dm_df(sm_df, dm_df, value, annot_col="annotation"):
"""
Add single mutant values to the diagonal of a prepared double mutant
heatmap
Inputs:
sm_df (DataFrame) -- A dataframe of single mutants
dm_df (DataFrame) -- A square dataframe of previously formated double mutants
value (str) -- column name indicating which value should be put in
the dataframe
annot_col (str) -- the annotation column name
Outputs:
new_frame (DataFrame) -- modified dm dataframe with single mutants
in diagonal
"""
# split mutations annotations and get value of interest:
list_data = sm_df.apply(lambda x: parse_point_mut_annot(x[annot_col]) + [x[value]],
axis=1).tolist()
sm_data = pd.DataFrame(list_data)
sm_data.columns = ['first_mut', 'value']
#print sm_data.head()
# Put single mutants in dm df
new_frame = dm_df.copy()
for ix, row in sm_data.iterrows():
pos = row['first_mut']
val = row['value']
new_frame.loc[pos,pos] = val
return new_frame
def construct_position_median_dm_df(dm_df, value, annot_col="mut_annotation"):
"""
Construct a square data frame of position-median double mutant values
(i.e. median of 9 for a single dataset)
Inputs:
dm_df (DataFrame) -- A dataframe of double mutants to be formatted into
the square dataframe. Must contain a column of 'Ago-style' double
mutant annotations.
value (str) -- the column name indicating which value should be put in
the square double mutant dataframe.
annot_col (str) -- the annotation column name
Outputs:
new_frame (DataFrame) -- a square dataframe containing the indicated
value at double mutant coordinate positions. This dataframe will
be symmetric across the BL-TR diagonal.
"""
# split mutations annotations and get value of interest:
list_data = dm_df.apply(lambda x: \
parse_point_mut_annot(x[annot_col], out='pos') + [x[value]],
axis=1).tolist()
df_data = pd.DataFrame(list_data)
df_data.columns = ['first_mut', 'second_mut', 'value']
# Get a sorted list of all possible base swaps:
keys = sorted(list(set([x[0] for x in list_data] + [x[1] for x in list_data])))
# Fill in square dataframe with desired double mutant values
new_frame = pd.DataFrame(index=keys[::-1], columns=keys)
for i in range(1, len(keys)+1,1):
for j in range(1, i, 1):
if i == j:
continue
med_dat = df_data[(df_data.first_mut == j) & (df_data.second_mut == i)]['value'].median()
new_frame.loc[i,j] = med_dat
new_frame.loc[j,i] = med_dat
return new_frame
def combine_double_mut_dfs(upper_df, lower_df):
"""
If you have two square dataframes, this function lets you merge them
into one dataframe (across a BL to TR diagonal)
Maintains the indices of the 'upper_df' and the column names of the 'lower_df'
"""
nrows = len(upper_df.index)
ncols = len(upper_df.columns)
combined_df = upper_df.copy()
for i in range(nrows):
for j in range(ncols):
if nrows - i <= j:
combined_df.iloc[i,j] = lower_df.iloc[i,j]
combined_df.columns = lower_df.columns
return combined_df
def double_mutant_heatmap(ax, dm_df, mask_color="lightgrey", cmap="viridis", cbar_label="",
splitCells=None, splitColor="lightgrey", slim_ticks=True, kwargs={}):
"""
Plot a double mutant heatmap.
Inputs:
ax (matplotlib axes class) -- The Axes instance on which to plot
dm_df (DataFrame) -- The rectangular dataframe containing data to plot
cbar_label (str) -- The label for the colorbar (color bar limits can be passed to kwargs under 'vmax'/'vmin')
splitCells (tuple of ints) -- should divisions between groups of cells be highlighted? Send a 2-member tuple
where the first int is the split frequency for rows and the second int is the split frequency for columns
splitColor (str) -- The color to be used between cells that are split
Output:
hm (matplotlib axes class) -- returns the modified axes object
"""
# cast all data to float (to prevent sns.heatmap from being a baby)
plot_df = dm_df.astype(float)
# this is how you change the 'mask' color
ax.set_facecolor(mask_color)
hm = sns.heatmap(plot_df, ax=ax, cmap=cmap, square=True, cbar_kws={'label':cbar_label}, **kwargs)
if splitCells:
ax.hlines([splitCells[0]*i for i in range(len(dm_df.index))], *ax.get_xlim(), color=splitColor, linewidth=1)
ax.vlines([splitCells[1]*i for i in range(len(dm_df.columns))], *ax.get_ylim(), color=splitColor, linewidth=1)
if slim_ticks:
xlabels = [item.get_text().split(">")[-1] for item in ax.get_xticklabels()]
ylabels = [item.get_text().split(">")[-1] for item in ax.get_yticklabels()]
ax.set_xticklabels(xlabels)
ax.set_yticklabels(ylabels)
xtick_pos = ax.get_xticks()
ytick_pos = ax.get_yticks()
x_pos_step = xtick_pos[1] - xtick_pos[0]
y_pos_step = ytick_pos[1] - ytick_pos[0]
new_xpos = []
new_ypos = []
for i, pos in enumerate(xtick_pos):
if i % 3 == 0:
new_xpos.append(pos + x_pos_step*0.1)
elif i % 3 == 2:
new_xpos.append(pos - x_pos_step*0.1)
else:
new_xpos.append(pos)
for i, pos in enumerate(ytick_pos):
if i % 3 == 0:
new_ypos.append(pos + y_pos_step*0.1)
elif i % 3 == 2:
new_ypos.append(pos - y_pos_step*0.1)
else:
new_ypos.append(pos)
ax.set_xticks(new_xpos)
ax.set_yticks(new_ypos)
plt.xticks(rotation=0)
return hm
def single_mutant_heatmap(ax, sm_df, mask_color="lightgrey", cmap="viridis", cbar_label="",
splitCells=None, splitColor="lightgrey", slim_ticks=True, kwargs={}):
"""
Plot a single mutant heatmap.
Inputs:
ax (matplotlib axes class) -- The Axes instance on which to plot
sm_df (DataFrame) -- The dataframe containing data to plot
cbar_label (str) -- The label for the colorbar (color bar limits can be passed to kwargs under 'vmax'/'vmin')
splitCells (tuple of ints) -- should divisions between groups of cells be highlighted? Send a 2-member tuple
where the first int is the split frequency for rows and the second int is the split frequency for columns
splitColor (str) -- The color to be used between cells that are split
Output:
hm (matplotlib axes class) -- returns the modified axes object
"""
# cast all data to float (to prevent sns.heatmap from being a baby)
plot_df = sm_df.astype(float)
# this is how you change the 'mask' color
ax.set_facecolor(mask_color)
hm = sns.heatmap(plot_df, ax=ax, cmap=cmap, cbar_kws={'label':cbar_label}, **kwargs)
if splitCells:
ax.hlines([splitCells[0]*i for i in range(len(sm_df.index))], *ax.get_xlim(), color=splitColor, linewidth=1)
ax.vlines([splitCells[1]*i for i in range(len(sm_df.columns))], *ax.get_ylim(), color=splitColor, linewidth=1)
if slim_ticks:
xlabels = [item.get_text().split(">")[-1] for item in ax.get_xticklabels()]
ax.set_xticklabels(xlabels)
xtick_pos = ax.get_xticks()
x_pos_step = xtick_pos[1] - xtick_pos[0]
new_xpos = []
for i, pos in enumerate(xtick_pos):
if i % 3 == 0:
new_xpos.append(pos + x_pos_step*0.1)
elif i % 3 == 2:
new_xpos.append(pos - x_pos_step*0.1)
else:
new_xpos.append(pos)
ax.set_xticks(new_xpos)
plt.xticks(rotation=0)
return hm
def construct_single_mut_df(sm_df, value, annot_col="annotation"):
"""
Construct a data frame for a set of single mutants, potentially
with multiple base contexts
Inputs:
sm_df (DataFrame) -- A dataframe of single mutants to be formatted into
the (context) dataframe. Must contain a column of 'Ago-style' single
mutant annotations.
value (str) -- the column name indicating which value should be put in
the single mutant dataframe.
annot_col (str) -- the annotation column name
Outputs:
new_frame (DataFrame) -- a context x mutant dataframe containing the indicated
value at each context and mutant position.
"""
# split mutations annotations and get value of interest:
flanks_and_swaps = sm_df.apply(lambda x: \
parse_point_mut_annot(x[annot_col], get_flank=True),
axis=1).tolist()
flanks, swaps = zip(*flanks_and_swaps)
# Reformat
flanks = list(flanks)
swaps = [x[0] for x in swaps]
vals = sm_df[value].tolist()
df_data = pd.DataFrame([flanks, swaps, vals]).T
df_data.columns = ['flank', 'swap', 'value']
# Get a sorted list of all possible base swaps:
keys = sorted(list(set(swaps)),
key=natural_keys)
# Fill in square dataframe with desired double mutant values
new_frame = pd.DataFrame(index=list(set(flanks)), columns=keys)
def fill_in_sm_frame(row, df_to_fill):
# Apply function for filling in a square dataframe
flank = row['flank']
swap = row['swap']
value = row['value']
df_to_fill.loc[flank, swap] = value
df_data.apply(lambda x: fill_in_sm_frame(x, new_frame), axis=1)
return new_frame
##########################################
### Cumulative Mutant Heatmap Plotting ###
##########################################
def is_cumulative_mut(row, wt_seq, flank = "AAAAA",
cm_dict={"A": "T", "T": "A", "G": "C", "C": "G"}):
"""
Manually determine if sequence is cumulative mutant
"""
if row.sequence[:5] != flank or row.sequence[-5:] != flank:
# Make sure flank is correct
return "NA"
seq = row.sequence[5:-5]
if len(seq) != len(wt_seq):
# If seq lengths are not equal, not a cumulative mutant
return "NA"
start = 1
end = 1
in_mut = False
found_end = False
for i, (a, b) in enumerate(zip(seq, wt_seq)):
if a == b:
if in_mut:
# End of mutant stretch, mark end
end = i
found_end = True
in_mut = False
elif a == cm_dict[b]:
if found_end:
return "NA" # Already had one mutant stretch. Not continuous
if not in_mut:
start = i + 1
in_mut = True
else:
return "NA" # Not a complement mismatch
# If got all the way to end of sequence, set end
if in_mut and not found_end:
end = len(seq)
if not in_mut and not found_end:
# no mutations found
return "NA"
return "_".join(["polyA", "comp", str(start), "to", str(end)])
def parse_cumulative_mut_annot(annotation, get_flank=False):
"""
Pull out the beginning and end point of cumulative mutant.
Return these as a list.
"""
flank, comp, start, to, end = annotation.split('_')
return [int(x) for x in [start, end]]
def construct_cumulative_mut_df(cm_df, value, annot_col="annotation", reverse=True):
"""
Construct a square data frame for cumulative mutants
Inputs:
cm_df (DataFrame) -- A dataframe of cumulative mutants to be formatted into
the square dataframe. Must contain a column of 'Ago-style' double
mutant annotations.
value (str) -- the column name indicating which value should be put in
the square double mutant dataframe.
annot_col (str) -- the annotation column name
Outputs:
new_frame (DataFrame) -- a square dataframe containing the indicated
value at double mutant coordinate positions. This dataframe will
be symmetric across the BL-TR diagonal.
"""
# split mutations annotations and get value of interest:
list_data = cm_df.apply(lambda x: \
parse_cumulative_mut_annot(x[annot_col]) + [x[value]],
axis=1).tolist()
df_data = pd.DataFrame(list_data)
df_data.columns = ['start_pos', 'end_pos', 'value']
# Get range of positions
first_pos = min(df_data.start_pos.values)
last_pos = max(df_data.end_pos.values)
all_pos = range(first_pos, last_pos + 1)
# Reverse orientation to be guide-centric
if reverse:
new_start = last_pos - df_data.end_pos + 1
new_end = last_pos - df_data.start_pos + 1
df_data.start_pos = new_start
df_data.end_pos = new_end
# Fill in square dataframe with desired double mutant values
new_frame = pd.DataFrame(index=all_pos[::-1], columns=all_pos)
def fill_in_cm_frame(row, df_to_fill):
# Apply function for filling in a square dataframe
p1 = row['start_pos']
p2 = row['end_pos']
value = row['value']
df_to_fill.loc[p1, p2] = value
df_to_fill.loc[p2, p1] = value
df_data.apply(lambda x: fill_in_cm_frame(x, new_frame), axis=1)
return new_frame
def cumulative_mutant_heatmap(ax, cm_df, mask_color="lightgrey", cmap="viridis", cbar_label="", kwargs={}):
"""
Plot a cumulative mutant heatmap.
Inputs:
ax (matplotlib axes class) -- The Axes instance on which to plot
cm_df (DataFrame) -- The square dataframe containing data to plot
cbar_label (str) -- The label for the colorbar (color bar limits can be passed to kwargs under 'vmax'/'vmin')
Output:
hm (matplotlib axes class) -- returns the modified axes object
"""
# cast all data to float (to prevent sns.heatmap from being a baby)
plot_df = cm_df.astype(float)
# this is how you change the 'mask' color
ax.set_facecolor(mask_color)
hm = sns.heatmap(plot_df, ax=ax, cmap=cmap, square=True, cbar_kws={'label':cbar_label}, **kwargs)
return hm
############################
### Tandem mismatch Plots ##
############################
def make_tandem_mutant_df(mut_df):
"""
Given a dataframe already filtered to the mutant class you're interested in,
generate a tandem mutant df
"""
orig_col_names = mut_df.columns.tolist()