-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcharts.py
1758 lines (1531 loc) · 81.9 KB
/
charts.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
# -*- coding: utf-8 -*-
"""
This model helps to build complicated charts. It contains the following functions:
BarCharts - Used for building bar charts. The bar charts can be built as one or more charts in subplots.
StackBarCharts - Used to build a stacked bar chart.
HistCharts - Used for creating histogram charts
pairplotVerCol - Used for comparing every 2 features against the target feature. Return a grid of scatter charts
with X and y as the features and the value as the target features. Charts are made by matplotlib
pairplotVerColSNS - The same as pairplotVerCol but charts made with seaborn library
AnomalyChart - Use this chart to show inertia when using k - means
plotCM - Plotting graphical confusion matrix can also show classification report
ClassicGraphicCM - like plotCM, except it does not get a model and perform a prediction(gets y_pred and classes instead)
PlotFeatureImportance - Plot feature importance and return a dataframe
Show_AucAndROC - Show AUC value, and if a classifier model is given, it also shows the ROC chart
BuildMuliLineChart - Built a chart with two or more lines. The first line is on the left axis, the rest are on the
right axis
PolyFitResults - Build ski-learn curve fit for polynomials until the 5th degree with intercept and without.
(no intercept means that when x=0 also y=0)
Scatter - Used for creating a scatter that uses x and y as the location of the point. It also uses DBSCAN to show
outliers values.
"""
# Imports
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
import sklearn
from scipy.optimize import curve_fit
from sklearn.metrics import r2_score
from sklearn.metrics import mean_squared_error
import matplotlib.colors as mcolors
from matplotlib.colors import colorConverter
from sklearn.cluster import DBSCAN
from pandas.api.types import is_string_dtype, is_numeric_dtype, is_bool_dtype
from sklearn.metrics import confusion_matrix, classification_report, roc_curve, auc
def BarCharts(InpList, TitleList, NumRows=1, NumCol=1, ChartType='bar', ChartSize=(15, 5), Fsize=15, TitleSize=30,
WithPerc=0, XtickFontSize=15, Colorcmap='plasma', Xlabelstr=['', 15], Ylabelstr=['', 15], PadValue=0.3,
LabelPrecision=0, txt2show=[("", 10)], RotAngle=45, SaveCharts=False):
"""
Builds one or more bar charts (use the NumRows and NumCol to determine the grid)
The charts can be customized using the following parameters:
:param InpList: list of dataframes to show
:param TitleList: List of titles to appear on the top of the charts
:param NumRows: Number of rows of charts
:param NumCol: Number of columns of charts
:param ChartType: chart type to show default = bar
:param ChartSize: The size of each chart
:param Fsize: Font size of the data labels
:param TitleSize: Font size of the title
:param WithPerc:
0 or default = data labels + Normalized Percentage
1 = Only Normalized Percentage
2 = Only values
3 = Only Percentage
Normalized Percentage = The value of column/ sum of all columns
:param XtickFontSize: The size of the fonts of the x ticks labels
:param Colorcmap: The color scheme used. Schemas can be found here:
https://matplotlib.org/examples/color/named_colors.html
:param Xlabelstr: Gets a list. The first element is the X-axis label and the second element is the font size
:param Ylabelstr: Gets a list. The first element is the Y-axis label and the second element is the font size
:param PadValue: Float. the amount of space to put around the value label
:param LabelPrecision: integer. The number of digits after the period in the label value
:param txt2show: Gets a list of tuples. Each tuple is for each chart. Every tuple must have 4 values:
(string to show, font size,position correction of x,position correction of y) for example:
txt2show=[('50% of people are men',10,0.1,-0.1)]
The position correction values are in the percentage of the chart.
So if we want to move the textbox 20% (of the chart length) to the right let's put in
the third place the value 0.2
:param RotAngle: The angle for the x-axis labels
:param SaveCharts: If True, then every time this function is called, the chart is also saved as a jpeg
"""
i = 0
j = 0
RemarkAvail = True
if len(txt2show) == 1 and txt2show[0][0] == "":
RemarkAvail = False
if NumRows > 1 or NumCol > 1:
fig, axes = plt.subplots(nrows=NumRows, ncols=NumCol, figsize=ChartSize)
if NumRows == 1 and NumCol == 1:
ax = InpList[0].plot(kind=ChartType, title=TitleList[0], cmap=Colorcmap, figsize=ChartSize)
ax.title.set_size(TitleSize)
ax.xaxis.set_tick_params(labelsize=XtickFontSize, rotation=RotAngle)
ax.set_xlabel(Xlabelstr[0], fontsize=Xlabelstr[1])
ax.set_ylabel(Ylabelstr[0], fontsize=Ylabelstr[1])
if ChartType == 'barh':
MaxVal = __add_Horizontal_value_labels(ax, Fsize, WithPerc, PadValue=PadValue)
else:
MaxVal = __add_value_labels(ax, Fsize, WithPerc, PadValue=PadValue, precision=LabelPrecision)
if RemarkAvail:
__AddTextOnTheCorner(ax, txt2show[0])
elif NumRows == 1:
for i in range(len(InpList)):
ax = InpList[i].plot(kind=ChartType, ax=axes[i], title=TitleList[i], cmap=Colorcmap, figsize=ChartSize)
ax.title.set_size(TitleSize)
ax.xaxis.set_tick_params(labelsize=XtickFontSize, rotation=RotAngle)
ax.set_xlabel(Xlabelstr[0], fontsize=Xlabelstr[1])
ax.set_ylabel(Ylabelstr[0], fontsize=Ylabelstr[1])
# ax.set_xticklabels(labels)
# ax.set_xticklabels(labels)
if ChartType == 'barh':
MaxVal = __add_Horizontal_value_labels(ax, Fsize, WithPerc, PadValue=PadValue)
else:
MaxVal = __add_value_labels(ax, Fsize, WithPerc, PadValue=PadValue, precision=LabelPrecision)
if RemarkAvail:
__AddTextOnTheCorner(ax, txt2show[i])
else:
for counter in range(len(InpList)):
ax = InpList[counter].plot(kind=ChartType, ax=axes[i][j], title=TitleList[counter], cmap=Colorcmap,
figsize=ChartSize)
ax.title.set_size(TitleSize)
ax.xaxis.set_tick_params(labelsize=XtickFontSize, rotation=RotAngle)
ax.set_xlabel(Xlabelstr[0], fontsize=Xlabelstr[1])
ax.set_ylabel(Ylabelstr[0], fontsize=Ylabelstr[1])
# ax.set_xticklabels(labels)
if ChartType == 'barh':
MaxVal = __add_Horizontal_value_labels(ax, Fsize, WithPerc, PadValue=PadValue)
else:
MaxVal = __add_value_labels(ax, Fsize, WithPerc, PadValue=PadValue, precision=LabelPrecision)
if RemarkAvail:
__AddTextOnTheCorner(ax, txt2show[counter])
counter += 1
if j < (NumCol - 1):
j += 1
else:
j = 0
i += 1
if SaveCharts:
__SaveCharts(plt, TitleList[0])
plt.show()
"""Add data labels. Values and percentages"""
def __add_value_labels(ax, Fsize=15, WithPerc=0, spacing=5, PadValue=0.3, precision=0):
"""
Add labels to the end of each bar in a bar chart.
:param ax: (matplotlib.axes.Axes): The matplotlib object containing the axes of the plot to annotate.
:param Fsize: int. The font size
:param WithPerc: int.
0 or default = data labels + Normalized Percentage
1 = Only Normalized Percentage
2 = Only values
3 = Only Percentage
Normalized Percentage = The value of column / sum of all columns
:param spacing: int. The distance between the labels and the bars.
:param PadValue: float The amount of space around the text
:param precision: int. Number of digits after the dot to show in the label
:return: The maximum value
"""
totals = []
for i in ax.patches:
totals.append(i.get_height())
total = sum(totals)
Max = max(totals)
# For each bar: Place a label
for rect in ax.patches:
# Get X and Y placement of label from rect.
y_value = rect.get_height()
# Number of points between bar and label. Change to your liking.
space = spacing
# Vertical alignment for positive values
# If value of bar is negative: Place label below bar
if y_value < 0:
# Invert space to place label below
space *= -1
# Vertically align label at top
# Use Y value as label and format number with one decimal place
strValFormat = "{:,." + str(precision) + "f}"
strPercFormat = "{:." + str(precision) + "%}"
CompleteLabel = strValFormat + '\n' + strPercFormat
label = CompleteLabel.format(y_value, y_value / total)
if WithPerc == 2:
label = strValFormat.format(y_value)
elif WithPerc == 1:
label = strPercFormat.format(y_value / total)
elif WithPerc == 3:
label = strPercFormat.format(y_value)
x_value = rect.get_x() + rect.get_width() / 4
y_value = rect.get_height() / 2
ax.text(x_value, y_value, label, style='italic',
bbox={'facecolor': 'bisque', 'alpha': 1, 'pad': PadValue, 'boxstyle': 'round'}, fontsize=Fsize)
return Max
def __add_Horizontal_value_labels(ax, Fsize=15, WithPerc=0, spacing=5, PadValue=0.3):
"""
Add labels to the end of each bar in a bar chart. For horizontal bars
:param ax (matplotlib.axes.Axes): The matplotlib object containing the plot's axes to annotate.
:param spacing (int): The distance between the labels and the bars.
:param PadValue (float): The amount of space around the text
"""
totals = []
for i in ax.patches:
totals.append(i.get_width())
total = sum(totals)
Max = max(totals)
# For each bar: Place a label
for rect in ax.patches:
# Get X and Y placement of label from rect.
x_value = rect.get_width()
# Number of points between bar and label. Change to your liking.
space = spacing
# Vertical alignment for positive values
# If value of bar is negative: Place label below bar
if x_value < 0:
# Invert space to place label below
space *= -1
# Vertically align label at top
# Use x value as label and format number with one decimal place
label = "{:,.0f}\n{:.0%}".format(x_value, x_value / total)
if WithPerc == 2:
label = "{:,.0f}".format(x_value)
elif WithPerc == 1:
label = "{:.0%}".format(x_value / total)
x_value = rect.get_width() / 2
y_value = rect.get_y() + rect.get_height() / 4
ax.text(x_value, y_value, label, style='italic',
bbox={'facecolor': 'bisque', 'alpha': 1, 'pad': PadValue, 'boxstyle': 'round'}, fontsize=Fsize)
return Max
"""Add the small remark in the corner"""
def __AddTextOnTheCorner(ax, str2Show):
"""
Add a remark on the chart (usually at the corner).
:param ax: A plt object
:param str2Show: tuple: (string to show, font size,position correction of x,position correction of y)
:return: nothing
"""
if len(str2Show) == 4:
text, FontSize, correctionX, correctionY = str2Show
ax.text(0 + correctionX, 1 + correctionY, text, transform=ax.transAxes,
bbox={'facecolor': 'gold', 'alpha': 1, 'pad': 0.3, 'boxstyle': 'round'}, fontsize=FontSize)
def StackBarCharts(InpList, TitleList, NumRows=1, NumCol=1, ChartType='bar', ChartSize=(15, 5), Fsize=10, TitleSize=30,
WithPerc=0, XtickFontSize=15, ColorInt=0, Xlabelstr=['', 15], Ylabelstr=['', 15], PadValue=0.3,
StackBarPer=False, txt2show=[("", 10)], TopValFactor=1.1, SaveCharts=False, SortBySum=0,
CategSortLs=[]):
"""
Parameters:
:param InpList = List of tuples.Dataframes to show. Each element in the list is a tuple.
The tuple looks like this (df,xCol,LegendCol,ValueCol):
df=dataframes
xCol = The name of the column we want to use for the X axis
LegendCol = The name of the column we want to use as a LegendCol
ValueCol = The name of the column we want to use as the values
:param TitleList = List of titles to appear on the top of the charts
:param NumRows = Number of rows of charts
:param NumCol = Number of columns of charts
:param ChartType = chart type to show default = bar
:param ChartSize = The size of each chart
:param Fsize = Font size of the data labels
:param TitleSize = Font size of the title
:param WithPerc =
0 or default = data labels + Percentage
1 = Only percentage
2= Only values
:param XtickFontSize = The size of the fonts of the x ticks labels
:param ColorInt =Currently there are 5 color pallets use (0,1,2,3,4) to run them
:param Xlabelstr = Gets a list. The first element is the X-axis label and the second
element is the font size
:param Ylabelstr = Gets a list. The first element is the Y-axis label and the second element is the font size
:param PadValue = The padding of the data labels bbox
:param StackBarPer = If true, the stack bar is showing 100%.
If false, then it is a regular values stack bar
:param txt2show = List of tuples. Each tuple contains (string,integer,integer,integer).
The text will show on the chart in a box. The second parameter (integer)
is the font size. The third parameter is the correction in the box's location on the X-axis.
The last integer is the correction on the y-axis.
:param TopValFactor: float. The max value of the y-axis is determined by the max value
in the chart * TopValFactor
:param SaveCharts = Bool. If True, then it will save the chart as a jpeg file (used for presentations)
:param SortBySum = int. If 0 then the x-axis is sorted by xCol else it is sorted by the sum of all ValueCol per
xCol just like doing group by xCol, sum by ValueCol, and then sort by the grouped ValueCol
:param CategSortLs = list. If not empty, then the Legend will be sorted according to the list order
(should contain all possible categories). If the data contains new categories it will be
placed at the end
"""
if ColorInt > 4:
ColorInt = 0
i = 0
j = 0
if NumRows > 1 or NumCol > 1:
fig, axes = plt.subplots(nrows=NumRows, ncols=NumCol, figsize=ChartSize)
if NumRows == 1 and NumCol == 1:
ax, maxVal = __CreateStackBarDetails(InpList[0], TitleList[0], PadVal=PadValue, StackBarPer=StackBarPer,
ChartSizeVal=ChartSize, FsizeVal=Fsize, WithPerc=WithPerc,
ColorInt=ColorInt, SortBySum=SortBySum, CategSortLs=CategSortLs)
ax.title.set_size(TitleSize)
ax.xaxis.set_tick_params(labelsize=XtickFontSize, rotation=45)
ax.set_xlabel(Xlabelstr[0], fontsize=Xlabelstr[1])
ax.set_ylabel(Ylabelstr[0], fontsize=Ylabelstr[1])
ax.set_ylim(top=maxVal * TopValFactor)
__AddTextOnTheCorner(ax, txt2show[0])
# elif NumRows == 1:
# for i in range(len(InpList)):
# ax = InpList[i].plot(kind=ChartType, ax=axes[i], title=TitleList[i], stacked=True)
# ax.title.set_size(TitleSize)
# ax.xaxis.set_tick_params(labelsize=XtickFontSize, rotation=45)
# ax.set_xlabel(Xlabelstr[0], fontsize=Xlabelstr[1])
# ax.set_ylabel(Ylabelstr[0], fontsize=Ylabelstr[1])
# # ax.set_xticklabels(labels)
# __add_value_labels(ax, Fsize, WithPerc)
# else:
# for counter in range(len(InpList)):
# ax = InpList[counter].plot(kind=ChartType, ax=axes[i][j], title=TitleList[counter], cmap=Colorcmap,
# figsize=ChartSize, stacked=True)
# ax.title.set_size(TitleSize)
# ax.xaxis.set_tick_params(labelsize=XtickFontSize, rotation=45)
# ax.set_xlabel(Xlabelstr[0], fontsize=Xlabelstr[1])
# ax.set_ylabel(Ylabelstr[0], fontsize=Ylabelstr[1])
# # ax.set_xticklabels(labels)
# __add_value_labels(ax, Fsize, WithPerc)
# counter += 1
# if j < (NumCol - 1):
# j += 1
# else:
# j = 0
# i += 1
if SaveCharts:
__SaveCharts(plt, TitleList[0])
plt.show()
def __list_compare_and_sort(mainList, actualList):
"""
This function is sorting the actualList according to mainList. If there is a member in actualList that
is not in mainList it will be at the end of the returned list
mainList = list. The list that contains the sorting order
actualList = list. The list that need to be sorted
"""
if mainList == actualList:
return mainList
elif set(actualList).issubset(set(mainList)):
return sorted(actualList, key=mainList.index)
else:
newList = mainList.copy()
for item in actualList:
if item not in mainList:
newList.append(item)
return newList
""" Create the stack bar from scratch """
def __CreateStackBarDetails(tupleParam, titleVal, TitleSize=20, PadVal=0.3, StackBarPer=False, ChartSizeVal=(10, 7),
FsizeVal=10, WithPerc=0, ColorInt=0, SortBySum=0, CategSortLs=[]):
"""
xCol = The column we want to be in the x-axis
LegendCol = The column that we want to be the legend
ValueCol = The column that we want to be the values
"""
DataLabelLocation = []
dfOriginal, xCol, LegendCol, ValueCol = tupleParam
# Copy the original dataframe so if we add records it will not have an effect on the original
df = dfOriginal.copy()
# Add records with zero values to a combination of xCol and LegendCol that does not exist in the original dataframe
for xColVal in df[xCol].unique():
for LegendValue in df[LegendCol].unique():
if len(df[(df[xCol] == xColVal) & (df[LegendCol] == LegendValue)]) == 0:
tempDic = {xCol: [xColVal], LegendCol: [LegendValue], ValueCol: [0]}
tmpDF = pd.DataFrame.from_dict(tempDic)
tmpDF.index = [df.index.max() + 1]
df = pd.concat([df, tmpDF], axis=0)
if SortBySum == 0:
df = df.sort_values(by=xCol)
else:
SortDF = df[[xCol, ValueCol]].rename({ValueCol: 'Sort_col'}, axis=1).groupby([xCol]).sum()
df = df.merge(SortDF, on=xCol, how='left')
df = df.sort_values(by=['Sort_col', xCol], ascending=False)
df = df.drop('Sort_col', axis=1)
fig, ax = plt.subplots(figsize=ChartSizeVal)
if len(CategSortLs) > 0:
LegendVal = __list_compare_and_sort(CategSortLs, list(df[LegendCol].drop_duplicates()))
else:
LegendVal = df[LegendCol].drop_duplicates()
margin_bottom = np.zeros(len(df[xCol].drop_duplicates()))
# colors = ["#CC0000", "#FF8000","#FFFF33","#66FFB2","#66FFB2"]
colors = ["#A20101", "#F44E54", "#FF9904", "#FDDB5E", "#BAF1A1", "76AD3B"]
colors2 = ["#3C3C86", "#863C5A", "#865A3C", "#DB6262", "#DCE4FC"]
colors3 = ["#DCE4FC", "#FCE7DC", "#524F48", "#DCfCE4", "#7C6D6E"]
colors4 = ["#4E0035", "#803468", "#B2027A", "#354D01", "#F703AA"]
colors5 = ["#28180D", "#D24647", "#D27D46", "#D2B546", "#E6B798"]
ColorList = [colors, colors2, colors3, colors4, colors5]
for num, Leg in enumerate(LegendVal):
values = list(df[df[LegendCol] == Leg].loc[:, ValueCol])
x = df[df[LegendCol] == Leg].plot.bar(x=xCol, y=ValueCol, ax=ax, stacked=True,
bottom=margin_bottom,
color=ColorList[ColorInt][num], label=Leg,
title=titleVal)
margin_bottom += values
if StackBarPer:
__ReArrangeStackBar2percent(ax)
if StackBarPer:
__add_value_labels2StackBar(x, PadValue=PadVal, WithPerc=3, Fsize=FsizeVal)
ax.set_ylim(0, 1)
else:
__add_value_labels2StackBar(x, PadValue=PadVal, Fsize=FsizeVal, WithPerc=WithPerc)
return ax, max(margin_bottom)
"""This function change the data to be 100% stack bar"""
def __ReArrangeStackBar2percent(ax):
RecTotal = {}
# Update the total for every column
for i in ax.patches:
if i.get_x() in RecTotal:
RecTotal[i.get_x()] += (i.get_height())
else:
RecTotal[i.get_x()] = i.get_height()
# Starts the dic. with zeros per column
RecValues = {}
for i in ax.patches:
RecValues[i.get_x()] = 0
# update the height according to percentage
counter = 0
for i in ax.patches:
PercVal = float(i.get_height() / RecTotal[i.get_x()])
i.set_y(RecValues[i.get_x()])
i.set_height(PercVal)
RecValues[i.get_x()] = RecValues[i.get_x()] + PercVal # keeps in dictionary the last value for the column
return ax
"""This function deals with the labels"""
def __add_value_labels2StackBar(ax, Fsize=12, WithPerc=0, spacing=2, PadValue=0.3, StackBarPer=False):
"""
Add labels to the end of each bar in a bar chart.
Arguments:
ax (matplotlib.axes.Axes): The matplotlib object containing the plot's axes to annotate.
spacing (int): The distance between the labels and the bars.
"""
totals = {}
for i in ax.patches:
if i.get_x() in totals:
totals[i.get_x()] += (i.get_height())
else:
totals[i.get_x()] = i.get_height()
y_value = {}
for i in ax.patches:
y_value[i.get_x()] = 0
# For each bar: Place a label
for rect in ax.patches:
# Get X and Y placement of label from rect.
y_value[rect.get_x()] += rect.get_height()
x_value = rect.get_x() + rect.get_width() / 2
# Number of points between bar and label. Change to your liking.
space = spacing
# Vertical alignment for positive values
va = 'bottom'
# If value of bar is negative: Place label below bar
if y_value[rect.get_x()] < 0:
# Invert space to place label below
space *= -1
# Vertically align label at top
va = 'top'
# Use Y value as label and format number with one decimal place
if WithPerc == 0:
label = "{:,.0f} -> {:.0%}".format(rect.get_height(), rect.get_height() / totals[rect.get_x()])
elif WithPerc == 2:
label = "{:,.0f}".format(rect.get_height())
elif WithPerc == 1:
label = "{:.0%}".format(rect.get_height() / totals[rect.get_x()])
elif WithPerc == 3:
label = "{:.0%}".format(rect.get_height())
x_value = rect.get_x() + rect.get_width() / 4
ax.text(x_value, y_value[rect.get_x()] - 0.5 * rect.get_height(), label, style='italic',
bbox={'facecolor': 'bisque', 'alpha': 1, 'pad': PadValue, 'boxstyle': 'round'}, fontsize=Fsize)
def __SaveCharts(pltObject, FileName):
# noinspection PyBroadException
try:
pltObject.savefig(FileName + '.jpg', dpi=300)
except:
return
def HistCharts(InpList, TitleList, NumRows, NumCol, ChartSize=(25, 15), Fsize=15, TitleSize=30, WithPerc=0, binSize=50,
SaveCharts=False):
"""
Parameters:
InpList = List of dataframes to show
TitleList = List of titles to appear on the top of the charts
NumRows = Number of rows of charts
NumCol = Number of columns of charts
ChartSize = The size of each chart
Fsize = Font size of the data labels
TitleSize = Font size of the title
WithPerc =
0 or default = data labels + Percentage
1 = Only percentage
2= Only values
binSize = int. How many bins to use for the histogram
SaveCharts = Bool. If True, then it will save the chart as a jpeg file (use for presentations)
"""
i = 0
j = 0
empty = pd.DataFrame.from_dict({'a': (5, 4)})
if NumRows > 1 and NumCol > 1:
fig, axes = plt.subplots(nrows=NumRows, ncols=NumCol, figsize=ChartSize)
if NumRows == 1 and NumCol == 1:
if type(InpList[0]) != type(empty):
InpList[0] = pd.DataFrame(InpList[0])
ax = InpList[0].plot(kind='hist', title=TitleList[0], cmap='plasma', bins=binSize, figsize=ChartSize)
ax.title.set_size(TitleSize)
ax.xaxis.set_tick_params(labelsize=10, rotation=45)
# __add_value_labels(ax,Fsize,WithPerc)
elif NumRows == 1:
for i in range(len(InpList)):
ax = InpList[i].plot(kind='hist', ax=axes[i], title=TitleList[i], cmap='plasma', bins=binSize,
figsize=ChartSize)
ax.title.set_size(TitleSize)
ax.xaxis.set_tick_params(labelsize=10, rotation=45)
# __add_value_labels(ax,Fsize,WithPerc)
else:
for counter in range(len(InpList)):
ax = InpList[counter].plot(kind='hist', ax=axes[i][j], title=TitleList[counter], cmap='plasma',
bins=binSize)
ax.title.set_size(TitleSize)
ax.xaxis.set_tick_params(labelsize=10, rotation=45)
# __add_value_labels(ax,Fsize,WithPerc)
counter += 1
if j < (NumCol - 1):
j += 1
else:
j = 0
i += 1
if SaveCharts:
__SaveCharts(plt, TitleList[0])
plt.show()
def pairplotVerCol(DF, TargetCol, Figsize=(15, 5), Xlabelstr=15, Ylabelstr=15, RotAngle=45, C='DarkBlue', S=30):
"""
Show a chart for each feature against the target column. Using matplotlib.
:param DF: Dataframe as an input.
:param TargetCol: string. The target column.
:param Figsize: tuple, The figure size.
:param Xlabelstr: string. The label of the x-axis.
:param Ylabelstr: string. The label of the y-axis.
:param RotAngle: integer. The rotation of the labels on the x-axis.
:param C: In case of a scatter plot. Color of data points. Can get a name of color, an RGB, or even a column name.
See scatter matplotlib documentation
:param S: In the case of a scatter plot, how big should the points be. See scatter matplotlib documentation
:return: nothing
"""
warnings.filterwarnings("ignore", message="More than 20 figures have been opened")
for col in DF.drop([TargetCol], axis=1).columns:
# noinspection PyBroadException
try:
tempDF = DF[[col, TargetCol]]
if is_bool_dtype(DF[col].dtype):
ax = tempDF.boxplot(by=col, column=TargetCol, figsize=Figsize)
elif is_numeric_dtype(DF[col].dtype):
ax = tempDF.plot(col, TargetCol, kind='scatter', figsize=Figsize, c=C, s=S)
elif is_string_dtype(DF[col].dtype):
ax = tempDF.boxplot(by=col, column=TargetCol, figsize=Figsize)
# From here it is common for all data types
ax.set_title(col + ' ver. ' + TargetCol)
ax.xaxis.set_tick_params(labelsize=15, rotation=RotAngle)
ax.yaxis.set_tick_params(labelsize=15)
ax.set_ylabel(TargetCol, fontsize=18)
ax.set_xlabel(col, fontsize=18)
ax.title.set_size(18)
ax.plot()
except:
print('Not able to show a chart for column: ' + str(col) + '\t Data type:' + str(DF[col].dtype))
def pairplotVerColSNS(DF, TargetCol, Figsize=(15, 5), Xlabelstr=15, Ylabelstr=15, RotAngle=45, S=50,
UseTargetAsHue=False, ChangeAxis=False, Savepng=False):
"""
Show a chart for each feature against the target column. Using matplotlib.
:param DF: Dataframe as an input
:param TargetCol: string. The target column.
:param Figsize: tuple, The figure size.
:param Xlabelstr: string. The label of the x-axis.
:param Ylabelstr: string. The label of the y-axis.
:param RotAngle: integer. The rotation of the labels on the x-axis.
:param S: In the case of a scatter plot: how big should the points be.
:param UseTargetAsHue: bool. If true, then use the target column value as the chart's hue value.
(determine the colors based on the values)
:param ChangeAxis: bool. If false, then f(x) is on the y-axis (default) if true, then change the axis so f(x)
is on the x-axis
:param Savepng: bool. If True, then every chart will be saved in png format
:return: nothing
"""
warnings.filterwarnings("ignore", message="More than 20 figures have been opened")
for col in DF.drop([TargetCol], axis=1).columns:
plt.figure(figsize=Figsize)
plt.title(col + ' ver. ' + TargetCol)
# Find out which column should be on which axis
X = col
Y = TargetCol
if ChangeAxis:
Y = col
X = TargetCol
# noinspection PyBroadException
try:
tempDF = DF[[col, TargetCol]]
if is_bool_dtype(DF[col].dtype):
ax = sns.boxplot(x=X, y=Y, data=tempDF)
elif is_numeric_dtype(DF[col].dtype):
if UseTargetAsHue:
ax = sns.scatterplot(x=X, y=Y, data=tempDF, s=S, hue=TargetCol)
else:
ax = sns.scatterplot(x=X, y=Y, data=tempDF, s=S)
elif is_string_dtype(DF[col].dtype):
ax = sns.boxplot(x=X, y=Y, data=tempDF)
if Savepng:
plt.savefig(col + ' ver ' + TargetCol + '.png')
except:
print('Not able to show a chart for column: ' + str(col) + '\t Data type:' + str(DF[col].dtype))
"""# Anomaly chart"""
def AnomalyChart(X, model, ylim=(-7, 7), xlim=(-7, 7), FigSize=(10, 10)):
"""
The function gets a np array X and an outlier model, AFTER FITTING, such as:
Isolation forest
Local Outlier Factor (LOF)
One-Class Svm
It draws a contour chart with the outliers as black dots.
Parameters:
X dataframe. The input dataframe
model model. one of the 3 models above, alreadt fitted.
ylim,xlim tuple. The axis limitation for y and x
FigSize tuple. The figure size in inches
"""
n = int(model.get_params()['contamination'] * len(X))
xx1, xx2 = np.meshgrid(np.linspace(xlim[0], xlim[1], 100),
np.linspace(ylim[0], ylim[1], 100))
Z = model.decision_function(np.c_[xx1.ravel(), xx2.ravel()]).reshape(xx1.shape)
fig, ax = plt.subplots(1, 1, figsize=FigSize)
# Background colors
ax.contourf(xx1, xx2, Z,
levels=np.linspace(Z.min(), 0, 6),
cmap=plt.cm.Blues_r)
# Threshold contour
a = ax.contour(xx1, xx2, Z,
levels=[0],
linewidths=2, colors='red')
# Inliers coloring
ax.contourf(xx1, xx2, Z,
levels=[0, Z.max()],
colors='orange')
# Inliers scatter
b = ax.scatter(X.iloc[:-n, 0], X.iloc[:-n, 1],
c='white', s=30, edgecolor='k')
# Outliers scatter
c = ax.scatter(X.iloc[-n:, 0], X.iloc[-n:, 1],
c='black', s=30, edgecolor='k')
ax.set_xlim(xlim)
ax.set_ylim(ylim)
plt.show()
"""# Inertia elbow chart"""
def __calc_inertia(k, model, data):
"""
Used for fit the model to k clusters
k int. The number of clusters to use by the model
model model. The inertia model
data dataframe. The input dataframe
Returns the odel.inertia_ for each k input
"""
model = model(n_clusters=k).fit(data)
return model.inertia_
def InertiaElbow(data, model, StartFrom=1, EndAt=10, AddLabels=False):
"""
Gets a dataframe and the inertia modeland create a chart to help find where the "elbow" is.
data dataframe. The input dataframe
model model. The inertia model
StartFrom int. This is the minimum k value
EndAt int. This is the maximum k value
AddLabels bool. If true, then add labels for each point
Returns nothing
"""
inertias = [(k, __calc_inertia(k, model, data)) for k in range(StartFrom, EndAt)]
plt.figure(figsize=(10, 5))
plt.plot(*zip(*inertias), linewidth=3, marker='*', markersize=15, markerfacecolor='red', markeredgecolor='#411a20')
plt.title('Inertia vs. k', fontdict={'fontsize': 20, 'color': '#411a20'})
plt.xlabel('k', fontdict={'fontsize': 20, 'color': '#411a20'})
plt.ylabel('Inertia', fontdict={'fontsize': 20, 'color': '#411a20'})
if AddLabels:
for i, j in inertias:
plt.annotate(str(int(j)), xy=(i, j), xytext=(i + 0.2, j + 0.2))
# Confusion matrix
def plotCM(X, y_true, modelName, normalize=False, title=None, cmap=plt.cm.Blues, precisionVal=2, titleSize=15,
fig_size=(7, 5), InFontSize=15, LabelSize=15, ClassReport=True, RemoveColorBar=False, ShowAUCVal=False,
pos_label=1):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
Input:
X: The input dataframe
y_true: Target column
modelName: The model used to predict AFTER FIT
normalize: If True, then normalize the by row
title: string. Chart title
cmap: color map
precisionVal: Precision values (0.00 = 2)
titleSize: Title font size
fig_size: Figure size
InFontSize: The font of the values inside the table
LabelSize: Label font size (the classes names on the axes)
ClassReport: If true, add a classification report at the bottom
RemoveColorBar: bool. If True, then don't show the color bar
ShowAUCVal: bool. If true, then show the AUC value and ROC chart
pos_label: str. The positive value for calculating the AUC
"""
if not title:
if normalize:
title = 'Normalized confusion matrix'
else:
title = 'Confusion matrix'
y_pred = modelName.predict(X)
# Compute confusion matrix
cm = confusion_matrix(y_true, y_pred)
# Only use the labels that appear in the data
classes = modelName.classes_
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
# print("Normalized confusion matrix")
# else:
# print('Confusion matrix, without normalization')
fig, ax = plt.subplots(figsize=fig_size)
im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
if not RemoveColorBar:
ax.figure.colorbar(im, ax=ax)
# We want to show all ticks...
ax.set(xticks=np.arange(cm.shape[1]),
yticks=np.arange(cm.shape[0]),
# ... and label them with the respective list entries
xticklabels=classes, yticklabels=classes,
title=title
)
ax.xaxis.set_tick_params(labelsize=LabelSize)
ax.yaxis.set_tick_params(labelsize=LabelSize)
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
# Loop over data dimensions and create text annotations.
fmt = '.' + str(precisionVal) + 'f' if normalize else 'd'
thresh = cm.max() / 2.
for i in range(cm.shape[0]):
for j in range(cm.shape[1]):
ax.text(j, i, format(cm[i, j], fmt),
ha="center", va="center",
color="white" if cm[i, j] > thresh else "black", fontdict={'fontsize': InFontSize})
fig.tight_layout()
plt.xlim(-0.5, len(np.unique(y_true)) - 0.5)
plt.ylim(len(np.unique(y_true)) - 0.5, -0.5)
plt.xlabel(xlabel='Predicted label', fontdict={'fontsize': 15, 'color': '#411a20'})
plt.ylabel(ylabel='True label', fontdict={'fontsize': 15, 'color': '#411a20'})
plt.title(title + '\n', fontdict={'fontsize': titleSize, 'color': '#411a20'})
plt.show()
if ClassReport:
print('\n\nClassification_report\n*********************\n')
print(classification_report(y_true=y_true,
y_pred=y_pred))
if ShowAUCVal:
Show_AucAndROC(y_true, y_pred, pos_label, modelName, X)
def ClassicGraphicCM(y_pred, y_true, ModelClasses, normalize=False, title=None, cmap=plt.cm.Blues, precisionVal=2,
titleSize=15, fig_size=(7, 5), InFontSize=15, LabelSize=15, ClassReport=True, ReturnAx=False,
RemoveColorBar=False, ShowAUCVal=False, pos_label=1):
"""
This function prints and plots the confusion matrix. WITHOUT using the model (no prediction needed)
Normalization can be applied by setting `normalize=True`.
Input:
y_Pred: Prediction array
y_true: Target array
ModelClasses: A list of classes as they appear in model.classes_
normalize: If True, then normalize the by row
title: Chart title
cmap: color map
precisionVal: Precision values (0.00 = 2)
titleSize: Title font size
fig_size: Figure size
InFontSize: The font of the values inside the table
LabelSize: Label font size (the classes names on the axes)
ClassReport: If true, add a classification report at the bottom
ReturnAx: Bool. If true, then don't show the confusion matrix and return the figure
RemoveColorBar: bool. If True, then don't show the color bar
ShowAUCVal: bool. If true, then show the AUC value
pos_label: str. The positive value for calculating the AUC
"""
if not title:
if normalize:
title = 'Normalized confusion matrix'
else:
title = 'Confusion matrix'
# Compute confusion matrix
cm = confusion_matrix(y_true, y_pred)
# Only use the labels that appear in the data
classes = ModelClasses
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
# print("Normalized confusion matrix")
# else:
# print('Confusion matrix, without normalization')
fig, ax = plt.subplots(figsize=fig_size)
im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
if not RemoveColorBar:
ax.figure.colorbar(im, ax=ax)
# We want to show all ticks...
ax.set(xticks=np.arange(cm.shape[1]),
yticks=np.arange(cm.shape[0]),
# ... and label them with the respective list entries
xticklabels=classes, yticklabels=classes,
title=title
)
ax.xaxis.set_tick_params(labelsize=LabelSize)
ax.yaxis.set_tick_params(labelsize=LabelSize)
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
# Loop over data dimensions and create text annotations.
fmt = '.' + str(precisionVal) + 'f' if normalize else 'd'
thresh = cm.max() / 2.
for i in range(cm.shape[0]):
for j in range(cm.shape[1]):
ax.text(j, i, format(cm[i, j], fmt),
ha="center", va="center",
color="white" if cm[i, j] > thresh else "black", fontdict={'fontsize': InFontSize})
fig.tight_layout()
plt.xlim(-0.5, len(np.unique(y_true)) - 0.5)
plt.ylim(len(np.unique(y_true)) - 0.5, -0.5)
plt.xlabel(xlabel='Predicted label', fontdict={'fontsize': 15, 'color': '#411a20'})
plt.ylabel(ylabel='True label', fontdict={'fontsize': 15, 'color': '#411a20'})
plt.title(title + '\n', fontdict={'fontsize': titleSize, 'color': '#411a20'})
if ReturnAx:
return plt
else:
plt.show()
if ClassReport:
print('\n\nClassification_report\n*********************\n')
print(classification_report(y_true=y_true,
y_pred=y_pred))
if ShowAUCVal:
Show_AucAndROC(y_true, y_pred, pos_label)
def Show_AucAndROC(y_true, y_pred, pos_label=1, cls=None, X=None):
"""
It shows the AUC value, and if a classification model is given, it also offers a plot of the ROC curve.
Source code: https://medium.com/@kunanba/what-is-roc-auc-and-how-to-visualize-it-in-python-f35708206663
:param cls: classifier model. If no classifier is given, then it will only show the AUC value
:param y_true: The actual values (ground true)
:param y_pred: The predicted values
:param pos_label: The label that is considered a positive value
:param X: array. Used to predict proba
:return: nothing
"""
fpr, tpr, thresholds = roc_curve(y_true, y_pred, pos_label=pos_label)
result = auc(fpr, tpr)
print('\n\n AUC value: ' + str(result))
if cls is not None:
probas = cls.predict_proba(X)[:, 1]
roc_values = []
for thresh in np.linspace(0, 1, 100):
preds = __get_preds(thresh, probas)
tn, fp, fn, tp = confusion_matrix(y_true, preds).ravel()
tpr = tp / (tp + fn)
fpr = fp / (fp + tn)
roc_values.append([tpr, fpr])
tpr_values, fpr_values = zip(*roc_values)
fig, ax = plt.subplots(figsize=(10, 7))
ax.plot(fpr_values, tpr_values)
ax.plot(np.linspace(0, 1, 100),
np.linspace(0, 1, 100),
label='baseline',
linestyle='--')
plt.title('Receiver Operating Characteristic Curve', fontsize=18)
plt.ylabel('TPR', fontsize=16)
plt.xlabel('FPR', fontsize=16)
plt.legend(fontsize=12)
def __get_preds(threshold, probabilities):
return [1 if prob > threshold else 0 for prob in probabilities]
def PlotFeatureImportance(X, model, TopFeatures=10, ShowChart=True, Label_Precision=2):
"""
Show feature importance as a chart and returns a dataframe
:param X: dataframe. The dataframe used for the fitting