-
Notifications
You must be signed in to change notification settings - Fork 45
/
plot_tools.py
1495 lines (1327 loc) · 58.4 KB
/
plot_tools.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
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/API/plot_tools.ipynb.
# %% ../nbs/API/plot_tools.ipynb 2
from __future__ import annotations
# %% auto 0
__all__ = ['halfviolin', 'get_swarm_spans', 'error_bar', 'check_data_matches_labels', 'normalize_dict', 'width_determine',
'single_sankey', 'sankeydiag', 'summary_bars_plotter', 'contrast_bars_plotter', 'swarm_bars_plotter',
'swarmplot', 'SwarmPlot']
# %% ../nbs/API/plot_tools.ipynb 4
import math
import warnings
import itertools
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import matplotlib.axes as axes
import matplotlib.patches as mpatches
from collections import defaultdict
from typing import List, Tuple, Dict, Iterable, Union
from pandas.api.types import CategoricalDtype
from matplotlib.colors import ListedColormap
# %% ../nbs/API/plot_tools.ipynb 5
def halfviolin(v, half="right", fill_color="k", alpha=1, line_color="k", line_width=0):
for b in v["bodies"]:
V = b.get_paths()[0].vertices
mean_vertical = np.mean(V[:, 0])
mean_horizontal = np.mean(V[:, 1])
if half == "right":
V[:, 0] = np.clip(V[:, 0], mean_vertical, np.inf)
elif half == "left":
V[:, 0] = np.clip(V[:, 0], -np.inf, mean_vertical)
elif half == "bottom":
V[:, 1] = np.clip(V[:, 1], -np.inf, mean_horizontal)
elif half == "top":
V[:, 1] = np.clip(V[:, 1], mean_horizontal, np.inf)
b.set_color(fill_color)
b.set_alpha(alpha)
b.set_edgecolor(line_color)
b.set_linewidth(line_width)
def get_swarm_spans(coll):
"""
Given a matplotlib Collection, will obtain the x and y spans
for the collection. Will return None if this fails.
"""
if coll is None:
raise ValueError("The collection `coll` parameter cannot be None")
x, y = np.array(coll.get_offsets()).T
try:
return x.min(), x.max(), y.min(), y.max()
except ValueError as e:
warnings.warn(f"Failed to calculate spans for the collection. Details: {e}")
return None
def error_bar(
data: pd.DataFrame, # This DataFrame should be in 'long' format.
x: str, # x column to be plotted.
y: str, # y column to be plotted.
type: str = "mean_sd", # Choose from ['mean_sd', 'median_quartiles']. Plots the summary statistics for each group. If 'mean_sd', then the mean and standard deviation of each group is plotted as a gapped line. If 'median_quantiles', then the median and 25th and 75th percentiles of each group is plotted instead.
offset: float = 0.2, # Give a single float (that will be used as the x-offset of all gapped lines), or an iterable containing the list of x-offsets.
ax=None, # If a matplotlib Axes object is specified, the gapped lines will be plotted in order on this axes. If None, the current axes (plt.gca()) is used.
line_color="black", # The color of the gapped lines.
gap_width_percent=1, # The width of the gap in the gapped lines, as a percentage of the y-axis span.
pos: list = [
0,
1,
], # The positions of the error bars for the sankey_error_bar method.
method: str = "gapped_lines", # The method to use for drawing the error bars. Options are: 'gapped_lines', 'proportional_error_bar', and 'sankey_error_bar'.
**kwargs: dict,
):
"""
Function to plot the standard deviations as vertical errorbars.
The mean is a gap defined by negative space.
This function combines the functionality of gapped_lines(),
proportional_error_bar(), and sankey_error_bar().
"""
if gap_width_percent < 0 or gap_width_percent > 100:
raise ValueError("`gap_width_percent` must be between 0 and 100.")
if method not in ["gapped_lines", "proportional_error_bar", "sankey_error_bar"]:
raise ValueError(
"Invalid `method`. Must be one of 'gapped_lines', \
'proportional_error_bar', or 'sankey_error_bar'."
)
if ax is None:
ax = plt.gca()
ax_ylims = ax.get_ylim()
ax_yspan = np.abs(ax_ylims[1] - ax_ylims[0])
gap_width = ax_yspan * gap_width_percent / 100
keys = kwargs.keys()
if "clip_on" not in keys:
kwargs["clip_on"] = False
if "zorder" not in keys:
kwargs["zorder"] = 5
if "lw" not in keys:
kwargs["lw"] = 2.0
if isinstance(data[x].dtype, pd.CategoricalDtype):
group_order = pd.unique(data[x]).categories
else:
group_order = pd.unique(data[x])
means = data.groupby(x)[y].mean().reindex(index=group_order)
if method in ["proportional_error_bar", "sankey_error_bar"]:
g = lambda x: np.sqrt(
(np.sum(x) * (len(x) - np.sum(x))) / (len(x) * len(x) * len(x))
)
sd = data.groupby(x)[y].apply(g)
else:
sd = data.groupby(x)[y].std().reindex(index=group_order)
lower_sd = means - sd
upper_sd = means + sd
if (lower_sd < ax_ylims[0]).any() or (upper_sd > ax_ylims[1]).any():
kwargs["clip_on"] = True
medians = data.groupby(x)[y].median().reindex(index=group_order)
quantiles = (
data.groupby(x)[y].quantile([0.25, 0.75]).unstack().reindex(index=group_order)
)
lower_quartiles = quantiles[0.25]
upper_quartiles = quantiles[0.75]
if type == "mean_sd":
central_measures = means
lows = lower_sd
highs = upper_sd
elif type == "median_quartiles":
central_measures = medians
lows = lower_quartiles
highs = upper_quartiles
else:
raise ValueError("Only accepted values for type are ['mean_sd', 'median_quartiles']")
n_groups = len(central_measures)
if isinstance(line_color, str):
custom_palette = np.repeat(line_color, n_groups)
else:
if len(line_color) != n_groups:
err1 = "{} groups are being plotted, but ".format(n_groups)
err2 = "{} colors(s) were supplied in `line_color`.".format(len(line_color))
raise ValueError(err1 + err2)
custom_palette = line_color
try:
len_offset = len(offset)
except TypeError:
offset = np.repeat(offset, n_groups)
len_offset = len(offset)
if len_offset != n_groups:
err1 = "{} groups are being plotted, but ".format(n_groups)
err2 = "{} offset(s) were supplied in `offset`.".format(len_offset)
raise ValueError(err1 + err2)
kwargs["zorder"] = kwargs["zorder"]
for xpos, central_measure in enumerate(central_measures):
kwargs["color"] = custom_palette[xpos]
if method == "sankey_error_bar":
_xpos = pos[xpos] + offset[xpos]
else:
_xpos = xpos + offset[xpos]
low = lows[xpos]
high = highs[xpos]
if low == high == central_measure:
low_to_mean = mlines.Line2D(
[_xpos, _xpos], [low, central_measure], **kwargs
)
ax.add_line(low_to_mean)
mean_to_high = mlines.Line2D(
[_xpos, _xpos], [central_measure, high], **kwargs
)
ax.add_line(mean_to_high)
else:
low_to_mean = mlines.Line2D(
[_xpos, _xpos], [low, central_measure - gap_width], **kwargs
)
ax.add_line(low_to_mean)
mean_to_high = mlines.Line2D(
[_xpos, _xpos], [central_measure + gap_width, high], **kwargs
)
ax.add_line(mean_to_high)
def check_data_matches_labels(
labels, # list of input labels
data, # Pandas Series of input data
side: str, # 'left' or 'right' on the sankey diagram
):
"""
Function to check that the labels and data match in the sankey diagram.
And enforce labels and data to be lists.
Raises an exception if the labels and data do not match.
"""
if len(labels) > 0:
if isinstance(data, list):
data = set(data)
if isinstance(data, pd.Series):
data = set(data.unique())
if isinstance(labels, list):
labels = set(labels)
if labels != data:
msg = "\n"
if len(labels) <= 20:
msg = "Labels: " + ",".join(labels) + "\n"
if len(data) < 20:
msg += "Data: " + ",".join(data)
raise Exception(f"{side} labels and data do not match.{msg}")
def normalize_dict(nested_dict, target):
"""
Normalizes the values in a nested dictionary based on a target dictionary.
This function iterates through a nested dictionary, calculates the sum of values for each key
across all sub-dictionaries, and then normalizes these values according to a target dictionary.
The normalization is performed such that the values in each sub-dictionary are proportionally
scaled to match the corresponding 'right' values in the target dictionary.
Parameters:
nested_dict (dict of dict): A nested dictionary where each key maps to another dictionary.
The values in these inner dictionaries are subject to normalization.
target (dict): A dictionary with the target values for normalization. Each key in nested_dict
should have a corresponding key in target, and each target[key] should be a
dictionary with a 'right' key containing the target normalization value.
Returns:
dict: The normalized nested dictionary. The original nested_dict is modified in place.
Note:
- If the sum of values for a particular key in nested_dict is zero, the normalized value is set to 0.
- If a key in a sub-dictionary of nested_dict does not exist in the target dictionary, the
corresponding 'right' value from the target dictionary is directly assigned.
- The function modifies the input nested_dict in place and also returns it.
"""
val = {}
for key in nested_dict.keys():
val[key] = np.sum(
[
nested_dict[sub_key][key]
for sub_key in nested_dict.keys()
if key in nested_dict[sub_key]
]
)
for key, value in nested_dict.items():
if isinstance(value, dict):
for subkey in value.keys():
if subkey in val.keys():
if val[subkey] != 0:
# Address the problem when one of the labels has zero value
value[subkey] = (
value[subkey] * target[subkey]["right"] / val[subkey]
)
else:
value[subkey] = 0
else:
value[subkey] = target[subkey]["right"]
return nested_dict
def width_determine(labels, data, pos="left"):
"""
Calculates normalized width positions for a set of labels based on their associated data.
This function is designed to determine width positions for plotting or graphical representation.
It takes into account the cumulative weight of each label in the data and adjusts their positions
accordingly. The function allows for adjusting the position of labels to either the 'left' or 'right'.
Parameters:
labels (list): A list of labels whose width positions are to be calculated.
data (DataFrame): A pandas DataFrame containing the data used for calculating width positions.
The DataFrame should have columns corresponding to the 'pos' and 'posWeight'.
pos (str, optional): The position of labels. It can be either 'left' or 'right'. Defaults to 'left'.
Returns:
defaultdict: A dictionary where each key is a label and the value is another dictionary with keys
'bottom', 'top', and 'pos', representing the calculated width positions.
Note:
The function assumes that the data DataFrame contains columns named after the value of 'pos' and
an additional column named 'posWeight' which represents the weight of each label.
"""
if labels is None:
raise ValueError("The `labels` parameter cannot be None")
if data is None:
raise ValueError("The `data` parameter cannot be None")
widths_norm = defaultdict()
for i, label in enumerate(labels):
myD = {}
myD[pos] = data[data[pos] == label][pos + "Weight"].sum()
if len(labels) != 1:
if i == 0:
myD["bottom"] = 0
myD[pos] -= 0.01
myD["top"] = myD[pos]
elif i == len(labels) - 1:
myD[pos] -= 0.01
myD["bottom"] = 1 - myD[pos]
myD["top"] = 1
else:
myD[pos] -= 0.02
myD["bottom"] = widths_norm[labels[i - 1]]["top"] + 0.02
myD["top"] = myD["bottom"] + myD[pos]
else:
myD["bottom"] = 0
myD["top"] = 1
widths_norm[label] = myD
return widths_norm
def single_sankey(
left: np.array, # data on the left of the diagram
right: np.array, # data on the right of the diagram, len(left) == len(right)
xpos: float = 0, # the starting point on the x-axis
left_weight: np.array = None, # weights for the left labels, if None, all weights are 1
right_weight: np.array = None, # weights for the right labels, if None, all weights are corresponding left_weight
colorDict: dict = None, # input format: {'label': 'color'}
left_labels: list = None, # labels for the left side of the diagram. The diagram will be sorted by these labels.
right_labels: list = None, # labels for the right side of the diagram. The diagram will be sorted by these labels.
ax=None, # matplotlib axes to be drawn on
flow: bool = True, # if True, draw the sankey in a flow, else draw 1 vs 1 Sankey diagram for each group comparison
sankey: bool = True, # if True, draw the sankey diagram, else draw barplot
width=0.5,
alpha=0.65,
bar_width=0.2,
error_bar_on: bool = True, # if True, draw error bar for each group comparison
strip_on: bool = True, # if True, draw strip for each group comparison
one_sankey: bool = False, # if True, only draw one sankey diagram
right_color: bool = False, # if True, each strip of the diagram will be colored according to the corresponding left labels
align: bool = "center", # if 'center', the diagram will be centered on each xtick, if 'edge', the diagram will be aligned with the left edge of each xtick
):
"""
Make a single Sankey diagram showing proportion flow from left to right
Original code from: https://github.com/anazalea/pySankey
Changes are added to normalize each diagram's height to be 1
"""
# Initiating values
if ax is None:
ax = plt.gca()
if left_weight is None:
left_weight = []
if right_weight is None:
right_weight = []
if left_labels is None:
left_labels = []
if right_labels is None:
right_labels = []
# Check weights
if len(left_weight) == 0:
left_weight = np.ones(len(left))
if len(right_weight) == 0:
right_weight = np.ones(len(right))
# Create Dataframe
if isinstance(left, pd.Series):
left.reset_index(drop=True, inplace=True)
if isinstance(right, pd.Series):
right.reset_index(drop=True, inplace=True)
dataFrame = pd.DataFrame(
{
"left": left,
"right": right,
"left_weight": left_weight,
"right_weight": right_weight,
},
index=range(len(left)),
)
if dataFrame[["left", "right"]].isnull().any(axis=None):
raise Exception("Sankey graph does not support null values.")
# Identify all labels that appear 'left' or 'right'
allLabels = pd.Series(
np.sort(np.r_[dataFrame.left.unique(), dataFrame.right.unique()])[::-1]
).unique()
# Identify left labels
if len(left_labels) == 0:
left_labels = pd.Series(np.sort(dataFrame.left.unique())[::-1]).unique()
else:
check_data_matches_labels(left_labels, dataFrame["left"], "left")
# Identify right labels
if len(right_labels) == 0:
right_labels = pd.Series(np.sort(dataFrame.right.unique())[::-1]).unique()
else:
check_data_matches_labels(left_labels, dataFrame["right"], "right")
# If no colorDict given, make one
if colorDict is None:
colorDict = {}
palette = "hls"
colorPalette = sns.color_palette(palette, len(allLabels))
for i, label in enumerate(allLabels):
colorDict[label] = colorPalette[i]
fail_color = {0: "grey"}
colorDict.update(fail_color)
else:
missing = [label for label in allLabels if label not in colorDict.keys()]
if missing:
msg = "The palette parameter is missing values for the following labels : "
msg += "{}".format(", ".join(missing))
raise ValueError(msg)
if align not in ("center", "edge"):
err = "{} assigned for `align` is not valid.".format(align)
raise ValueError(err)
if align == "center":
try:
leftpos = xpos - width / 2
except TypeError as e:
raise TypeError(
f"the dtypes of parameters x ({xpos.dtype}) "
f"and width ({width.dtype}) "
f"are incompatible"
) from e
else:
leftpos = xpos
# Combine left and right arrays to have a pandas.DataFrame in the 'long' format
left_series = pd.Series(left, name="values").to_frame().assign(groups="left")
right_series = pd.Series(right, name="values").to_frame().assign(groups="right")
concatenated_df = pd.concat([left_series, right_series], ignore_index=True)
# Determine positions of left label patches and total widths
# We also want the height of the graph to be 1
leftWidths_norm = defaultdict()
for i, left_label in enumerate(left_labels):
myD = {}
myD["left"] = (
dataFrame[dataFrame.left == left_label].left_weight.sum()
/ dataFrame.left_weight.sum()
)
if len(left_labels) != 1:
if i == 0:
myD["bottom"] = 0
myD["left"] -= 0.01
myD["top"] = myD["left"]
elif i == len(left_labels) - 1:
myD["left"] -= 0.01
myD["bottom"] = 1 - myD["left"]
myD["top"] = 1
else:
myD["left"] -= 0.02
myD["bottom"] = leftWidths_norm[left_labels[i - 1]]["top"] + 0.02
myD["top"] = myD["bottom"] + myD["left"]
topEdge = myD["top"]
else:
myD["bottom"] = 0
myD["top"] = 1
myD["left"] = 1
leftWidths_norm[left_label] = myD
# Determine positions of right label patches and total widths
rightWidths_norm = defaultdict()
for i, right_label in enumerate(right_labels):
myD = {}
myD["right"] = (
dataFrame[dataFrame.right == right_label].right_weight.sum()
/ dataFrame.right_weight.sum()
)
if len(right_labels) != 1:
if i == 0:
myD["bottom"] = 0
myD["right"] -= 0.01
myD["top"] = myD["right"]
elif i == len(right_labels) - 1:
myD["right"] -= 0.01
myD["bottom"] = 1 - myD["right"]
myD["top"] = 1
else:
myD["right"] -= 0.02
myD["bottom"] = rightWidths_norm[right_labels[i - 1]]["top"] + 0.02
myD["top"] = myD["bottom"] + myD["right"]
topEdge = myD["top"]
else:
myD["bottom"] = 0
myD["top"] = 1
myD["right"] = 1
rightWidths_norm[right_label] = myD
# Total width of the graph
xMax = width
# Plot vertical bars for each label
for left_label in left_labels:
ax.fill_between(
[leftpos + (-(bar_width) * xMax * 0.5), leftpos + (bar_width * xMax * 0.5)],
2 * [leftWidths_norm[left_label]["bottom"]],
2 * [leftWidths_norm[left_label]["top"]],
color=colorDict[left_label],
alpha=0.99,
)
if (not flow and sankey) or one_sankey:
for right_label in right_labels:
ax.fill_between(
[
xMax + leftpos + (-bar_width * xMax * 0.5),
leftpos + xMax + (bar_width * xMax * 0.5),
],
2 * [rightWidths_norm[right_label]["bottom"]],
2 * [rightWidths_norm[right_label]["top"]],
color=colorDict[right_label],
alpha=0.99,
)
# Plot error bars
if error_bar_on and strip_on:
error_bar(
concatenated_df,
x="groups",
y="values",
ax=ax,
offset=0,
gap_width_percent=2,
method="sankey_error_bar",
pos=[leftpos, leftpos + xMax],
)
# Determine widths of individual strips, all widths are normalized to 1
ns_l = defaultdict()
ns_r = defaultdict()
ns_l_norm = defaultdict()
ns_r_norm = defaultdict()
for left_label in left_labels:
leftDict = {}
rightDict = {}
for right_label in right_labels:
leftDict[right_label] = dataFrame[
(dataFrame.left == left_label) & (dataFrame.right == right_label)
].left_weight.sum()
rightDict[right_label] = dataFrame[
(dataFrame.left == left_label) & (dataFrame.right == right_label)
].right_weight.sum()
factorleft = leftWidths_norm[left_label]["left"] / sum(leftDict.values())
leftDict_norm = {k: v * factorleft for k, v in leftDict.items()}
ns_l_norm[left_label] = leftDict_norm
ns_r[left_label] = rightDict
# ns_r should be using a different way of normalization to fit the right side
# It is normalized using the value with the same key in each sub-dictionary
ns_r_norm = normalize_dict(ns_r, rightWidths_norm)
# Plot strips
if sankey and strip_on:
for left_label, right_label in itertools.product(left_labels, right_labels):
labelColor = left_label
if right_color:
labelColor = right_label
if len(dataFrame[(dataFrame.left == left_label) &
(dataFrame.right == right_label)]) > 0:
# Create array of y values for each strip, half at left value,
# half at right, convolve
ys_d = np.array(
50 * [leftWidths_norm[left_label]["bottom"]]
+ 50 * [rightWidths_norm[right_label]["bottom"]]
)
ys_d = np.convolve(ys_d, 0.05 * np.ones(20), mode="valid")
ys_d = np.convolve(ys_d, 0.05 * np.ones(20), mode="valid")
# to remove the array wrapping behaviour of black
# fmt: off
ys_u = np.array(50 * [leftWidths_norm[left_label]['bottom'] + ns_l_norm[left_label][right_label]] + \
50 * [rightWidths_norm[right_label]['bottom'] + ns_r_norm[left_label][right_label]])
# fmt: on
ys_u = np.convolve(ys_u, 0.05 * np.ones(20), mode="valid")
ys_u = np.convolve(ys_u, 0.05 * np.ones(20), mode="valid")
# Update bottom edges at each label so next strip starts at the right place
leftWidths_norm[left_label]["bottom"] += ns_l_norm[left_label][right_label]
rightWidths_norm[right_label]["bottom"] += ns_r_norm[left_label][
right_label
]
ax.fill_between(
np.linspace(
leftpos + (bar_width * xMax * 0.5),
leftpos + xMax - (bar_width * xMax * 0.5),
len(ys_d),
),
ys_d,
ys_u,
alpha=alpha,
color=colorDict[labelColor],
edgecolor="none",
)
def sankeydiag(
data: pd.DataFrame,
xvar: str, # x column to be plotted.
yvar: str, # y column to be plotted.
left_idx: str, # the value in column xvar that is on the left side of each sankey diagram
right_idx: str, # the value in column xvar that is on the right side of each sankey diagram, if len(left_idx) == 1, it will be broadcasted to the same length as right_idx, otherwise it should have the same length as right_idx
left_labels: list = None, # labels for the left side of the diagram. The diagram will be sorted by these labels.
right_labels: list = None, # labels for the right side of the diagram. The diagram will be sorted by these labels.
palette: str | dict = None,
ax=None, # matplotlib axes to be drawn on
flow: bool = True, # if True, draw the sankey in a flow, else draw 1 vs 1 Sankey diagram for each group comparison
sankey: bool = True, # if True, draw the sankey diagram, else draw barplot
one_sankey: bool = False, # determined by the driver function on plotter.py, if True, draw the sankey diagram across the whole raw data axes
width: float = 0.4, # the width of each sankey diagram
right_color: bool = False, # if True, each strip of the diagram will be colored according to the corresponding left labels
align: str = "center", # the alignment of each sankey diagram, can be 'center' or 'left'
alpha: float = 0.65, # the transparency of each strip
**kwargs,
):
"""
Read in melted pd.DataFrame, and draw multiple sankey diagram on a single axes
using the value in column yvar according to the value in column xvar
left_idx in the column xvar is on the left side of each sankey diagram
right_idx in the column xvar is on the right side of each sankey diagram
"""
if "width" in kwargs:
width = kwargs["width"]
if "align" in kwargs:
align = kwargs["align"]
if "alpha" in kwargs:
alpha = kwargs["alpha"]
if "right_color" in kwargs:
right_color = kwargs["right_color"]
if "bar_width" in kwargs:
bar_width = kwargs["bar_width"]
if "sankey" in kwargs:
sankey = kwargs["sankey"]
if "flow" in kwargs:
flow = kwargs["flow"]
if ax is None:
ax = plt.gca()
allLabels = pd.Series(np.sort(data[yvar].unique())[::-1]).unique()
# Check if all the elements in left_idx and right_idx are in xvar column
unique_xvar = data[xvar].unique()
if not all(elem in unique_xvar for elem in left_idx):
raise ValueError(f"{left_idx} not found in {xvar} column")
if not all(elem in unique_xvar for elem in right_idx):
raise ValueError(f"{right_idx} not found in {xvar} column")
xpos = 0
# For baseline comparison, broadcast left_idx to the same length as right_idx
# so that the left of sankey diagram will be the same
# For sequential comparison, left_idx and right_idx can have anything different
# but should have the same length
if len(left_idx) == 1:
broadcasted_left = np.broadcast_to(left_idx, len(right_idx))
elif len(left_idx) != len(right_idx):
raise ValueError(f"left_idx and right_idx should have the same length")
else:
broadcasted_left = left_idx
if isinstance(palette, dict):
if not all(key in allLabels for key in palette.keys()):
raise ValueError(f"keys in palette should be in {yvar} column")
plot_palette = palette
elif isinstance(palette, str):
plot_palette = {}
colorPalette = sns.color_palette(palette, len(allLabels))
for i, label in enumerate(allLabels):
plot_palette[label] = colorPalette[i]
else:
plot_palette = None
# Create a strip_on list to determine whether to draw the strip during repeated measures
strip_on = [
int(right not in broadcasted_left[:i]) for i, right in enumerate(right_idx)
]
draw_idx = list(zip(broadcasted_left, right_idx))
for i, (left, right) in enumerate(draw_idx):
if not one_sankey:
if flow:
width = 1
align = "edge"
sankey = (
False if i == len(draw_idx) - 1 else sankey
) # Remove last strip in flow
error_bar_on = (
False if i == len(draw_idx) - 1 and flow else True
) # Remove last error_bar in flow
bar_width = 0.4 if sankey == False and flow == False else bar_width
single_sankey(
data[data[xvar] == left][yvar],
data[data[xvar] == right][yvar],
xpos=xpos,
ax=ax,
colorDict=plot_palette,
width=width,
left_labels=left_labels,
right_labels=right_labels,
strip_on=strip_on[i],
right_color=right_color,
bar_width=bar_width,
sankey=sankey,
error_bar_on=error_bar_on,
flow=flow,
align=align,
alpha=alpha,
)
xpos += 1
else:
xpos = 0
width = 1
if not sankey:
bar_width = 0.5
single_sankey(
data[data[xvar] == left][yvar],
data[data[xvar] == right][yvar],
xpos=xpos,
ax=ax,
colorDict=plot_palette,
width=width,
left_labels=left_labels,
right_labels=right_labels,
right_color=right_color,
bar_width=bar_width,
sankey=sankey,
one_sankey=one_sankey,
flow=False,
align="edge",
alpha=alpha,
)
# Now only draw vs xticks for two-column sankey diagram
if not one_sankey or (sankey and not flow):
sankey_ticks = (
[f"{left}" for left in broadcasted_left]
if flow
else [
f"{left}\n v.s.\n{right}"
for left, right in zip(broadcasted_left, right_idx)
]
)
ax.get_xaxis().set_ticks(np.arange(len(right_idx)))
ax.get_xaxis().set_ticklabels(sankey_ticks)
else:
sankey_ticks = [broadcasted_left[0], right_idx[0]]
ax.set_xticks([0, 1])
ax.set_xticklabels(sankey_ticks)
def summary_bars_plotter(summary_bars: list, results: object, ax_to_plot: object,
float_contrast: bool,summary_bars_kwargs: dict, ci_type: str,
ticks_to_plot: list, color_col: str, swarm_colors: list,
proportional: bool, is_paired: bool):
"""
Add summary bars to the contrast plot.
Parameters
----------
summary_bars : list
List of indices of the contrast objects to plot summary bars for.
results : object (Dataframe)
Dataframe of contrast object comparisons.
ax_to_plot : object
Matplotlib axis object to plot on.
float_contrast : bool
Whether the DABEST plot uses Gardner-Altman or Cummings.
summary_bars_kwargs : dict
Keyword arguments for the summary bars.
ci_type : str
Type of confidence interval to plot.
ticks_to_plot : list
List of indices of the contrast objects.
color_col : str
Column name of the color column.
swarm_colors : list
List of colors used in the plot.
proportional : bool
Whether the data is proportional.
is_paired : bool
Whether the data is paired.
"""
# Begin checks
if not isinstance(summary_bars, list):
raise TypeError("summary_bars must be a list of indices (ints).")
if not all(isinstance(i, int) for i in summary_bars):
raise TypeError("summary_bars must be a list of indices (ints).")
if any(i >= len(results) for i in summary_bars):
raise ValueError("Index {} chosen is out of range for the contrast objects.".format([i for i in summary_bars if i >= len(results)]))
if float_contrast:
raise ValueError("summary_bars cannot be used with Gardner-Altman plots.")
# End checks
else:
summary_xmin, summary_xmax = ax_to_plot.get_xlim()
summary_bars_colors = [summary_bars_kwargs.get('color')]*(len(summary_bars)+1) if summary_bars_kwargs.get('color') is not None else ['black']*(max(summary_bars)+1) if color_col is not None or (proportional and is_paired) or is_paired else swarm_colors
summary_bars_kwargs.pop('color')
for summary_index in summary_bars:
if ci_type == "bca":
summary_ci_low = results.bca_low[summary_index]
summary_ci_high = results.bca_high[summary_index]
else:
summary_ci_low = results.pct_low[summary_index]
summary_ci_high = results.pct_high[summary_index]
summary_color = summary_bars_colors[ticks_to_plot[summary_index]]
ax_to_plot.add_patch(mpatches.Rectangle((summary_xmin,summary_ci_low),summary_xmax+1,
summary_ci_high-summary_ci_low, zorder=-2, color=summary_color, **summary_bars_kwargs))
def contrast_bars_plotter(results: object, ax_to_plot: object, swarm_plot_ax: object,
ticks_to_plot: list, contrast_bars_kwargs: dict, color_col: str,
swarm_colors: list, show_mini_meta: bool, mini_meta_delta: object,
show_delta2: bool, delta_delta: object, proportional: bool, is_paired: bool):
"""
Add contrast bars to the contrast plot.
Parameters
----------
results : object (Dataframe)
Dataframe of contrast object comparisons.
ax_to_plot : object
Matplotlib axis object to plot on.
swarm_plot_ax : object (ax)
Matplotlib axis object of the swarm plot.
ticks_to_plot : list
List of indices of the contrast objects.
contrast_bars_kwargs : dict
Keyword arguments for the contrast bars.
color_col : str
Column name of the color column.
swarm_colors : list
List of colors used in the plot.
show_mini_meta : bool
Whether to show the mini meta-analysis.
mini_meta_delta : object
Mini meta-analysis object.
show_delta2 : bool
Whether to show the delta-delta.
delta_delta : object
delta-delta object.
proportional : bool
Whether the data is proportional.
is_paired : bool
Whether the data is paired.
"""
contrast_means = []
for j, tick in enumerate(ticks_to_plot):
contrast_means.append(results.difference[j])
contrast_bars_colors = [contrast_bars_kwargs.get('color')]*(len(ticks_to_plot)+1) if contrast_bars_kwargs.get('color') is not None else ['black']*(max(ticks_to_plot)+1) if color_col is not None or (proportional and is_paired) or is_paired else swarm_colors
contrast_bars_kwargs.pop('color')
for contrast_bars_x,contrast_bars_y in zip(ticks_to_plot, contrast_means):
ax_to_plot.add_patch(mpatches.Rectangle((contrast_bars_x-0.25,0),0.5, contrast_bars_y, zorder=-1, color=contrast_bars_colors[contrast_bars_x], **contrast_bars_kwargs))
if show_mini_meta:
ax_to_plot.add_patch(mpatches.Rectangle((max(swarm_plot_ax.get_xticks())+2-0.25,0),0.5, mini_meta_delta.difference, zorder=-1, color='black', **contrast_bars_kwargs))
if show_delta2:
ax_to_plot.add_patch(mpatches.Rectangle((max(swarm_plot_ax.get_xticks())+2-0.25,0),0.5, delta_delta.difference, zorder=-1, color='black', **contrast_bars_kwargs))
def swarm_bars_plotter(plot_data: object, xvar: str, yvar: str, ax: object,
swarm_bars_kwargs: dict, color_col: str, swarm_colors: list, is_paired: bool):
"""
Add bars to the raw data plot.
Parameters
----------
plot_data : object (Dataframe)
Dataframe of the plot data.
xvar : str
Column name of the x variable.
yvar : str
Column name of the y variable.
ax : object
Matplotlib axis object to plot on.
swarm_bars_kwargs : dict
Keyword arguments for the swarm bars.
color_col : str
Column name of the color column.
swarm_colors : list
List of colors used in the plot.
is_paired : bool
Whether the data is paired.
"""
# if is_paired:
# swarm_bar_xlocs_adjustleft = {'right': -0.2, 'left': -0.2, 'center': -0.2}
# swarm_bar_xlocs_adjustright = {'right': -0.1, 'left': -0.1, 'center': -0.1}
# else:
# swarm_bar_xlocs_adjustleft = {'right': 0, 'left': -0.4, 'center': -0.2}
# swarm_bar_xlocs_adjustright = {'right': -0.1, 'left': -0.1, 'center': -0.1}
if isinstance(plot_data[xvar].dtype, pd.CategoricalDtype):
swarm_bars_order = pd.unique(plot_data[xvar]).categories
else:
swarm_bars_order = pd.unique(plot_data[xvar])
swarm_means = plot_data.groupby(xvar)[yvar].mean().reindex(index=swarm_bars_order)
swarm_bars_colors = [swarm_bars_kwargs.get('color')]*(len(swarm_bars_order)+1) if swarm_bars_kwargs.get('color') is not None else ['black']*(len(swarm_bars_order)+1) if color_col is not None or is_paired else swarm_colors
swarm_bars_kwargs.pop('color')
for swarm_bars_x,swarm_bars_y,c in zip(np.arange(0,len(swarm_bars_order)+1,1), swarm_means, swarm_bars_colors):
ax.add_patch(mpatches.Rectangle((swarm_bars_x-0.25,0),
0.5, swarm_bars_y, zorder=-1,color=c,**swarm_bars_kwargs))
# %% ../nbs/API/plot_tools.ipynb 6
def swarmplot(
data: pd.DataFrame,
x: str,
y: str,
ax: axes.Subplot,
order: List = None,
hue: str = None,
palette: Union[Iterable, str] = "black",
zorder: float = 1,
size: float = 5,
side: str = "center",
jitter: float = 1,
is_drop_gutter: bool = True,
gutter_limit: float = 0.5,
**kwargs,
):
"""
API to plot a swarm plot.
Parameters
----------
data : pd.DataFrame
The input data as a pandas DataFrame.
x : str
The column in the DataFrame to be used as the x-axis.
y : str
The column in the DataFrame to be used as the y-axis.
ax : axes._subplots.Subplot | axes._axes.Axes
Matplotlib AxesSubplot object for which the plot would be drawn on. Default is None.
order : List
The order in which x-axis categories should be displayed. Default is None.
hue : str
The column in the DataFrame that determines the grouping for color.
If None (by default), it assumes that it is being grouped by x.
palette : Union[Iterable, str]
The color palette to be used for plotting. Default is "black".
zorder : int | float
The z-order for drawing the swarm plot wrt other matplotlib drawings. Default is 1.
dot_size : int | float
The size of the markers in the swarm plot. Default is 20.
side : str
The side on which points are swarmed ("center", "left", or "right"). Default is "center".
jitter : int | float
Determines the distance between points. Default is 1.
is_drop_gutter : bool
If True, drop points that hit the gutters; otherwise, readjust them.
gutter_limit : int | float
The limit for points hitting the gutters.
**kwargs:
Additional keyword arguments to be passed to the swarm plot.
Returns
-------
axes._subplots.Subplot | axes._axes.Axes
Matplotlib AxesSubplot object for which the swarm plot has been drawn on.
"""
s = SwarmPlot(data, x, y, ax, order, hue, palette, zorder, size, side, jitter)
ax = s.plot(is_drop_gutter, gutter_limit, ax, **kwargs)
return ax