/
mplot.py
1309 lines (993 loc) · 48.3 KB
/
mplot.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
"""
Minimal plotting functions implemented through matplotlib.
"""
############# PACKAGES #############
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
#matplotlib.rcParams['pdf.fonttype'] = 42
from matplotlib.ticker import FixedLocator
from scipy.stats.kde import gaussian_kde
from copy import deepcopy
############# PARAMETERS #############
#matplotlib.rcParams['pdf.fonttype'] = 42
blues = {
3 : ['#3182bd', '#9ecae1', '#deebf7'],
4 : ['#525252', '#969696', '#cccccc', '#f7f7f7'],
5 : ['#252525', '#636363', '#969696', '#cccccc', '#f7f7f7'],
6 : ['#252525', '#636363', '#969696', '#bdbdbd', '#d9d9d9', '#f7f7f7'],
7 : ['#252525', '#525252', '#737373', '#969696', '#bdbdbd', '#d9d9d9', '#f7f7f7'],
8 : ['#252525', '#525252', '#737373', '#969696', '#bdbdbd', '#d9d9d9', '#f0f0f0', '#ffffff']
}
greys = {
3 : ['#636363', '#bdbdbd', '#f0f0f0'],
4 : ['#2171b5', '#6baed6', '#bdd7e7', '#eff3ff'],
5 : ['#08519c', '#3182bd', '#6baed6', '#bdd7e7', '#eff3ff'],
6 : ['#08519c', '#3182bd', '#6baed6', '#9ecae1', '#c6dbef', '#eff3ff'],
7 : ['#084594', '#2171b5', '#4292c6', '#6baed6', '#9ecae1', '#c6dbef', '#eff3ff'],
8 : ['#084594', '#2171b5', '#4292c6', '#6baed6', '#9ecae1', '#c6dbef', '#deebf7', '#f7fbff']
}
defcolor = '#252525'
defplotcolor = '#2171b5'
defpaircolor = ['#2171b5', '#9ecae1']
def cm2inch(x): return float(x)/2.54
goldr = (1.0 + np.sqrt(5)) / 2.0
nbins = 50
aspect = 1.0
plotwidth = cm2inch(8.90)
offset = 0.02
offsetpt = 1.0
sublabelx = -0.10
sublabely = 0.95
ticklength = 3
tickpad = 3
axwidth = 0.4
sizedot = 8.
sizeline = 0.8
textcolor = defcolor
# paper
fontfamily = 'Arial'
sizesublabel = 8
sizetext = 6
sizelabel = 6
sizetick = 6
smallsizedot = 6.
## grant
#fontfamily = 'Arial'
#sizesublabel = 12
#sizetext = 8
#sizelabel = 8
#sizetick = 8
#smallsizedot = 6. * 2
#sizeline = 1
##slides/poster
#fontfamily = 'Avenir'
#sizesublabel = 18 #24 #18
#sizetext = 18 #24 #18
#sizelabel = 18 #24 #18
#sizetick = 18 #24 #18
#smallsizedot = 6. * 4
#axwidth = 1.5
#sizeline = 3.0
def_labelprops = {
'family' : fontfamily,
'size' : sizelabel,
'color' : textcolor
}
def_sublabelprops = {
'family' : fontfamily,
'size' : sizesublabel,
'weight' : 'bold',
'ha' : 'center',
'va' : 'center',
'color' : 'k'
}
def_ticklabelprops = {
'family' : fontfamily,
'size' : sizetick,
'color' : textcolor
}
def_axprops = {
'linewidth' : axwidth,
'linestyle' : '-',
'color' : textcolor
}
def_tickprops = {
'length' : ticklength,
'width' : axwidth/2,
'pad' : tickpad,
'axis' : 'both',
'direction' : 'out',
'colors' : textcolor,
'bottom' : True,
'left' : True,
'top' : False,
'right' : False
}
def_minortickprops = {
'length' : ticklength-1.25,
'width' : axwidth/2,
'axis' : 'both',
'direction' : 'out',
'which' : 'minor',
'colors' : textcolor
}
def_legendprops = {
'loc' : 1,
'frameon' : False,
'scatterpoints' : 1,
'handletextpad' : -0.1,
'prop' : {'size' : sizelabel}
}
def_scatterprops = {
'lw' : 0,
's' : sizedot,
'marker' : 'o'
}
# Define a new function "callout" which circles points on a scatter plot and labels them
# Need properties for the arrows, the scatter points, and the text
def_callscatterprops = {
'lw' : sizeline,
's' : sizedot,
'marker' : 'o'
}
def_callarrowprops = {
'lw' : sizeline,
's' : sizedot,
'marker' : 'o'
}
def_errorprops = {
'mew' : 0,
'markersize' : smallsizedot/2,
'fmt' : 'o',
'elinewidth' : sizeline/2,
'capthick' : 0,
'capsize' : 0
}
def_lineprops = {
'lw' : sizeline,
'ls' : '-',
#'drawstyle' : 'steps'
}
def_fillprops = {
'lw' : sizeline,
'linestyle' : '-',
'interpolate' : True
}
# NEW STYLE SOLID
def_histprops = {
'histtype' : 'bar',
'lw' : sizeline/2,
'ls' : 'solid',
'edgecolor' : defcolor,
'align' : 'left'
}
# OLD STYLE OUTLINE
#def_histprops = {
# 'histtype' : 'step',#'bar',
# 'lw' : sizeline,#/2,
# 'ls' : 'solid',
# #'edgecolor' : defcolor
# }
def_barprops = {
'lw' : sizeline/2,
'width' : 1,
'edgecolor' : defcolor,
'align' : 'center', #other option: edge
'orientation' : 'vertical'
}
def_violinprops = {
'vert' : False,
'widths' : 0.5, # Maximum height for violin, ~ half of vertical space
'showmeans' : True,
'showextrema' : False,
'showmedians' : False,
'points' : 100, # number of points to evaluate for Gaussian KDE
'bw_method' : 'silverman'
}
def_hexbinprops = {
'gridsize' : (50,50),
'mincnt' : 1,
'xscale' : 'linear',
'yscale' : 'linear',
'lw' : axwidth/4.
}
def_contourprops = {
'linewidths' : sizeline/2,
'linestyles' : 'solid'
}
def_vplineprops = {
'lw' : axwidth,
'color' : defcolor
}
def_figprops = {
'transparent' : True,
'bbox_inches' : 'tight'
}
def_tickprops_boxed = {
'length' : ticklength/1.75,
'width' : axwidth/1.75,
'pad' : tickpad,
'axis' : 'both',
'direction' : 'in',
'colors' : textcolor,
'bottom' : True,
'left' : True,
'top' : True,
'right' : True
}
def_minortickprops_boxed = {
'length' : (ticklength/1.75)-1.25,
'width' : axwidth/1.75,
'axis' : 'both',
'direction' : 'in',
'which' : 'minor',
'colors' : textcolor
}
def_axprops_ppt = {
'linewidth' : 2 * axwidth,
'linestyle' : '-',
'color' : textcolor
}
def_tickprops_ppt = {
'length' : ticklength,
'width' : axwidth,
'pad' : tickpad,
'axis' : 'both',
'direction' : 'out',
'colors' : textcolor,
'bottom' : True,
'left' : True,
'top' : False,
'right' : False
}
def_minortickprops_ppt = {
'length' : ticklength-1.25,
'width' : axwidth,
'axis' : 'both',
'direction' : 'out',
'which' : 'minor',
'colors' : textcolor
}
singlevartypes = ['hist', 'kde', 'violin']
############# PLOTTING FUNCTIONS #############
def plot(**pdata):
""" Generic plotting routine. Sets basic options then passes parameters to detailed plotting functions. """
# Sanity checks
ndata = 0
assert 'ax' not in pdata or 'save' not in pdata, 'Attempted to save the figure, but the axis has been supplied manually!'
assert ('x' in pdata or 'y' in pdata), 'No data passed to plot!'
if 'x' in pdata and 'y' in pdata:
ndata = len(np.array(pdata['x']).shape)
assert ndata==len(np.array(pdata['y']).shape), 'x (dimension %d) and y (dimension %d) have mismatched shapes!' % (ndata, len(np.array(pdata['y']).shape))
if ndata==1 and not ('type' in pdata and pdata['type']=='circos') and len(np.array(pdata['x'][0]))==1:
pdata['x'] = [pdata['x']]
pdata['y'] = [pdata['y']]
elif 'x' in pdata and 'y' not in pdata:
ndata = len(np.array(pdata['x']).shape)
assert pdata['type'] in singlevartypes, 'Only one set of values passed, but plot type (%s) requires two sets of values to plot!' % pdata['type']
if ndata==1 and len(np.array(pdata['x'][0]))==1: pdata['x'] = [pdata['x']]
elif 'y' in pdata and 'x' not in pdata:
ndata = len(np.array(pdata['y']).shape)
assert pdata['type'] in singlevartypes, 'Only one set of values passed, but plot type (%s) requires two sets of values to plot!' % pdata['type']
pdata['x'] = [k for k in pdata['y']]
pdata['y'] = []
if ndata==1 and len(np.array(pdata['x'][0]))==1: pdata['x'] = [pdata['x']]
if 'colors' not in pdata: assert len(pdata['x'])<9, 'No colors provided, but the number of elements to be plotted (%d) is >8, maximum number of default colors!' % len(pdata['x'])
# If no axis is passed, create the axis
fig = 0
if 'ax' not in pdata:
if 'aspect' not in pdata and 'dims' not in pdata:
fig = plt.figure(figsize=(aspect * plotwidth, plotwidth))
pdata['ax'] = plt.subplot(111)
elif 'aspect' in pdata:
fig = plt.figure(figsize=(pdata['aspect'] * plotwidth, plotwidth))
pdata['ax'] = plt.subplot(111)
elif 'dims' in pdata:
fig = plt.figure(figsize=(pdata['dims'][0], pdata['dims'][1]))
pdata['ax'] = plt.subplot(111)
# Fill style parameters if not passed in pdata
if 'theme' not in pdata: pdata['theme'] = 'open'
if 'type' not in pdata: pdata['type'] = 'scatter'
if 'ticklabelprops' not in pdata: pdata['ticklabelprops'] = def_ticklabelprops
if 'axprops' not in pdata:
if 'ppt' in pdata and pdata['ppt']: pdata['axprops'] = def_axprops_ppt
else: pdata['axprops'] = def_axprops
if 'tickprops' not in pdata:
if 'ppt' in pdata and pdata['ppt']: pdata['tickprops'] = def_tickprops_ppt
elif pdata['theme']=='boxed': pdata['tickprops'] = def_tickprops_boxed
else: pdata['tickprops'] = def_tickprops
if 'minortickprops' not in pdata:
if 'ppt' in pdata and pdata['ppt']: pdata['minortickprops'] = def_minortickprops_ppt
elif pdata['theme']=='boxed': pdata['minortickprops'] = def_minortickprops_boxed
else: pdata['minortickprops'] = def_minortickprops
if 'labelprops' not in pdata: pdata['labelprops'] = def_labelprops
if 'sublabelprops' not in pdata and 'sublabel' in pdata: pdata['sublabelprops'] = def_sublabelprops
if 'sublabelcoords' not in pdata and 'sublabel' in pdata: pdata['sublabelcoords'] = [sublabelx, sublabely]
if 'figprops' not in pdata and 'save' in pdata: pdata['figprops'] = def_figprops
if 'legendprops' not in pdata and 'legend' in pdata: pdata['legendprops'] = def_legendprops
if 'colors' not in pdata:
if len(pdata['x'])==1: pdata['colors'] = [defplotcolor]
elif len(pdata['x'])==2: pdata['colors'] = [k for k in defpaircolor]
else: pdata['colors'] = [k for k in blues[len(pdata['x'])]]
if 'plotprops' not in pdata:
if pdata['type']=='scatter': pdata['plotprops'] = def_scatterprops
if pdata['type']=='error': pdata['plotprops'] = def_errorprops
if pdata['type']=='line': pdata['plotprops'] = def_lineprops
if pdata['type']=='fill': pdata['plotprops'] = def_fillprops
if pdata['type']=='hist': pdata['plotprops'] = def_histprops
if pdata['type']=='bar': pdata['plotprops'] = def_barprops
if pdata['type']=='kde': pdata['plotprops'] = def_lineprops
if pdata['type']=='circos': pdata['plotprops'] = def_lineprops
if pdata['type']=='violin': pdata['plotprops'] = def_violinprops
if pdata['type']=='hexbin': pdata['plotprops'] = def_hexbinprops
if pdata['type']=='contour': pdata['plotprops'] = def_contourprops
# Fill in x axis limits and ticks if not passed in pdata
if pdata['type']=='circos' and 'xticks' not in pdata: pdata['xticks'] = []
if pdata['type']=='circos' and 'yticks' not in pdata: pdata['yticks'] = []
if 'xlim' not in pdata: pdata['xlim'] = [np.min([np.min(x) for x in pdata['x']]), np.max([np.max(x) for x in pdata['x']])]
if 'xticks' not in pdata:
xtick, xminortick = [], []
if 'logx' in pdata and pdata['logx']: xtick, xminortick = getlogticks(pdata['xlim'])
else: xtick, xminortick = getticks(pdata['xlim'])
pdata['xticks'] = xtick
if 'xminorticks' not in pdata: pdata['xminorticks'] = xminortick
if 'xminorticks' not in pdata: pdata['xminorticks'] = []
if 'bins' not in pdata and pdata['type']=='hist':
width = (pdata['xlim'][1]-pdata['xlim'][0])/nbins
bins = np.arange(pdata['xlim'][0], pdata['xlim'][1]+width, width)
pdata['bins'] = bins
if 'combine' not in pdata and pdata['type']=='hist': pdata['combine'] = False
# Fill in y axis limits and ticks
if 'ylim' not in pdata and pdata['type'] not in singlevartypes:
pdata['ylim'] = [np.min([np.min(y) for y in pdata['y']]), np.max([np.max(y) for y in pdata['y']])]
elif 'ylim' not in pdata:
ymin = 1.0
ymax = 0.0
if pdata['type']=='hist':
for i in range(len(pdata['x'])):
w = np.ones_like(pdata['x'][i])/float(len(pdata['x'][i]))
h, bin_edges = np.histogram(pdata['x'][i], weights=w, range=pdata['xlim'], bins=pdata['bins'])
if np.min(h)<ymin: ymin = np.min(h)
if np.max(h)>ymax: ymax = np.max(h)
elif pdata['type']=='kde':
for i in range(len(pdata['x'])):
ypdf = gaussian_kde(pdata['x'][i], bw_method='silverman')
x = np.linspace(np.min(pdata['xticks']), np.max(pdata['xticks']), 300)
if np.min(ypdf(x))<ymin: ymin = np.min(ypdf(x))
if np.max(ypdf(x))>ymax: ymax = np.max(ypdf(x))
elif pdata['type']=='violin':
ymax = len(pdata['x'])
if 'positions' in pdata:
ymin = np.min(pdata['positions'])
ymax = np.max(pdata['positions'])
pdata['ylim'] = [ymin, ymax]
if 'yticks' not in pdata:
ytick, yminortick = [], []
if 'logy' in pdata and pdata['logy']: ytick, yminortick = getlogticks(pdata['ylim'])
else: ytick, yminortick = getticks(pdata['ylim'])
pdata['yticks'] = ytick
if 'yminorticks' not in pdata: pdata['yminorticks'] = yminortick
if 'yminorticks' not in pdata: pdata['yminorticks'] = []
if pdata['type']=='fill' and 'y2' not in pdata: pdata['y2']=0
# Sanity check for ticks and log scale
if 'logx' in pdata and pdata['logx']:
assert pdata['xlim'][0]>0, 'Attempting to plot x on a log scale, but the lower limit (%lf) is <= 0!' % pdata['xlim'][0]
if 'xticks' not in pdata:
xtick, xminortick = getlogticks(pdata['xlim'])
pdata['xticks'] = xtick
if 'xminorticks' not in pdata: pdata['xminorticks'] = xminortick
else: pdata['logx'] = False
if 'logy' in pdata and pdata['logy'] and pdata['type'] not in singlevartypes:
assert pdata['ylim'][0]>0, 'Attempting to plot y on a log scale, but the lower limit (%lf) is <= 0!' % pdata['ylim'][0]
if 'yticks' not in pdata:
ytick, yminortick = getlogticks(pdata['ylim'])
pdata['yticks'] = ytick
if 'yminorticks' not in pdata: pdata['yminorticks'] = yminortick
else: pdata['logy'] = False
# Make plot
if pdata['type']=='scatter': scatter(**pdata)
elif pdata['type']=='error': error(**pdata)
elif pdata['type']=='line': line(**pdata)
elif pdata['type']=='fill': fill(**pdata)
elif pdata['type']=='hist': hist(**pdata)
elif pdata['type']=='bar': bar(**pdata)
elif pdata['type']=='kde': kde(**pdata)
elif pdata['type']=='circos': circos(**pdata)
elif pdata['type']=='violin': violin(**pdata)
elif pdata['type']=='hexbin': hexbin(**pdata)
elif pdata['type']=='contour': contour(**pdata)
# Set plot appearance and plot axes
if ('orientation' in pdata['plotprops']) and (pdata['plotprops']['orientation']=='horizontal'):
temp = [k for k in pdata['xlim']]
pdata['xlim'] = [k for k in pdata['ylim']]
pdata['ylim'] = [k for k in temp]
temp = [k for k in pdata['xticks']]
pdata['xticks'] = [k for k in pdata['yticks']]
pdata['yticks'] = [k for k in temp]
temp = [k for k in pdata['xminorticks']]
pdata['xminorticks'] = [k for k in pdata['yminorticks']]
pdata['yminorticks'] = [k for k in temp]
# if pdata['theme']=='open':
# adjustlim(pdata['xlim'], logscale=pdata['logx'])
# adjustlim(pdata['ylim'], logscale=pdata['logy'])
if 'nudgex' in pdata: pdata['xlim'][1] *= pdata['nudgex']
if 'nudgey' in pdata: pdata['ylim'][1] *= pdata['nudgey']
setappearance(**pdata)
# Save
if 'save' in pdata:
plt.savefig(pdata['save']+'.pdf', **pdata['figprops'])
plt.close(fig)
def scatter(**pdata):
""" Generic scatter plot. """
# Plot data
hollowprops = pdata['plotprops'].copy()
hollowprops['lw'] = 1
hollowprops['facecolor'] = 'none'
for i in range(len(pdata['x'])):
x = pdata['x'][i]
y = pdata['y'][i]
if 'facecolor' in pdata and pdata['facecolor'][i] and 'edgecolor' in pdata and pdata['edgecolor'][i]:
cf = pdata['facecolor'][i]
ce = pdata['edgecolor'][i]
if 'hollow' in pdata and pdata['hollow'][i]: pdata['ax'].scatter(x, y, edgecolor=ce, **hollowprops)
else: pdata['ax'].scatter(x, y, facecolor=cf, edgecolor=ce, **pdata['plotprops'])
elif 'colors' in pdata and pdata['colors'][i]:
c = pdata['colors'][i]
if 'hollow' in pdata and pdata['hollow'][i]: pdata['ax'].scatter(x, y, edgecolor=c, **hollowprops)
else: pdata['ax'].scatter(x, y, facecolor=c, edgecolor=c, **pdata['plotprops'])
else:
c = defcolor
if 'hollow' in pdata and pdata['hollow'][i]: pdata['ax'].scatter(x, y, edgecolor=c, **hollowprops)
else: pdata['ax'].scatter(x, y, facecolor=c, edgecolor=c, **pdata['plotprops'])
# Make legend (optional)
if 'legend' in pdata:
x = [10 * pdata['xlim'][1]]
y = [10 * pdata['ylim'][1]]
for i in range(len(pdata['legend'])):
if 'facecolor' in pdata and pdata['facecolor'][i] and 'edgecolor' in pdata and pdata['edgecolor'][i]:
cf = pdata['facecolor'][i]
ce = pdata['edgecolor'][i]
l = pdata['legend'][i]
if 'hollow' in pdata and pdata['hollow'][i]: pdata['ax'].scatter(x, y, edgecolor=ce, label=l, zorder=len(pdata['x'])-i+10, **hollowprops)
else: pdata['ax'].scatter(x, y, facecolor=cf, edgecolor=ce, label=l, zorder=len(pdata['x'])-i+10, **pdata['plotprops'])
else:
c = defcolor
if 'colors' in pdata and pdata['colors'][i]: c = pdata['colors'][i]
l = pdata['legend'][i]
if 'hollow' in pdata and pdata['hollow'][i]: pdata['ax'].scatter(x, y, edgecolor=c, label=l, zorder=len(pdata['x'])-i+10, **hollowprops)
else: pdata['ax'].scatter(x, y, facecolor=c, edgecolor=c, label=l, zorder=len(pdata['x'])-i+10, **pdata['plotprops'])
l = pdata['ax'].legend(**pdata['legendprops'])
for text in l.get_texts(): text.set_color(textcolor)
#for text in l.get_texts(): text.set_size(sizelabel)
def error(**pdata):
""" Generic errorbar plot. """
# Plot data
hollowprops = pdata['plotprops'].copy()
hollowprops['mew'] = 1
hollowprops['mfc'] = 'none'
for i in range(len(pdata['x'])):
x = pdata['x'][i]
y = pdata['y'][i]
xerr = None
yerr = None
if 'xerr' in pdata and np.any(pdata['xerr']) and np.any(pdata['xerr'][i]): xerr = pdata['xerr'][i]
if 'yerr' in pdata and np.any(pdata['yerr']) and np.any(pdata['yerr'][i]): yerr = pdata['yerr'][i]
if 'facecolor' in pdata and pdata['facecolor'][i] and 'edgecolor' in pdata and pdata['edgecolor'][i]:
cf = pdata['facecolor'][i]
ce = pdata['edgecolor'][i]
if 'hollow' in pdata and pdata['hollow'][i]: pdata['ax'].errorbar(x, y, xerr=xerr, yerr=yerr, mec=ce, color=ce, zorder=len(pdata['x'])-i+10, **hollowprops)
else: pdata['ax'].errorbar(x, y, xerr=xerr, yerr=yerr, mfc=cf, mec=ce, color=ce, zorder=len(pdata['x'])-i+10, **pdata['plotprops'])
elif 'colors' in pdata and pdata['colors'][i]:
c = pdata['colors'][i]
if 'hollow' in pdata and pdata['hollow'][i]: pdata['ax'].errorbar(x, y, xerr=xerr, yerr=yerr, mec=c, color=c, zorder=len(pdata['x'])-i+10, **hollowprops)
else: pdata['ax'].errorbar(x, y, xerr=xerr, yerr=yerr, mfc=c, mec=c, color=c, zorder=len(pdata['x'])-i+10, **pdata['plotprops'])
else:
c = defcolor
if 'hollow' in pdata and pdata['hollow'][i]: pdata['ax'].errorbar(x, y, xerr=xerr, yerr=yerr, mec=c, color=c, zorder=len(pdata['x'])-i+10, **hollowprops)
else: pdata['ax'].errorbar(x, y, xerr=xerr, yerr=yerr, mfc=c, mec=c, color=c, zorder=len(pdata['x'])-i+10, **pdata['plotprops'])
# for i in range(len(pdata['x'])):
# c = pdata['colors'][i]
# x = pdata['x'][i]
# y = pdata['y'][i]
#
# if 'xerr' in pdata:
# if 'yerr' in pdata: pdata['ax'].errorbar(x, y, xerr=pdata['xerr'][i], yerr=pdata['yerr'][i], c=c, mfc=c, mec=c, zorder=len(pdata['x'])-i+10, **pdata['plotprops'])
# else: pdata['ax'].errorbar(x, y, xerr=pdata['xerr'][i], c=c, mfc=c, mec=c, zorder=len(pdata['x'])-i+10, **pdata['plotprops'])
# elif 'yerr' in pdata: pdata['ax'].errorbar(x, y, yerr=pdata['yerr'][i], c=c, mfc=c, mec=c, zorder=len(pdata['x'])-i+10, **pdata['plotprops'])
# else: pdata['ax'].errorbar(x, y, c=c, mfc=c, mec=c, zorder=len(pdata['x'])-i+10, **pdata['plotprops'])
# Make legend (optional)
if 'legend' in pdata:
x = [10 * pdata['xlim'][1]]
y = [10 * pdata['ylim'][1]]
for i in range(len(pdata['legend'])):
c = pdata['colors'][i]
l = pdata['legend'][i]
pdata['ax'].scatter(x, y, facecolor=c, edgecolor=c, label=l, **def_scatterprops)
l = pdata['ax'].legend(**pdata['legendprops'])
for text in l.get_texts(): text.set_color(textcolor)
def line(**pdata):
""" Generic line plot. """
# Plot data
for i in range(len(pdata['x'])):
c = pdata['colors'][i]
x = pdata['x'][i]
y = pdata['y'][i]
if 'zorder' not in pdata['plotprops']: pdata['ax'].plot(x, y, color=c, zorder=len(pdata['x'])-i, **pdata['plotprops'])
else: pdata['ax'].plot(x, y, color=c, **pdata['plotprops'])
# if 'legend' in pdata:
# pdata['ax'].plot(x, y, color=c, zorder=len(pdata['x'])-i, label=pdata['legend'][i], **pdata['plotprops'])
#
# else:
# pdata['ax'].plot(x, y, color=c, zorder=len(pdata['x'])-i, **pdata['plotprops'])
# Make legend (optional)
if 'legend' in pdata:# and 'plotlegend' in pdata:
x = [10 * pdata['xlim'][1], 10 * pdata['xlim'][1]]
y = [10 * pdata['ylim'][1], 10 * pdata['ylim'][1]]
for i in range(len(pdata['legend'])):
c = pdata['colors'][i]
l = pdata['legend'][i]
pdata['ax'].plot(x, y, color=c, label=l, **pdata['plotprops'])
l = pdata['ax'].legend(**pdata['legendprops'])
for text in l.get_texts(): text.set_color(textcolor)
def fill(**pdata):
""" Generic filled line plot. """
# Plot data
for i in range(len(pdata['x'])):
c = pdata['colors'][i]
x = pdata['x'][i]
y = pdata['y'][i]
if 'zorder' not in pdata['plotprops']: pdata['ax'].fill_between(x, y, color=c, zorder=len(pdata['x'])-i, **pdata['plotprops'])
else: pdata['ax'].fill_between(x, y, color=c **pdata['plotprops'])
# Make legend (optional)
if 'legend' in pdata:# and 'plotlegend' in pdata:
x = [10 * pdata['xlim'][1], 10 * pdata['xlim'][1]]
y = [10 * pdata['ylim'][1], 10 * pdata['ylim'][1]]
for i in range(len(pdata['legend'])):
c = pdata['colors'][i]
l = pdata['legend'][i]
pdata['ax'].plot(x, y, color=c, label=l, **pdata['plotprops'])
l = pdata['ax'].legend(**pdata['legendprops'])
for text in l.get_texts(): text.set_color(textcolor)
def hist(**pdata):
""" Generic histogram. """
# Plot data
if pdata['combine']: n, bins, patches = pdata['ax'].hist(pdata['x'], weights=[np.ones_like(x)/float(len(x)) for x in pdata['x']], color=pdata['colors'], bins=pdata['bins'], **pdata['plotprops'])
else:
for i in range(len(pdata['x'])):
c = pdata['colors'][i]
x = pdata['x'][i]
w = np.ones_like(x)/float(len(x))
if 'weights' in pdata: w = pdata['weights'][i]
if 'percent' in pdata and pdata['percent']: w *= 100.0
n, bins, patches = pdata['ax'].hist(x, weights=w, facecolor=c, zorder=len(pdata['x'])-i, bins=pdata['bins'], range=(pdata['xlim'][0], pdata['xlim'][1]), **pdata['plotprops'])
for patch in patches: patch.set_facecolor(c)
# Make legend (optional)
if 'legend' in pdata:
x = [10 * pdata['xlim'][1], 10 * pdata['xlim'][1]]
y = [10 * pdata['ylim'][1], 10 * pdata['ylim'][1]]
for i in range(len(pdata['legend'])):
c = pdata['colors'][i]
l = pdata['legend'][i]
pdata['ax'].scatter(x, y, facecolor=c, edgecolor=c, label=l, **def_scatterprops)
l = pdata['ax'].legend(**pdata['legendprops'])
for text in l.get_texts(): text.set_color(textcolor)
# Annotate (optional)
if 'annotate' in pdata:
for i in range(len(pdata['annotate'])):
pdata['ax'].text(pdata['annotate'][i][0], pdata['annotate'][i][1], pdata['annotate'][i][2], **pdata['ticklabelprops'])
def bar(**pdata):
""" Generic bar graph. """
# Check alignment
isHorizontal = False
if pdata['plotprops']['orientation'] and pdata['plotprops']['orientation']=='horizontal':
isHorizontal = True
if 'width' in pdata['plotprops']:
pdata['plotprops']['height'] = pdata['plotprops']['width']
del pdata['plotprops']['width']
del pdata['plotprops']['orientation']
else: pdata['plotprops']['orientation'] = 'vertical'
# Plot data
for i in range(len(pdata['x'])):
c = pdata['colors'][i]
x = pdata['x'][i]
y = pdata['y'][i]
xerr = None
yerr = None
err_kw = {}
if 'xerr' in pdata and np.any(pdata['xerr']) and np.any(pdata['xerr'][i]): xerr = pdata['xerr'][i]
if 'yerr' in pdata and np.any(pdata['yerr']) and np.any(pdata['yerr'][i]): yerr = pdata['yerr'][i]
if np.any(xerr) or np.any(yerr): err_kw = { 'ecolor' : defcolor, 'capsize' : 0 }
if isHorizontal: pdata['ax'].barh(x, y, xerr=xerr, yerr=yerr, color=c, zorder=len(pdata['x'])-1-i, error_kw=err_kw, **pdata['plotprops'])
else: pdata['ax'].bar( x, y, xerr=xerr, yerr=yerr, color=c, zorder=len(pdata['x'])-1-i, error_kw=err_kw, **pdata['plotprops'])
# Make legend (optional)
if 'legend' in pdata:
x = [10 * pdata['xlim'][1], 10 * pdata['xlim'][1]]
y = [10 * pdata['ylim'][1], 10 * pdata['ylim'][1]]
for i in range(len(pdata['legend'])):
c = pdata['colors'][i]
l = pdata['legend'][i]
pdata['ax'].scatter(x, y, facecolor=c, edgecolor=c, label=l, **def_scatterprops)
l = pdata['ax'].legend(**pdata['legendprops'])
for text in l.get_texts(): text.set_color(textcolor)
# Annotate (optional)
if 'annotate' in pdata:
for i in range(len(pdata['annotate'])):
pdata['ax'].text(pdata['annotate'][i][0], pdata['annotate'][i][1], pdata['annotate'][i][2], **pdata['ticklabelprops'])
if isHorizontal: pdata['plotprops']['orientation'] = 'horizontal'
def kde(**pdata):
""" Generic kde-smoothed plot. """
# Plot data
for i in range(len(pdata['x'])):
c = pdata['colors'][i]
y = pdata['x'][i]
ypdf = gaussian_kde(y, bw_method='silverman')
x = np.linspace(np.min(pdata['xticks']), np.max(pdata['xticks']), 300)
pdata['ax'].plot(x, ypdf(x), color=c, zorder=len(pdata['x'])-i, **pdata['plotprops'])
# Make legend (optional)
if 'legend' in pdata:
x = [10 * pdata['xlim'][1], 10 * pdata['xlim'][1]]
y = [10 * pdata['ylim'][1], 10 * pdata['ylim'][1]]
for i in range(len(pdata['legend'])):
c = pdata['colors'][i]
l = pdata['legend'][i]
pdata['ax'].plot(x, y, color=c, label=l, **pdata['plotprops'])
l = pdata['ax'].legend(**pdata['legendprops'])
for text in l.get_texts(): text.set_color(textcolor)
def circos(**pdata):
""" Generic circos-style plot. """
# Generate Bezier curves using index to angle map
if 't' not in pdata:
pdata['t'] = np.arange(0., 1.01, 0.01)
if 'rad' not in pdata:
pdata['rad'] = [[0.8, 0.8] for i in range(len(pdata['x']))]
if 'size' not in pdata:
pdata['size'] = float(np.max([np.max(pdata['x']), np.max(pdata['y'])]))
if 'bezrad' not in pdata:
pdata['bezrad'] = 0.
if not hasattr(pdata['bezrad'], '__len__'):
temp = pdata['bezrad']
pdata['bezrad'] = [temp for i in range(len(pdata['rad']))]
if 'angle' not in pdata:
pdata['angle'] = [[-2 * np.pi * pdata['x'][i] / pdata['size'], -2 * np.pi * pdata['y'][i] / pdata['size']] for i in range(len(pdata['x']))]
cpolar = bezier(pdata['rad'], pdata['angle'], pdata['t'], pdata['bezrad'])
# Plot data
for i in range(len(pdata['x'])):
c = pdata['colors'][i]
x = cpolar[i][0]
y = cpolar[i][1]
if 'arcprops' in pdata: pdata['ax'].plot(x, y, color=c, zorder=len(pdata['x'])-i, **pdata['arcprops'][i])
else: pdata['ax'].plot(x, y, color=c, zorder=len(pdata['x'])-i, **pdata['plotprops'])
# Add labels (optional)
if 'ticklabels' in pdata:
for tl in pdata['ticklabels']:
t = -2 * np.pi * tl[0] / pdata['size']
r = 0.85
l = tl[0]
if len(tl)>1: r = tl[1]
if len(tl)>2: l = tl[2]
if t>-np.pi/2. or t<-3.*np.pi/2.: pdata['ax'].text(r * np.cos(t), r * np.sin(t), l, rotation_mode='anchor', rotation=rad2deg(t), ha='left', va='center', **pdata['ticklabelprops'])
else: pdata['ax'].text(r * np.cos(t), r * np.sin(t), l, rotation_mode='anchor', rotation=rad2deg(t)+180., ha='right', va='center', **pdata['ticklabelprops'])
if 'textlabels' in pdata:
for tl in pdata['textlabels']:
t = -2 * np.pi * tl[0] / pdata['size']
r = tl[1]
l = tl[2]
if t>-np.pi/2. or t<-3.*np.pi/2.: pdata['ax'].text(r * np.cos(t), r * np.sin(t), l, rotation_mode='anchor', rotation=rad2deg(t), ha='left', va='center', **pdata['labelprops'])
else: pdata['ax'].text(r * np.cos(t), r * np.sin(t), l, rotation_mode='anchor', rotation=rad2deg(t)+180., ha='right', va='center', **pdata['labelprops'])
# Make legend (optional)
if 'legend' in pdata:
x = [10 * pdata['xlim'][1], 10 * pdata['xlim'][1]]
y = [10 * pdata['ylim'][1], 10 * pdata['ylim'][1]]
for i in range(len(pdata['legend'])):
c = pdata['colors'][i]
l = pdata['legend'][i]
pdata['ax'].plot(x, y, color=c, label=l, **pdata['plotprops'])
l = pdata['ax'].legend(**pdata['legendprops'])
for text in l.get_texts(): text.set_color(textcolor)
#for text in l.get_texts(): text.set_size(sizelabel+1)
def violin(**pdata):
""" Generic violin plot. """
# Plot data
for i in range(len(pdata['x'])):
x = pdata['x'][i]
pos = [i+1]
if 'positions' in pdata: pos = pdata['positions'][i]
#print(pos)
#print(len(x))
#vp = pdata['ax'].violinplot(x, **pdata['plotprops'])
vp = pdata['ax'].violinplot(x, positions=pos, **pdata['plotprops'])
# Adjust appearance
c = defcolor
fc = defcolor
ec = defcolor
if 'colors' in pdata:
c = pdata['colors'][i]
fc = pdata['colors'][i]
ec = pdata['colors'][i]
if 'facecolor' in pdata:
fc = pdata['facecolor'][i]
if 'edgecolor' in pdata:
fc = pdata['edgecolor'][i]
for body in vp['bodies']:
body.set_facecolor(fc)
body.set_edgecolor(ec)
body.set_linewidth(axwidth)
showLines = ['cmins', 'cmaxes', 'cmeans', 'cmedians']
hideLines = ['cbars']
for line in [vp[l] for l in showLines if l in vp]:
line.set_color(c)
line.set_linewidth(axwidth)
for line in [vp[l] for l in hideLines if l in vp]:
line.set_linewidth(0)
# Make legend (optional)
if 'legend' in pdata:
x = [10 * pdata['xlim'][1], 10 * pdata['xlim'][1]]
y = [10 * pdata['ylim'][1], 10 * pdata['ylim'][1]]
for i in range(len(pdata['legend'])):
c = pdata['colors'][i]
l = pdata['legend'][i]
pdata['ax'].plot(x, y, color=c, label=l, **pdata['plotprops'])
l = pdata['ax'].legend(**pdata['legendprops'])
for text in l.get_texts(): text.set_color(textcolor)
def hexbin(**pdata):
""" 2D histogram with hexagonal bins. """
# Plot data
for i in range(len(pdata['x'])):
x = pdata['x'][i]
y = pdata['y'][i]
hb = pdata['ax'].hexbin(x, y, **pdata['plotprops'])
# Annotate (optional)
if 'annotate' in pdata:
for i in range(len(pdata['annotate'])):
pdata['ax'].text(pdata['annotate'][i][0], pdata['annotate'][i][1], pdata['annotate'][i][2], **pdata['ticklabelprops'])
def contour(**pdata):
""" Generic contour plot. """
# Sort out contour shading plot props from line props
cShade = ['cmap', 'hatches']
cLine = ['linewidths', 'linestyles']
# Plot data
for i in range(len(pdata['x'])):
x = pdata['x'][i]
y = pdata['y'][i]
z = pdata['z'][i]
tempprops = deepcopy(pdata['plotprops'])
for prop in cLine:
if prop in tempprops: del tempprops[prop]
if 'colors' in tempprops and 'cmap' in tempprops: del tempprops['colors']
pdata['ax'].contourf(x, y, z, **tempprops)
tempprops = deepcopy(pdata['plotprops'])
for prop in cShade:
if prop in tempprops: del tempprops[prop]
pdata['ax'].contour(x, y, z, **tempprops)
# Annotate (optional)
if 'annotate' in pdata:
for i in range(len(pdata['annotate'])):
pdata['ax'].text(pdata['annotate'][i][0], pdata['annotate'][i][1], pdata['annotate'][i][2], **pdata['ticklabelprops'])
def setappearance(**pdata):
""" Set out general plot appearance (axis labels, tick parameters, etc). """
# Make axis invisible
if 'noaxes' in pdata and pdata['noaxes']:
for axis in ['left', 'right', 'bottom', 'top']: pdata['ax'].spines[axis].set_visible(False)
elif pdata['theme']=='boxed':
for axis in ['left', 'right', 'bottom', 'top']: pdata['ax'].spines[axis].set_visible(True)
elif pdata['theme']=='open':
for axis in ['top', 'right']: pdata['ax'].spines[axis].set_visible(False)
for axis in ['bottom', 'left']: pdata['ax'].spines[axis].set_visible(True)
if 'hide' in pdata:
for axis in pdata['hide']: pdata['ax'].spines[axis].set_visible(False)
if 'show' in pdata:
for axis in pdata['show']: pdata['ax'].spines[axis].set_visible(True)
# Add labels
if 'xlabel' in pdata: pdata['ax'].set_xlabel(pdata['xlabel'], **pdata['labelprops'])
if 'ylabel' in pdata: pdata['ax'].set_ylabel(pdata['ylabel'], **pdata['labelprops'])
if 'sublabel' in pdata: