-
Notifications
You must be signed in to change notification settings - Fork 0
/
pretty_plot.py
1783 lines (1611 loc) · 65.8 KB
/
pretty_plot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# simply plotting suite
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import networkx as nx
import mpl_toolkits.axisartist.floating_axes as floating_axes
from matplotlib.projections import PolarAxes
import pandas as pd
import seaborn as sns
sns.set_style('white')
import matplotlib as mpl
import scipy.stats as stats
########################################################################
# Helper functions
########################################################################
def lims(V):
# get upper and lower bounds on a LIST OF LISTS (or matrix) D=2
# returns min, max
mi, ma = np.inf, 0
for m in V:
for n in m:
if n > ma:
ma = n
if n < mi:
mi = n
return mi, ma
def condition_by_name(labels, arr, arr2=None, arr3=None):
# sort by common labels in order so same types show up next to one another
unique_labels = np.unique([i for i in labels])
order = []
for i in unique_labels:
for x in range(len(labels)):
if labels[x] == i:
order.append(x)
new_labels = [labels[j] for j in order]
new_arr = [arr[j] for j in order]
if arr2:
new_arr2 = [arr2[j] for j in order]
if arr3:
new_arr3 = [arr3[j] for j in order]
return new_labels, new_arr, new_arr2, new_arr3
if arr2:
return new_labels, new_arr, new_arr2
return new_labels, new_arr
def group_by_name(labels, arr, metric='mean'):
# Group data by name for bar/summary plotting, metric=('mean','median')
llist = list(np.unique(labels))
vals = {}
for l in range(len(labels)):
if labels[l] not in vals.keys():
vals[labels[l]] = []
if metric == 'mean':
vals[labels[l]].append(np.mean(arr[l]))
elif metric == 'median':
vals[labels[l]].append(np.median(arr[l]))
lab_data, arr_data = [k for k in vals.keys()], [np.mean(d) for d in vals.values()]
return lab_data, arr_data, [np.std(d) for d in vals.values()]
def rm_nan(vec):
# Remove nans (generated by illegally conditioned angles fed to cos-1)
return [i for i in vec if str(i) != 'nan']
def dict_summary(obj):
"""
Print a summary of the object values in a dictionary. Only works for
dicts of keys=['files','cellTypes','obj1, 'obj2', ...]
"""
grouplist = list(set(obj['cellTypes']))
for k in obj.keys():
if k != 'files' and k != 'cellTypes': # Don't do this for files/types
print('Property: %s' %k)
groups = [[] for i in grouplist] # New group for each key
for samp in range(len(obj[k])):
groups[grouplist.index(obj['cellTypes'][samp])].append(obj[k][samp])
# Now print group stats for each group
ind_vars = []
for g in range(len(groups)):
ind_means = [np.mean(i) for i in groups[g]]
ind_meds = [np.median(i) for i in groups[g]]
ind_std = [np.std(i) for i in groups[g]]
for sub in groups[g]:
ind_vars.append(np.var(sub))
ind_qs = [[np.percentile(i,25), np.percentile(i,75)]
for i in groups[g]]
ic = np.var(ind_means)**2 / \
(np.var(ind_means)**2 + sum([np.var(i) for i in groups[g]])**2)
print('For %i %s objects' %(len(groups[g]), grouplist[g]))
print('Mean: %.5f +/- %.5f, Median: %.5f'
%(np.mean(ind_means), np.mean(ind_std), np.mean(ind_meds)))
print('Means +/- std Median IQR (25th - 75th):')
for u in range(len(groups[g])):
print('%.5f +/- %.5f %.5f (%.5f - %.5f)'
%(ind_means[u], ind_std[u], ind_meds[u], ind_qs[u][0], ind_qs[u][1]))
print('Intraclass correlation: %.5f' %ic)
g_means = []
for g in groups:
g_means.append(np.mean([np.mean(i) for i in g]))
master_ic = np.var(g_means)**2 / \
(np.var(g_means)**2 + sum(ind_vars)**2)
print('Master intraclass correlation: %.5f' %master_ic)
return
#group_means = [np.mean(k) for k in v_means] # group_means are the master means (only 4)
#master_ic = np.var(group_means)**2 / \
# (np.var(group_means)**2 + sum([np.var(i) for i in v_means])**2)
def pyplot_defaults():
""" After calling pandas or seaborn, the default plt can be messed up.
If this causes inconsistencies, can call this to revert back to defaults. """
mpl.rcParams.update(mpl.rcParamsDefault)
return
########################################################################
# Basic plots: box bar, scatter (multi-dimensional plots next section)
########################################################################
def pretty_boxplot(V, labelsin, title=None, ticks=None, axes=None):
"""
V is a matrix of arrays to be plotted; labels must be same length.
labels = ['PD', 'LG' ...], ticks = ['791_233', ...]
ticks=False to omit x-ticks altogether; None for legend=ticks
"""
# mi, ma = lims(V)
L = list(np.unique(labelsin))
C = [L.index(i) for i in labelsin]
fcolors = ['darkkhaki', 'royalblue', 'forestgreen','lavenderblush']
# plotting
fig = plt.figure()
ax = fig.add_subplot(111)
if ticks:
box = ax.boxplot(V, labels=ticks, showmeans=True, notch=True,
patch_artist=True)
#ax.set_xticks([i-1 for i in range(len(ticks))])
#ax.set_xticklabels(ticks, rotation=45) # rotate ticks
elif ticks is None:
box = ax.boxplot(V, labels=[' ' for i in range(len(labelsin))],
showmeans=True, notch=True, patch_artist=True,
showfliers=False)
else:
box = ax.boxplot(V, labels=labelsin, showmeans=True, notch=True,
patch_artist=True, showfliers=False)
for patch, color in zip(box['boxes'], [fcolors[i] for i in C]):
patch.set_facecolor(color)
# set y axis range
# ax.set_ylim([mi, ma])
# legend
khaki_patch = mpatches.Patch(color='darkkhaki',
label=labelsin[C.index(fcolors.index('darkkhaki'))])
royal_patch = mpatches.Patch(color='royalblue',
label=labelsin[C.index(fcolors.index('royalblue'))])
forest_patch = mpatches.Patch(color='forestgreen',
label=labelsin[C.index(fcolors.index('forestgreen'))])
lavender_patch = mpatches.Patch(color='lavenderblush',
label=labelsin[C.index(fcolors.index('lavenderblush'))])
plt.legend(handles=[khaki_patch, royal_patch, forest_patch, lavender_patch])
# titles
if axes:
ax.set_xlabel(axes[0], fontsize=15)
ax.set_ylabel(axes[1], fontsize=15)
ax.set_title(title, fontsize=20)
plt.show()
return
def mean_scatter(V, labelsin, title=None, ticks=None, axes=None,
showboth=True, showleg='best'):
"""
One point per cell, plotted by type. showboth=Also show median.
"""
Vmean = [np.mean(i) for i in V] # Take the mean of each element (okay for lists and scalars)
Vmed = [np.median(i) for i in V]
L = list(np.unique(labelsin))
C = [L.index(i) for i in labelsin]
fcolors = ['darkkhaki', 'royalblue', 'forestgreen','tomato']
# plotting
fig = plt.figure()
ax = fig.add_subplot(111)
for v in range(len(V)):
meanline = ax.scatter(L.index(labelsin[v]), Vmean[v], c=fcolors[C[v]], s=100,
marker='o', edgecolor='k', alpha=0.6)#fcolors[C[v]])
if showboth:
medline = ax.scatter(L.index(labelsin[v])+.2, Vmed[v], c=fcolors[C[v]], s=100,
marker='s', edgecolor='k', alpha=0.6)#fcolors[C[v]])
# legend
khaki_patch = mpatches.Patch(color='darkkhaki',
label=labelsin[C.index(fcolors.index('darkkhaki'))])
royal_patch = mpatches.Patch(color='royalblue',
label=labelsin[C.index(fcolors.index('royalblue'))])
patches = [khaki_patch, royal_patch]
if len(L) > 2:
forest_patch = mpatches.Patch(color='forestgreen',
label=labelsin[C.index(fcolors.index('forestgreen'))])
patches.append(forest_patch)
if len(L) > 3:
tomato_patch = mpatches.Patch(color='tomato',
label=labelsin[C.index(fcolors.index('tomato'))])
patches.append(tomato_patch)
if showleg is not None:
ax.legend(handles=patches, loc=showleg, fontsize=15) # I often mess with this
if ticks is None:
ax.tick_params(axis='x',which='both',bottom='off',top='off',
labelbottom='off')
# title
if title:
ax.set_title(title, fontsize=20)
if axes is not None:
ax.set_xlabel(axes[0], fontsize=25)
ax.set_ylabel(axes[1], fontsize=25)
ax.tick_params(axis='y', which='major', labelsize=20) # Size of y ticks
ax.locator_params(nbins=4) # Number of y-tick bins
plt.show(); return
def pretty_scatter(V, labelsin, title=None, ticks=None, axes=None,
showleg='best', moreD=None, bounds=None):
"""
moreD = another set of type V to be plot on right axes, len(axes)=3
"""
L = list(np.unique(labelsin))
C = [L.index(i) for i in labelsin]
fcolors = ['darkkhaki', 'royalblue', 'forestgreen','tomato']
# plotting
fig = plt.figure(figsize=(2,4))
ax = fig.add_subplot(111)
ax2 = None
if moreD is not None:
if len(moreD) == len(V):
ax2 = ax.twinx()
for v in range(len(V)):
ax.scatter(L.index(labelsin[v]), V[v], c=fcolors[C[v]], s=80,
marker='o', edgecolor='k', alpha=0.6)#fcolors[C[v]])
if ax2 is not None:
ax2.scatter(L.index(labelsin[v])+.1, moreD[v], c=fcolors[C[v]], s=80,
marker='s', edgecolor='k', alpha=0.6)#fcolors[C[v]])
# legend
khaki_patch = mpatches.Patch(color='darkkhaki',
label=labelsin[C.index(fcolors.index('darkkhaki'))])
royal_patch = mpatches.Patch(color='royalblue',
label=labelsin[C.index(fcolors.index('royalblue'))])
patches = [khaki_patch, royal_patch]
if len(L) > 2:
forest_patch = mpatches.Patch(color='forestgreen',
label=labelsin[C.index(fcolors.index('forestgreen'))])
patches.append(forest_patch)
if len(L) > 3:
tomato_patch = mpatches.Patch(color='tomato',
label=labelsin[C.index(fcolors.index('tomato'))])
patches.append(tomato_patch)
if showleg is not None:
ax.legend(handles=patches, loc=showleg, fontsize=15) # I often mess with this
if ticks is None:
ax.tick_params(axis='x',which='both',bottom='off',top='off',
labelbottom='off')
# Get rid of side labels
for pos in ['top', 'right']:
ax.spines[pos].set_visible(False)
# title
if bounds is not None:
ax.set_ylim([bounds[0], bounds[1]])
if title:
ax.set_title(title, fontsize=20)
if axes is not None:
ax.set_xlabel(axes[0], fontsize=15)
ax.set_ylabel(axes[1], fontsize=15)
if ax2 is not None:
ax2.set_ylabel(axes[2], fontsize=15) # color='r'
plt.show(); return
def simple_scatter(x, y, fit=False, title=None, axes=None, showtext=True):
"""
"""
import scipy.stats as stats
if type(x[0]) is list: # Multiple plots
fcolors = ['darkkhaki', 'royalblue', 'forestgreen','deeppink']
if len(x) > 4:
print('Can only handle 4 data groups, got %i' %len(x))
else:
x, y = [x], [y]
fcolors = ['steelblue']
fig = plt.figure()
ax = fig.add_subplot(111)
for v in range(len(x)):
ax.scatter(x[v], y[v], c='ivory', edgecolor=fcolors[v],
linewidth=2, s=50, alpha=0.5)
beta, alpha, r, p, _ = stats.linregress(x[v], y[v])
ax.plot([min(x[v]), max(x[v])],
[min(x[v])*beta+alpha, max(x[v])*beta+alpha], c=fcolors[v],
linewidth=2.5)
print('Group %i fit: R=%.5f, P=%.5f (alpha=%.f5, beta=%.5f)'
%(v, r, p, alpha, beta))
if title is not None:
ax.set_title(title, fontsize=20)
if axes is not None:
ax.set_xlabel(axes[0], fontsize=25)
ax.set_ylabel(axes[1], fontsize=25)
#ax.set_xlim([min([min(i) for i in x]), 0.7*max([max(i) for i in x])])
#ax.set_ylim([min([min(i) for i in y]), max([max(i) for i in y])])
if showtext is True:
ax.text(min(x[0]), max(y[0])*.8, r'$r=%.3f$' %(r),
fontsize=25) # Can also print P-value as well
plt.show()
return
# Simple bar plot
def pretty_bar(v, labelsin, stderr=None, ticks=None, title=None, axes=None,
showleg='best', bounds=None):
"""
showleg can also be None or 'uppermiddle' etc.
"""
#mi, ma = lims(v)
L = list(np.unique(labelsin))
C = [L.index(i) for i in labelsin]
fcolors = ['darkkhaki', 'royalblue', 'forestgreen','lavenderblush']
# plotting
fig = plt.figure()
ax = fig.add_subplot(111)
if len(np.shape(v))>1:
V = [np.mean(i) for i in v]
Vstd = [np.std(i) for i in v]
else:
V=v
Vstd=stderr
num = len(V)
# plotting
if stderr is not None:
for e in range(num):
ax.bar(e,V[e], yerr=Vstd[e], color=fcolors[C[e]], ecolor='k', width=0.5)
else:
for e in range(num):
ax.bar(e,V[e], color=fcolors[C[e]], ecolor='k', width=0.5)
# legend
khaki_patch = mpatches.Patch(color='darkkhaki',
label=labelsin[C.index(fcolors.index('darkkhaki'))])
royal_patch = mpatches.Patch(color='royalblue',
label=labelsin[C.index(fcolors.index('royalblue'))])
patches = [khaki_patch, royal_patch]
if len(L) > 2:
forest_patch = mpatches.Patch(color='forestgreen',
label=labelsin[C.index(fcolors.index('forestgreen'))])
patches.append(forest_patch)
if len(L) > 3:
lavender_patch = mpatches.Patch(color='tomato',
label=labelsin[C.index(fcolors.index('tomato'))])
patches.append(lavender_patch)
if showleg is not None:
plt.legend(handles=patches, loc=showleg)
if stderr is not None:
ax.set_ylim([0, 1.5*(max(V)+np.mean(Vstd))])
else:
ax.set_ylim([0, max(V)+0.5*min(V)])
ax.set_xlim([-.5, len(V)])
if bounds is not None and type(bounds) is list:
ax.set_ylim([bounds[0], bounds[1]])
if ticks is None:
ax.tick_params(axis='x',which='both',bottom='off',top='off',
labelbottom='off')
for pos in ['bottom', 'left', 'top', 'right']:
ax.spines[pos].set_visible(False)
# title
if title:
ax.set_title(title, fontsize=20)
if axes is not None:
ax.set_xlabel(axes[0], fontsize=15)
ax.set_ylabel(axes[1], fontsize=15)
plt.show(); return
def pretty_stackedbar(V, labelsin, title=None, colors=None,
axes=None, showxticks=True, counts=True, ):
"""
Stacked bar plots. Groups are labeled (x-tick) and binned items are
colored. Colors can be supplied by user; must be >= len(kkeys) (one
unique color per unique item, NOT per group).
_counts_ determines whether percentages have already been computed,
if False, elements of _V_ should be dicts (keys are groups).
"""
# Colors - must be different, can be supplied by user
if colors is None:
colors = ['darkorchid', 'orchid', 'violet', 'pink', 'deeppink']
# Most abundant is on bottom, and so on
if counts:
print('Computing counts....')
plotgroups = [{i: float(V[k].count(i))/len(V[k]) for i in list(set(V[k]))}
for k in range(len(V))]
else:
print('Using supplied values...')
plotgroups = V
# Fill in the dicts
kkeys = []
for gr in plotgroups:
for k in gr.keys():
if k not in kkeys:
kkeys.append(k)
for u in range(len(plotgroups)):
for k in kkeys:
if k not in plotgroups[u].keys():
plotgroups[u][k] = 0. # Just make it a zero
bottoms = [0. for i in plotgroups]
# Plotting
plt.figure()
pbars = []
for k in kkeys:
pbars.append(plt.bar(np.arange(len(V)),
[plotgroups[i][k] for i in range(len(V))],
width=.5, color=colors[k],
edgecolor='white',
bottom=bottoms))
bottoms = [bottoms[b]+plotgroups[b][k] for b in range(len(bottoms))]
# Plot aesthetics
if axes is not None:
plt.xlabel(axes[0])
plt.ylabel(axes[1])
if title is not None:
plt.title(title)
if showxticks:
plt.xticks(np.arange(len(V))+0.25, labelsin)
plt.xlim([-.5, len(V)])
plt.legend(pbars, kkeys)
plt.show()
return
def plot_cum_dist(V, labelsin, title=None):
"""
Plot lines showing cumulative distribution, i.e. for Sholl.
Labels must be len(V) (one label per array).
"""
if max(V[0]) > 1:
normed = []
for i in V:
M = max(i)
normed.append([a/M for a in i])
V = normed
L = list(np.unique(labelsin))
C = [L.index(i) for i in labelsin]
fcolors = ['darkkhaki', 'royalblue', 'forestgreen','tomato']
fig = plt.figure(); ax = fig.add_subplot(111)
for i in range(len(V)):
ax.plot(V[i], [a/len(V[i]) for a in range(len(V[i]))], color=fcolors[C[i]],
linewidth=2)
ax.plot(V[i], [a/len(V[i]) for a in range(len(V[i]))], color=fcolors[C[i]],
linewidth=4, alpha=0.5)
# legend
khaki_patch = mpatches.Patch(color='darkkhaki',
label=labelsin[C.index(fcolors.index('darkkhaki'))])
royal_patch = mpatches.Patch(color='royalblue',
label=labelsin[C.index(fcolors.index('royalblue'))])
patches = [khaki_patch, royal_patch]
if len(L) > 2:
forest_patch = mpatches.Patch(color='forestgreen',
label=labelsin[C.index(fcolors.index('forestgreen'))])
patches.append(forest_patch)
if len(L) > 3:
lavender_patch = mpatches.Patch(color='tomato',
label=labelsin[C.index(fcolors.index('tomato'))])
patches.append(lavender_patch)
plt.legend(handles=patches)
# title
if title:
ax.set_title(title, fontsize=20)
plt.show()
########################################################################
# Pretty dimensional scatters
########################################################################
# -- colors are subjects but all axes are dimensions (not groups)
# Data do not need to be conditioned for these
def pretty_3d(v1, labelsin, v2, v3, shadows='z', title=None, axes=None,
showleg=None, lines=None, figsize=[5,5], ellipses=True):
"""
A 3-D scatter plot of various features (must have 3). shadows='x', 'y', 'z'
(points are projected onto the XY, XZ and YZ planes), len(axes)==3
lines = ['x', 'y', 'z']
"""
# Set up colors, check data
if len(v1) == len(v2) and len(v2) == len(v3) and len(v3) == len(labelsin):
pass
else:
print('Data are of different lengths!'); return
L = list(np.unique(labelsin)) # Get color data
C = [L.index(i) for i in labelsin]
colors = ['darkkhaki', 'royalblue', 'forestgreen','tomato']
#
fig = plt.figure(figsize=figsize, dpi=150)
ax = fig.add_subplot(111, projection='3d')
# For each data point plot it and its projection
for u in range(len(v1)):
ax.scatter(v1[u], v2[u], v3[u], color=colors[C[u]], edgecolor='k',
alpha=0.7, s=30) # Main scatter point
if shadows is not None:
if type(shadows) is not list:
shadows = list(shadows)
for sha in shadows:
shpts = {'x': v1[u], 'y': v2[u], 'z': v3[u]}
shpts[sha] = 0
ax.scatter(shpts['x'], shpts['y'], shpts['z'], color=colors[C[u]],
edgecolor='none', alpha=0.2, s=20) # XY plane (Z=0)
if lines is not None:
if type(lines) is not list:
lines = list(lines)
for la in lines:
lapts = {'x': v1[u], 'y': v2[u], 'z': v3[u]}
lapts[la] = 0
ax.plot([v1[u], lapts['x']], [v2[u],lapts['y']], [v3[u],lapts['z']],
color=colors[C[u]], alpha=0.2, linewidth=1.5) # XY plane (Z=0)
if ellipses:
from matplotlib.patches import Ellipse
for u in range(len(L)):
dat1 = [v1[j] for j in range(len(C)) if C[j]==u]
dat2 = [v2[j] for j in range(len(C)) if C[j]==u]
cov = np.cov(dat1, dat2)
lambda_, v = np.linalg.eig(cov)
lambda_ = np.sqrt(lambda_)
ell = Ellipse(xy=(np.mean(dat1), np.mean(dat2)), # Initial offset
width=lambda_[0]*2, height=lambda_[1]*2,
angle=np.rad2deg(np.arccos(v[0,0])), alpha=0.1)
ell.set_facecolor(colors[u])
ell.set_edgecolor(colors[u])
ell.set_linewidth(1)
# ell.set_linestyle('--')
ax.add_patch(ell)
pathpatch_2d_to_3d(ell, z=0, normal='z')
pathpatch_translate(ell, (0, 0, 0)) # Here can add _additional_ offset in x,y,z
#ax.add_artist(ell)
# Labels, legends
if axes is not None:
ax.set_xlabel(axes[0], fontsize=15)
ax.set_ylabel(axes[1], fontsize=15)
ax.set_zlabel(axes[2], fontsize=15)
if showleg is not None:
plt.legend(colors, L, loc=showleg)
ax.grid(False) # Remove the grids
ax.xaxis.pane.set_edgecolor('black')
ax.yaxis.pane.set_edgecolor('black')
ax.w_xaxis.set_pane_color((0.,0.,0.,0.1))
ax.w_yaxis.set_pane_color((0.,0.,0.,0.15))
ax.w_zaxis.set_pane_color((1.,1.,1.,0.))
for spax in ['x', 'y', 'z']:
plt.locator_params(axis=spax, nbins=3)
ax.set_zlim([0, (int(max(v3) / 10**int(math.log10(max(v3))))+1 ) * 10**int(math.log10(max(v3)))])
ax.set_zticks([0, (int(max(v3) / 10**int(math.log10(max(v3))))+1 ) * 10**int(math.log10(max(v3)))])
#ax.set_xlim([0,12000]) # Mess around with stuff as needed
plt.show()
return
def pretty_2d(v1, labelsin, v2, title=None, axes=None, showleg=None,
ellipses=True, figsize=[5,4], alteig=[]):
"""
A 2-D scatter plot of various features (must have 2).
len(axes)==2. ellipses = 1 std dev. If any elipses look back, enter
that order into alteig (i.e.: alteig=[1,2] if the 2nd and 3rd ells look off).
"""
# Set up colors, check data
if len(v1) == len(v2) and len(v2) == len(labelsin):
pass
else:
print('Data are of different lengths!'); return
L = list(np.unique(labelsin)) # Get color data
C = [L.index(i) for i in labelsin]
colors = ['darkkhaki', 'royalblue', 'forestgreen','tomato']
print('Order is: darkkhaki, royalblue, forestgreen, tomato') ## Tell user the order
fig = plt.figure(figsize=figsize, dpi=100)
ax = fig.add_subplot(111)
# For each data point plot it and its projection
for u in range(len(v1)):
ax.scatter(v1[u], v2[u], color=colors[C[u]], edgecolor='k',
alpha=1, s=40) # Main scatter point
# Add std ellipses via eigenvectors etc
if ellipses:
from matplotlib.patches import Ellipse
for u in range(len(L)):
dat1 = [v1[j] for j in range(len(C)) if C[j]==u]
dat2 = [v2[j] for j in range(len(C)) if C[j]==u]
cov = np.cov([i for i in dat1 if not pd.isnull(i)],
[i for i in dat2 if not pd.isnull(i)])
if u in alteig:
vals, vecs = eigsorted(cov)
theta = np.degrees(np.arctan2(*vecs[:,0][::-1]))
w, h = np.sqrt(vals) * np.array([0.5,2])
ell = Ellipse(xy=(np.mean(dat1), np.mean(dat2)),
width=2, height=h, angle=theta, alpha=0.1)
else:
lambda_, v = np.linalg.eig(cov)
lambda_ = np.sqrt(lambda_)
ell = Ellipse(xy=(np.mean(dat1), np.mean(dat2)),
width=lambda_[0]*2, height=lambda_[1]*2,
angle=np.rad2deg(np.arccos(v[0,0])), alpha=0.1)
ell.set_facecolor(colors[u])
ell.set_linewidth(1)
ell.set_edgecolor(colors[u])
ax.add_artist(ell)
# Labels, legends
if axes is not None:
ax.set_xlabel(axes[0], fontsize=15)
ax.set_ylabel(axes[1], fontsize=15)
if showleg is not None:
plt.legend(colors, L, loc=showleg)
ax.grid(False) # Remove the grids
plt.locator_params(axis='x', nbins=4)
plt.locator_params(axis='y', nbins=4)
for pos in ['top', 'right']:
ax.spines[pos].set_visible(False)
plt.tight_layout() # OR plt.gca().tight_layout() # gca = get current axes
plt.show()
return
def hist_2d(x, y, labelsin=None, axes=None, showstats=False,
tint=False, forcebins=10):
"""
Scatter-plot 2-D data with histograms on either axes.
Colors codes x-y pairs by groups and then can allow the histograms
to be tinted (tint=True) to show composition of each group.
x,y can be pd.Series from DataFrame.
"""
# Colors etc
if labelsin is not None:
uniq_cols = [list(np.random.random(3)) for i in list(set(labelsin))]
cols = [uniq_cols[list(set(labelsin)).index(i)] for i in labelsin]
col_dict = {}
for l in range(len(labelsin)):
if cols[l] not in col_dict.values():
col_dict[len(col_dict.keys())] = cols[l]
else:
cols = ['blue' for i in range(len(x))]
### Scatter
plt.subplot2grid( (4,4), (1,0), rowspan=3, colspan=3)
for p in range(len(x)):
plt.plot(x[p], y[p], color=cols[p], marker='o', markeredgecolor='none',
alpha=0.9, ) # markersize=2
Xrange, Yrange = plt.xlim(), plt.ylim()
if axes is not None:
plt.xlabel(axes[0], fontsize=15); plt.ylabel(axes[1], fontsize=15)
# Stats
if showstats:
from scipy.stats import spearmanr as spear
plt.text(Xrange[1]/2., Yrange[1]-Yrange[1]*.1, 'spearman rank: %.3f' %spear(x,y)[0])
### Horizontal histogram
plt.subplot2grid( (4,4), (0,0), colspan=3)
bin_edges = np.linspace(Xrange[0], Xrange[1], forcebins+1)
bin_colors = [ [] for i in range(forcebins)]
for d in range(len(x)): # X values only for horizontal
bin_colors[len([b for b in bin_edges if x[d]>=b])-1].append(cols[d])
if tint: # Add a tint to the color -- average colors
bin_col = [[np.mean([k[i] for k in bin_colors[bin_]]) for i in range(3)]
for bin_ in range(len(bin_colors))]
for b in range(len(bin_col)): # len(bin_col) == len(bin_edges)-1
plt.bar((bin_edges[b]+bin_edges[b+1])/2., len(bin_colors[b]),
color=bin_col[b], edgecolor='white',
width=(bin_edges[b+1]-bin_edges[b])*.95)
else: # No tint, stack the bars (hori)
for b in range(len(bin_colors)):
try:
bar_colors = [col_ for col_ in col_dict.values() if col_ in bin_colors[b]]
except:
print(bin_colors[b], col_dict.values())
bottom = 0
for color_ in bar_colors:
height = bin_colors[b].count(color_)
plt.bar((bin_edges[b]+bin_edges[b+1])/2., height, bottom=bottom,
color=color_, edgecolor='white', alpha=0.6,
width=(bin_edges[b+1]-bin_edges[b])*.95)
bottom += height
plt.axis('off')
### Vertical histogram
plt.subplot2grid( (4,4), (1,3), rowspan=3)
bin_edges = np.linspace(Yrange[0], Yrange[1], forcebins+1)
bin_colors = [ [] for i in range(forcebins)]
for d in range(len(y)): # Y values only for vertical
bin_colors[len([b for b in bin_edges if y[d]>=b])-1].append(cols[d])
if tint: # Add a tint to the color -- average colors
bin_col = [[np.mean([k[i] for k in bin_colors[bin_]]) for i in range(3)]
for bin_ in range(len(bin_colors))]
for b in range(len(bin_col)): # len(bin_col) == len(bin_edges)-1
plt.barh((bin_edges[b]+bin_edges[b+1])/2., len(bin_colors[b]),
color=bin_col[b], edgecolor='white',
height=(bin_edges[b+1]-bin_edges[b])*.95)
else: # No tint, stack the bars (vert)
for b in range(len(bin_colors)):
bar_colors = [col_ for col_ in col_dict.values() if col_ in bin_colors[b]]
bottom = 0
for color_ in bar_colors:
height = bin_colors[b].count(color_)
plt.barh((bin_edges[b]+bin_edges[b+1])/2., height, left=bottom,
color=color_, edgecolor='white', alpha=0.6,
height=(bin_edges[b+1]-bin_edges[b])*.95)
bottom += height
plt.axis('off')
plt.show(); return
########################################################################
# Horizontal plots: histograms, violins and scatters
########################################################################
def hori_histogram(xdata, labelsin, title=None, axes=None, norm=False,
showmean=True, switch=False, llog=False, rrange=None,
forcebins=100, shade=True, eps=False, xcnt=True):
"""xcnt is the max of the y axis (on bottom)
"""
if switch:
for i in range(len(xdata)-1):
xdata.append(xdata.pop(0))
labelsin.append(labelsin.pop(0))
colors = ['darkkhaki', 'royalblue', 'forestgreen','tomato', 'darkorchid']
altcolors = ['palegoldenrod', 'lightskyblue', 'lightgreen', 'lightpink', 'plum']
L = list(np.unique(labelsin))
C = [L.index(i) for i in labelsin]
#print(L,C)
fig = plt.figure(dpi=200) # Give it pub-quality DPI
plots = [fig.add_subplot(1,len(xdata),i+1) for i in range(len(xdata))]
if norm is True:
#tdata = np.linspace(0,100,len(xdata[0]))
X = []
for x in xdata:
X.append([i/max(x) for i in x])
xdata = X
minm, maxm = 0, 1.
elif norm is False and rrange is None:
minm, maxm = np.inf, 0 # condition the data
for x in xdata:
if np.mean(x)-np.std(x) < minm:
minm = np.mean(x)-2*np.std(x)
if np.mean(x)+np.std(x) > maxm:
maxm = np.mean(x)+2*np.std(x)
if minm < 0:
minm = 0.
else:
minm, maxm = rrange[0], rrange[1]
for p in range(len(xdata)): # now plot
if type(forcebins) is list:
b_e = forcebins
else:
b_e = np.linspace(minm, maxm, forcebins) # len/100 bins
hist, _ = np.histogram(xdata[p], bins=b_e)
plotbins = [(b_e[i]+b_e[i+1])/2. for i in range(len(b_e)-1)]
# find the appropriate bar width #print(minm, maxm, p);
hgt = (maxm-minm)/len([i for i in hist if i != 0]) # as high as there are filled hist elements
hgt = plotbins[2]-plotbins[1]
q25, q75 = np.percentile(xdata[p], [25, 75])
barcols = [colors[C[p]] if q75 > plotbins[t] > q25 # In IQR
else altcolors[C[p]] for t in range(len(plotbins))]
for b in range(len(plotbins)):
plots[p].barh(plotbins[b], hist[b]/max(hist), height=hgt, linewidth=0, alpha=0.9,
color=barcols[b], edgecolor=barcols[b]) #=colors[C[p]])
# show the means:
if showmean:
plots[p].plot([0,1], [np.mean(xdata[p]), np.mean(xdata[p])],
linewidth=1., c='purple')
plots[p].plot([0,1], [np.median(xdata[p]), np.median(xdata[p])],
'--', linewidth=1., c='purple', )
if p == 0: #if first plot, show the axes
#plots[p].tick_params(axis='x',which='both',bottom='off',top='off',
# labelbottom='off')
if axes:
plots[p].set_ylabel(axes[1], fontsize=15)
plots[p].set_ylim([minm, maxm])
if llog is True:
plots[p].set_yscale('log'); plots[p].set_ylim([0, maxm]) ## Log scale
for pos in ['top', 'right']:
plots[p].spines[pos].set_visible(False)
else:
#plots[p].axis('off')
#plots[p].tick_params(axis='x',which='both',bottom='off',top='off',
# labelbottom='off')
plots[p].get_yaxis().set_visible(False)
if llog is True:
plots[p].set_yscale('log') ## Log scale
plots[p].set_ylim([minm,maxm])
for pos in ['top', 'left', 'right']:
plots[p].spines[pos].set_visible(False)
plt.locator_params(nbins=4) #################### Set one x-tick
plots[p].set_xticks([.5])
plots[p].set_xticklabels(['%i' %int(max(hist))])
if title:
plt.suptitle(title, fontsize=20)
plt.show()
return
# A sample legend for horizontal histograms
def hori_bars_legend():
plt.bar(range(100),np.random.normal(100),facecolor='darkgray', edgecolor='darkgray')
plt.axvspan(25, 75, 0,1, color='gray', alpha=0.3)
plt.plot([50,50],[0,1], '-', c='k', linewidth=3)
plt.plot([55,55],[0,1], '--', c='k', linewidth=3)
plt.tick_params(axis='x', which='both',bottom='off', top='off', labelbottom='off')
plt.tick_params(axis='y', which='both',left='off', right='off', labelleft='off')
plt.show()
def violin_box(xdata, labelsin, title=None, axes=None, norm=False,
showmean=True, switch=False, llog=False, rrange=None,
forcebins=100, shade=True, eps=False, xcnt=True):
"""xcnt is the max of the y axis (on bottom)
"""
if switch:
for i in range(len(xdata)-1):
xdata.append(xdata.pop(0))
labelsin.append(labelsin.pop(0))
colors = ['darkkhaki', 'royalblue', 'forestgreen','tomato', 'darkorchid']
altcolors = ['palegoldenrod', 'lightskyblue', 'lightgreen', 'lightpink', 'plum']
L = list(np.unique(labelsin))
C = [L.index(i) for i in labelsin]
#print(L,C)
fig = plt.figure(dpi=200) # Give it pub-quality DPI
plots = [fig.add_subplot(1,len(xdata),i+1) for i in range(len(xdata))]
if norm is True:
#tdata = np.linspace(0,100,len(xdata[0]))
X = []
for x in xdata:
X.append([i/max(x) for i in x])
xdata = X
minm, maxm = 0, 1.
elif norm is False and rrange is None:
minm, maxm = np.inf, 0 # condition the data
for x in xdata:
if np.mean(x)-np.std(x) < minm:
minm = np.mean(x)-2*np.std(x)
if np.mean(x)+np.std(x) > maxm:
maxm = np.mean(x)+2*np.std(x)
if minm < 0:
minm = 0.
else:
minm, maxm = rrange[0], rrange[1]
for p in range(len(xdata)): # now plot
if type(forcebins) is list:
b_e = forcebins
else:
b_e = np.linspace(minm, maxm, forcebins) # len/100 bins
hist, _ = np.histogram(xdata[p], bins=b_e)
plotbins = [(b_e[i]+b_e[i+1])/2. for i in range(len(b_e)-1)]
# find the appropriate bar width #print(minm, maxm, p);
hgt = (maxm-minm)/len([i for i in hist if i != 0]) # as high as there are filled hist elements
# hgt = plotbins[2]-plotbins[1]
q25, q75 = np.percentile(xdata[p], [25, 75])
barcols = [colors[C[p]] if q75 > plotbins[t] > q25 # In IQR
else altcolors[C[p]] for t in range(len(plotbins))]
# Plot the baseline
for base in [[q25+hgt,q75,colors[C[p]]], [q25,min(plotbins),altcolors[C[p]]], [max(plotbins),q75+hgt,altcolors[C[p]]]]:
plots[p].plot([0.,0.], [base[0],base[1]], c=base[2], linewidth=1, alpha=0.9)
for b in range(len(plotbins)): # Plot the +bar and -bar
#plots[p].barh(plotbins[b], 0.5+hist[b]/(2*max(hist)), height=hgt, linewidth=0, alpha=0.9,
# color=barcols[b], edgecolor=barcols[b]) #=colors[C[p]])
plots[p].barh(plotbins[b], hist[b]/(max(hist)), height=hgt, linewidth=0, alpha=0.9,
color=barcols[b], edgecolor=barcols[b],
left=-(hist[b]/(2*max(hist)))) #=colors[C[p]])
# show the means:
if showmean:
plots[p].plot([-.5,.5], [np.mean(xdata[p]), np.mean(xdata[p])],
linewidth=1., c='purple')
plots[p].plot([-.5,.5], [np.median(xdata[p]), np.median(xdata[p])],
'--', linewidth=1., c='purple', )
if p == 0: #if first plot, show the axes
if axes:
plots[p].set_ylabel(axes[1], fontsize=15)
plots[p].set_ylim([minm, maxm])
if llog is True:
plots[p].set_yscale('log'); plots[p].set_ylim([0, maxm]) ## Log scale
for pos in ['top', 'right']:
plots[p].spines[pos].set_visible(False)
else:
plots[p].get_yaxis().set_visible(False)
if llog is True:
plots[p].set_yscale('log') ## Log scale
plots[p].set_ylim([minm,maxm])
for pos in ['top', 'left', 'right']:
plots[p].spines[pos].set_visible(False)
plt.locator_params(nbins=4) #################### Set one x-tick
plots[p].set_xticks([.5])
plots[p].set_xticklabels(['%i' %int(max(hist))])
# plots[p].set_xlim([0,1.])
if title:
plt.suptitle(title, fontsize=20)
plt.show()
return
def violin_spline(xdata, labelsin, title=None, axes=None, norm=False,
showmean=True, stepfilled=True, llog=False, rrange=None,
forcebins=100, shade=True, eps=False, xcnt=True):
"""xcnt is the max of the y axis (on bottom)
"""
from scipy.ndimage.filters import gaussian_filter1d as filt
colors = ['darkkhaki', 'royalblue', 'forestgreen','tomato', 'darkorchid']
altcolors = ['palegoldenrod', 'lightskyblue', 'lightgreen', 'lightpink', 'plum']
L = list(np.unique(labelsin))
C = [L.index(i) for i in labelsin]
#print(L,C)
fig = plt.figure(dpi=200) # Give it pub-quality DPI
plots = [fig.add_subplot(1,len(xdata),i+1) for i in range(len(xdata))]
if norm is True:
#tdata = np.linspace(0,100,len(xdata[0]))
X = []
for x in xdata:
X.append([i/max(x) for i in x])
xdata = X
minm, maxm = 0, 1.
elif norm is False and rrange is None:
minm, maxm = np.inf, 0 # condition the data
for x in xdata:
if np.mean(x)-np.std(x) < minm:
minm = np.mean(x)-2*np.std(x)
if np.mean(x)+np.std(x) > maxm:
maxm = np.mean(x)+2*np.std(x)
if minm < 0:
minm = 0.
else:
minm, maxm = rrange[0], rrange[1]
for p in range(len(xdata)): # now plot
if type(forcebins) is list:
b_e = forcebins
else:
b_e = np.linspace(minm, maxm, forcebins) # len/100 bins
hist, _ = np.histogram(xdata[p], bins=b_e)
occupied = len([i for i in hist if i != 0])
if type(forcebins) is int and occupied < forcebins/2.: # Sparse bins
hist, b_e = np.histogram(xdata[p], bins=int(occupied*2))
plotbins = [(b_e[i]+b_e[i+1])/2. for i in range(len(b_e)-1)]
# find the appropriate bar width #print(minm, maxm, p);
hgt = (maxm-minm)/occupied # as high as there are filled hist elements
# hgt = plotbins[2]-plotbins[1]
q25, q75 = np.percentile(xdata[p], [25, 75])
barcols = [colors[C[p]] if q75 > plotbins[t] > q25 # In IQR
else altcolors[C[p]] for t in range(len(plotbins))]
# Plot the baseline
for base in [[q25,q75,colors[C[p]]], [q25,min(plotbins),altcolors[C[p]]], [max(plotbins),q75+hgt,altcolors[C[p]]]]:
plots[p].plot([0.,0.], [base[0],base[1]], c=base[2], linewidth=1, alpha=0.9)
fit = filt(hist, 1.5)
q1_inds = [[plotbins[u], fit[u]] for u in range(len(fit)) if plotbins[u] < q25+hgt]
q4_inds = [[plotbins[u], fit[u]] for u in range(len(fit)) if plotbins[u] > q75-hgt]
iqr_inds = [[plotbins[u], fit[u]] for u in range(len(fit)) if q25 < plotbins[u] < q75]
plots[p].fill_betweenx([q[0] for q in q1_inds],[q[1]/max(fit) for q in q1_inds],
[-q[1]/max(fit) for q in q1_inds], color=altcolors[C[p]], alpha=0.9)
plots[p].fill_betweenx([q[0] for q in q4_inds],[q[1]/max(fit) for q in q4_inds],
[-q[1]/max(fit) for q in q4_inds], color=altcolors[C[p]], alpha=0.9)
plots[p].fill_betweenx([q[0] for q in iqr_inds],[q[1]/max(fit) for q in iqr_inds],
[-q[1]/max(fit) for q in iqr_inds], color=colors[C[p]], alpha=0.9)
if stepfilled:
xsteps = [plotbins[0], plotbins[0], plotbins[0], plotbins[1]]
ysteps = [0, hist[0], hist[1], hist[1]] #
for u in range(1,len(plotbins)-1):
ysteps.append(hist[u+1]); ysteps.append(hist[u+1]) # ysteps xsteps-1 -> xsteps+1
xsteps.append(plotbins[u]); xsteps.append(plotbins[u+1]) # now xsteps -> ysteps+1
xsteps.append(xsteps[-1]); ysteps.append(plotbins[-1]) # Back to 0
ysteps = np.array(ysteps)/max(ysteps)
plots[p].plot(ysteps, xsteps, color='white', linewidth=0.5)