-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathM_GraphClasses.py
1512 lines (1166 loc) · 59 KB
/
M_GraphClasses.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
import sys
from turtle import width
import pandas as pd
import numpy as np
from PySide6.QtGui import QAction
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QApplication, QVBoxLayout, QWidget, QMenu, QFileDialog, QSizePolicy, QLayout
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.cm as cm
import matplotlib.animation as animation
from matplotlib.font_manager import FontProperties
class MultiHorizontalBarGraphWidget(QWidget):
def __init__(self, categories, values, xmax):
super().__init__()
self.categories = categories
self.values = values
self.xmax = xmax
self.initUI()
def initUI(self):
# Create a figure and axes
self.fig = Figure(constrained_layout=True)
self.ax = self.fig.add_subplot(111)
# Fix the X values between 0 and 100%
self.ax.set_xlim(0, self.xmax)
# Set the x-axis tick intervals to 25 and show % sign
if self.xmax == 100:
self.ax.set_xticks(range(0, 101, 25))
self.ax.set_xticklabels([f"{tick}%" for tick in range(0, 101, 25)])
elif self.xmax == 1:
self.ax.set_xticks(np.arange(0, 1.01, 0.25))
self.ax.set_xticklabels([f"{tick}" for tick in np.arange(0, 1.01, 0.25)])
self.ax.xaxis.set_tick_params(labelsize = "small")
self.ax.yaxis.set_tick_params(labelsize = "small")
# Set the number of y values
self.ax.set_yticks(range(len(self.categories)))
self.ax.set_yticklabels(self.categories, weight ='bold')
# Hide the top and bottom axis lines
self.ax.spines['top'].set_visible(False)
self.ax.spines['bottom'].set_visible(False)
# Hide vertical gridlines
self.ax.grid(False)
# Set the background color with 50% transparency
self.fig.patch.set_facecolor("AliceBlue")
self.fig.patch.set_alpha(1)
# Set the facecolor to none
self.ax.set_facecolor('none')
# Create a colormap and normalize the values
cmap = cm.get_cmap('RdYlGn')
norm = plt.Normalize(0, self.xmax)
#colors = [cmap(norm(value)) if value != '' else 'darkgrey' for value in self.values]
# Create a values bar
self.bars = self.ax.barh(self.categories, self.values, height = 0.3, alpha= 1, color = cmap(norm(self.values)), zorder = 1)
# Create a light grey bar as a background behind the data bars
self.ax.barh(self.categories, self.xmax, color='lightgrey', edgecolor = 'black', linewidth = 0.5, height = 0.3, alpha = 0.2, zorder=0)
# Create the canvas to display the plot
self.canvas = FigureCanvas(self.fig)
self.canvas.setStyleSheet("background-color: transparent;")
# Connect the mouse motion event
self.canvas.mpl_connect('motion_notify_event', self.on_bar_hover)
# Set the layout
layout = QVBoxLayout()
layout.addWidget(self.canvas)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self.setLayout(layout)
# Initialize the text element for the value inside the bars
self.text = None
def animateBars(self):
def update(frame):
progress = frame / self.frames * self.xmax
max_value = max(self.values)
for bar, w in zip(self.bars, self.values):
width = min(progress , w)
bar.set_width(width)
self.canvas.draw()
if progress >= max_value:
self.animation.event_source.stop()
self.frames = 100
self.animation = animation.FuncAnimation(self.fig, update, frames = self.frames, interval= 0.2)
self.canvas.draw_idle()
def on_bar_hover(self, event):
if event.inaxes == self.ax:
for i, bar in enumerate(self.bars):
if bar.contains(event)[0]:
# Set the transparency of the hovered bar to 1.0
#bar.set_alpha(1)
# Add a contour
bar.set_edgecolor('darkblue')
bar.set_linewidth(1)
# Get the value of the hovered bar
value = self.values[i]
# Remove the previous text element if it exists
if self.text:
self.text.remove()
# Add the text for the value inside the bar
if self.xmax == 100:
self.text = self.ax.text(value + 1, i, f"{str(value)}%", va='center')
elif self.xmax == 1:
self.text = self.ax.text(value + 0.01, i, f"{str(value)}", va='center')
else:
# Set the transparency of non-hovered bars to 0.5
bar.set_alpha(0.5)
bar.set_edgecolor('none')
# Remove the text element if it exists and the mouse is not over any bar
if not any(bar.contains(event)[0] for bar in self.bars):
for i, bar in enumerate(self.bars):
bar.set_alpha(1)
if self.text:
self.text.remove()
self.text = None
self.canvas.draw()
class SingleHorizontalBarGraphWidget(QWidget):
def __init__(self, value, xmax):
super().__init__()
self.value = value
self.xmax = xmax
self.initUI()
def initUI(self):
# Create a figure and axes
self.fig = Figure(constrained_layout=True)
self.ax = self.fig.add_subplot(111)
# Fix the X values between 0 and 100%
self.ax.set_xlim(0, self.xmax)
# Set the x-axis tick intervals to 25 and show % sign
if self.xmax == 100:
self.ax.set_xticks(range(0, 101, 25))
#self.ax.set_xticklabels([f"{tick}%" for tick in range(0, 101, 25)])
elif self.xmax == 1:
self.ax.set_xticks(np.arange(0, 1.01, 0.25))
#self.ax.set_xticklabels([f"{tick}" for tick in np.arange(0, 1.01, 0.25)])
self.ax.set_xticklabels([])
self.ax.xaxis.set_tick_params(labelsize = "small")
self.ax.yaxis.set_tick_params(labelsize = "small")
# Set the number of y values
self.ax.set_yticks(range(1))
self.ax.set_yticklabels(())
# Hide the top and bottom axis lines
self.ax.spines['top'].set_visible(False)
self.ax.spines['bottom'].set_visible(False)
# Hide vertical gridlines
self.ax.grid(False)
# Set the background color with 50% transparency
self.fig.patch.set_facecolor("AliceBlue")
self.fig.patch.set_alpha(0)
# Set the facecolor to none
self.ax.set_facecolor('none')
# Create a colormap and normalize the values
cmap = cm.get_cmap('RdYlGn')
norm = plt.Normalize(0, self.xmax)
#colors = [cmap(norm(value)) if value != '' else 'darkgrey' for value in self.values]
# Create a values bar
self.bar = self.ax.barh(1, self.value, alpha= 1, color = cmap(norm(self.value)), zorder = 1)
# Create a light grey bar as a background behind the data bars
self.ax.barh(1, self.xmax, color='lightgrey', edgecolor = 'black', linewidth = 0.5, alpha = 0.2, zorder=0)
# Create the canvas to display the plot
self.canvas = FigureCanvas(self.fig)
self.canvas.setStyleSheet("background-color: transparent;")
# Connect the mouse motion event
self.canvas.mpl_connect('motion_notify_event', self.on_bar_hover)
def on_bar_hover(self, event):
if event.inaxes == self.ax:
for i, bar in enumerate(self.bars):
if bar.contains(event)[0]:
# Set the transparency of the hovered bar to 1.0
#bar.set_alpha(1)
# Add a contour
bar.set_edgecolor('darkblue')
bar.set_linewidth(1)
# Get the value of the hovered bar
value = self.values[i]
# Remove the previous text element if it exists
if self.text:
self.text.remove()
# Add the text for the value inside the bar
if self.xmax == 100:
self.text = self.ax.text(value + 1, i, f"{str(value)}%", va='center')
elif self.xmax == 1:
self.text = self.ax.text(value + 0.01, i, f"{str(value)}", va='center')
else:
# Set the transparency of non-hovered bars to 0.5
bar.set_alpha(0.5)
bar.set_edgecolor('none')
# Remove the text element if it exists and the mouse is not over any bar
if not any(bar.contains(event)[0] for bar in self.bars):
for i, bar in enumerate(self.bars):
bar.set_alpha(1)
if self.text:
self.text.remove()
self.text = None
self.canvas.draw()
# Set the layout
layout = QVBoxLayout()
layout.addWidget(self.canvas)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self.setLayout(layout)
# Initialize the text element for the value inside the bars
self.text = None
class SingleHorizontalBarGraph(QWidget):
def __init__(self, data: list, colors:list, xmax: int):
super().__init__()
self.data = data.copy()
self.colors = colors.copy()
self.xmax = xmax
self.initUI()
def initUI(self):
# Create a figure and axes
# self.fig = Figure(constrained_layout=True)
self.fig = Figure(layout='none')
# Set the background color with 50% transparency
self.fig.patch.set_facecolor("none")
#self.fig.patch.set_alpha(0) #transparent ?
self.ax = self.fig.add_subplot(111)
self.ax.set_facecolor('none')
# Fix the X values between 0 and xmax
self.ax.set_xlim(0, self.xmax)
# Set the x-axis tick intervals to 25 and show % sign
if self.xmax == 100:
self.ax.set_xticks(range(0, 101, 25))
#self.ax.set_xticklabels([f"{tick}%" for tick in range(0, 101, 25)])
elif self.xmax == 1:
self.ax.set_xticks(np.arange(0, 1.01, 0.25))
#self.ax.set_xticklabels([f"{tick}" for tick in np.arange(0, 1.01, 0.25)])
self.ax.set_xticklabels([])
self.ax.xaxis.set_tick_params(labelsize = "small")
self.ax.yaxis.set_tick_params(labelsize = "small")
# Set the number of y values
self.ax.set_yticks(range(1))
self.ax.set_yticklabels(())
# Hide the top and bottom axis lines
self.ax.spines['top'].set_visible(False)
self.ax.spines['bottom'].set_visible(False)
# Hide vertical gridlines
self.ax.grid(False)
# Create a colormap and normalize the values
cmap = cm.get_cmap('RdYlGn')
norm = plt.Normalize(0, self.xmax)
z_order = list(range(len(self.data), 0, -1))
for index, color in enumerate(self.colors):
if color == '':
self.colors[index] = cmap(norm(self.data[index]))
left = 0
for i, data in enumerate(self.data):
if i == 0:
z_order = 2
else:
z_order = 1
bar = self.ax.barh(1, data, color = self.colors[i], alpha = 1, left = left, zorder = z_order)
left += data
if i == 0:
self.bar = bar
# Create the canvas to display the plot
self.canvas = FigureCanvas(self.fig)
self.canvas.setStyleSheet("background-color: transparent;")
# Connect the mouse motion event
self.canvas.mpl_connect('motion_notify_event', self.on_bar_hover)
# Set the layout
layout = QVBoxLayout()
layout.addWidget(self.canvas)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self.setLayout(layout)
# Initialize the text element for the value inside the bars
self.text = None
def animateBars(self):
def update(frame):
progress = frame / self.frames * self.xmax
max_value = max(self.value)
for bar, w in zip(self.bar, self.value):
width = min(progress , w)
bar.set_width(width)
self.canvas.draw()
if progress >= max_value:
self.animation.event_source.stop()
self.frames = 100
self.animation = animation.FuncAnimation(self.fig, update, frames = self.frames, interval= 0.2)
self.canvas.draw_idle()
def on_bar_hover(self, event):
if event.inaxes == self.ax:
for i, bar in enumerate(self.bar):
if bar.contains(event)[0]:
# Add a contour
bar.set_edgecolor('darkblue')
bar.set_linewidth(1)
# Get the value of the hovered bar
value = bar._width
# Remove the previous text element if it exists
if self.text:
self.text.remove()
# Add the text for the value inside the bar
normvalue = value / self.xmax
labelpad = 0.025 * self.xmax
if self.xmax == 1:
label = f"{round(value, 2)}"
elif self.xmax == 100:
label = f"{round(value, 1)}%"
if normvalue <= 0.1:
self.text = self.ax.text(value + labelpad, 1, label , va='center', ha = "left")
else:
self.text = self.ax.text(value -labelpad, 1, label , va='center', ha = "right")
else:
bar.set_edgecolor('none')
if self.text:
self.text.remove()
self.text = None
else:
for bar in self.bar:
bar.set_edgecolor('none')
if self.text:
self.text.remove()
self.text = None
self.canvas.draw()
class CircularGraphWidget(QWidget):
def __init__(self, data: list, colors: list):
super().__init__()
self.data = data
self.colors = colors
self.category = categorizeResilience(self.data[0])
self.fontsize = int(self.width() / 50)
self.initUI()
def initUI(self):
self.fig = Figure(constrained_layout=True)
self.ax = self.fig.add_subplot(111)
# Set the self.axis limits and remove the self.axis labels
self.ax.set_xlim(-1.1, 1.1)
self.ax.set_ylim(-1.1, 1.1)
self.ax.axis("off")
self.ax.set_aspect('equal')
# Set the background color with 50% transparency
self.fig.patch.set_facecolor("AliceBlue")
self.fig.patch.set_alpha(0)
# Get the colors for the wedges
self.cmap = cm.get_cmap('RdYlGn')
self.norm = plt.Normalize(0, 1)
self.WedgeRadius = 1
self.WedgeWidth = 0.3
# Create the grey back wedge:
# wedge_empty = patches.Wedge(center = (0, 0), r = self.WedgeRadius, theta1 = 0, theta2= 360, width = self.WedgeWidth, facecolor='lightgrey', alpha = 0.2, edgecolor = 'black', linewidth = 0.5)
# self.ax.add_patch(wedge_empty)
for index, color in enumerate(self.colors):
if color == '':
self.colors[index] = self.cmap(self.norm(self.data[index]))
# Create the filled part of the circular bar
left = 0
for i, data in enumerate(self.data):
if not np.isnan(data):
if i == 0:
z_order = 2
edge_color = '#34495E'
else:
z_order = 1
edge_color = 'none'
wedge_filled = patches.Wedge(center = (0, 0), r = self.WedgeRadius,
theta1 = left, theta2 = left + 360 * data,
width = self.WedgeWidth, facecolor = self.colors[i],
zorder = z_order, edgecolor = edge_color, linewidth = 1)
left += 360 * data
self.ax.add_patch(wedge_filled)
if i == 0:
self.wedge_filled = wedge_filled
# Create a new axes for the text label
self.text_ax = self.fig.add_axes([0, 0, 1, 1], zorder=1)
self.text_ax.axis('off')
# Create the central label
self.text_label = self.text_ax.text(0.5, 0.5, f'{self.category}\n{self.data["Rating"]:.2f}', ha='center', va='center', fontsize = self.fontsize)
# Create the canvas to display the plot
self.canvas = FigureCanvas(self.fig)
self.canvas.setStyleSheet("background-color: transparent;")
# Connect the mouse motion event
#self.canvas.mpl_connect('motion_notify_event', self.on_bar_hover)
# Set the layout
layout = QVBoxLayout()
layout.addWidget(self.canvas)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self.setLayout(layout)
# Initialize text for on_bar_hover
self.text_value = None
def animateWedge(self):
self.wedge_filled.set_theta2(0)
self.wedge_filled.set_facecolor('None')
self.text_label.set_fontsize(0)
def update(frame):
# Calculate the normalized value based on the frame
norm_value = frame / 100
#self.frames
# Calculate the end angle for the filled part of the circular bar
end_angle = 360 * norm_value
# Update the theta2 value of the filled part of the circular bar
self.wedge_filled.set_theta2(end_angle)
self.wedge_filled.set_facecolor(self.cmap(self.norm(norm_value)))
if self.data[0] > 0:
self.text_label.set_fontsize(norm_value * self.fontsize/self.data[0])
else:
self.text_label.set_fontsize(self.fontsize)
if norm_value >= self.data[0]:
#self.canvas.draw()
self.animation.event_source.stop()
# Connect the mouse motion event
#self.canvas.mpl_connect('motion_notify_event', self.on_bar_hover)
self.canvas.draw()
self.frames = 150 # Number of frames in the animation
self.canvas.draw_idle()
self.animation = animation.FuncAnimation(self.fig, update, frames=self.frames, interval=0.2)
# Initialize text for on_bar_hover
self.text_value = None
def on_bar_hover(self, event):
if self.wedge_filled.contains(event)[0]:
# Add a contour
self.wedge_filled.set_edgecolor('darkblue')
self.wedge_filled.set_linewidth(1)
# Get the value of the hovered bar
value = self.wedge_filled.theta2
# Remove the previous text element if it exists
if self.text_value:
self.text_value.remove()
label = f"{(value):.2f}"
# Calculate the angular position for the text label
end_angle = 360 * value
padding = self.WedgeWidth / 2
label_padding_angle = -10
if end_angle <= 25:
label_padding_angle = - label_padding_angle
if end_angle <= 90:
text_angle = end_angle - label_padding_angle - 90
elif end_angle <= 180:
text_angle = -(180 - end_angle - label_padding_angle) + 90
elif end_angle <= 270:
text_angle = -(180 - end_angle - label_padding_angle) - 90
else:
text_angle = end_angle - label_padding_angle + 90
# Calculate the (x, y) coordinates for the text
x = (self.WedgeRadius - padding) * np.cos(np.deg2rad(end_angle + label_padding_angle))
y = (self.WedgeRadius - padding) * np.sin(np.deg2rad(end_angle + label_padding_angle))
# Add the text to the plot using the text method of the Axes object
self.text_value = self.ax.text(x, y, label, rotation = text_angle, ha='center', va='center', size=self.fontsize/1.5, color='black')
else:
self.wedge_filled.set_edgecolor('none')
if self.text_value:
self.text_value.remove()
self.text_value = None
self.canvas.draw()
def categorizeResilience(value):
categorization = {
'Bad': (0.00, 0.30),
'Insufficient': (0.30, 0.55),
'Acceptable': (0.55, 0.75),
'Good': (0.75, 0.90),
'Great': (0.90, 1.00)
}
if value == 1:
return "Great"
else:
for category, (lower,upper) in categorization.items():
if lower <= value < upper:
resilienceClass = category
return resilienceClass
class ScatterPerformancePlotWidget(QWidget):
def __init__(self, dataframe: pd.DataFrame, legend: pd.DataFrame):
super().__init__()
self.df = dataframe.copy()
self.legend = legend
self.initUI()
def initUI(self):
# Create a figure and axes
self.fig = Figure(layout = "tight")
self.fig.patch.set_facecolor("none")
self.ax = self.fig.add_subplot(111)
self.ax.set_facecolor('none')
self.ax.xaxis.set_tick_params(labelsize="small")
self.ax.yaxis.set_tick_params(labelsize="small")
# Set initial plot limits based on the data range
x_min= int(self.df.index.min())
x_max = int(self.df.index.max())
self.ax.set_xlim(max(0, round(x_min - 5, 1)), round(x_max + 5, 1))
self.ax.set_ylim(0, 1.1)
# X-AXIS SETTINGS
# Set X-axis label in bold
self.ax.set_xlabel("Rainfall RP (years)", fontsize="small", fontweight="bold")
# Align X-axis label to the right
self.ax.xaxis.set_label_coords(0.85, -0.15)
# Set X-axis ricks on data X values
self.ax.set_xticks(self.df.index.values)
# Hide the top and right spines
self.ax.spines['top'].set_visible(False)
self.ax.spines['right'].set_visible(False)
# Hide vertical gridlines
self.ax.grid(False, axis='y')
# Create a colormap with unique colors for each row
self.scatter_cmap = plt.get_cmap('tab10', len(self.df.columns))
# Get the colors for the average
self.cmap = cm.get_cmap('RdYlGn')
self.norm = plt.Normalize(0, 1)
# Set the area under the stackplot
x_avg_values = self.df.index.values
y_avg_values = self.df["Average"].values.astype(float)
# Calculate the area under the stackplot
average_area = np.trapz(y_avg_values, x_avg_values)
# Calculate the total width of the x-axis range
total_width = x_avg_values[-1] - x_avg_values[0]
# Calculate the normalized integral
ResilienceIndex = average_area / total_width
background_area = self.ax.fill_between(x_avg_values, y_avg_values, 1, alpha= 1, color='#D6DBDF', linewidth = 0)
average_area = self.ax.stackplot(x_avg_values,
y_avg_values,
alpha = 0.6,
color = self.cmap(self.norm(ResilienceIndex))
)
# Write the value of the normalized integral on the stackplot
normalized_value = self.ax.text(min(x_avg_values)+(max(x_avg_values)-min(x_avg_values))/2, ResilienceIndex / 2 , f"R = {ResilienceIndex:.2f}", ha='center', va='center', weight = "bold")
# Store scatter objects and legend entries
self.scatter_objects = []
self.legend_entries = []
marker_size = 30
i = 0
for col_name, col_data in self.df.iloc[:, :-1].items(): #without the last column!
# Plot scatter points for each valid value
scatter = self.ax.scatter(x = col_data.index.values,
y = col_data.values,
marker = 'o',
color = self.scatter_cmap(i),
s = marker_size,
alpha = 1)
self.scatter_objects.append(scatter)
i += 1
self.legend_filtered = self.legend[self.legend.index.isin(self.df.columns)]["ShowName"].values
self.legend = self.ax.legend(self.scatter_objects,
self.legend_filtered,
ncol = 3,
fontsize = "small",
loc = 'center',
bbox_to_anchor = (0.5, -0.35),
handletextpad = 0.1, # Adjust the space between symbols and labels
frameon = False)
# ncol=min(3, len(visible_labels)),
self.legend.set_visible(True) # Make sure the legend is visible
self.legend.set_picker(True) # Enable picking on the legend
self.legend.figure.canvas.mpl_connect('pick_event', self.on_legend_pick)
self.SelectedSeries = None
self.InteractiveElements = []
# Create a canvas and layout for the widget
self.canvas = FigureCanvas(self.fig)
self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.canvas.setStyleSheet("background-color: transparent;")
layout = QVBoxLayout()
layout.addWidget(self.canvas)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
layout.setSizeConstraint(QLayout.SetMinimumSize)
self.setLayout(layout)
def on_legend_pick(self, event):
legend_label = None
if event.mouseevent.button == 1: # Left mouse button clicked
legend_artist = event.artist
legend_handles = legend_artist.legendHandles
if not legend_label:
for handle, label in zip(legend_handles, self.legend_filtered):
contains, _ = handle.contains(event.mouseevent)
if contains:
legend_label = label
print("Clicked on legend item:", legend_label)
break
if not legend_label:
for text in legend_artist.get_texts():
if text.contains(event.mouseevent)[0]:
legend_label = text.get_text()
print("Clicked on legend label:", legend_label)
break
if self.SelectedSeries == legend_label:
# Clear the selected series and remove the lines and text
self.clearSelected_lines_and_text()
self.SelectedSeries = None
else:
if self.InteractiveElements:
self.clearSelected_lines_and_text()
self.SelectedSeries = legend_label
self.plot_Line_and_Text(legend_label)
# Redraw the canvas to reflect the changes
event.canvas.draw()
def plot_Line_and_Text(self, selected_label):
position = self.legend_filtered.tolist().index(selected_label)
series_column = self.df.columns[position]
data = self.df[series_column]
x_values = data.index.values
y_values = data.values
line = self.ax.plot(x_values, y_values, color=self.scatter_cmap(position), alpha=1, linestyle='-', marker='o', zorder=1)
self.InteractiveElements.append(line[0])
# calculate the area below line
area = np.trapz(y_values, x_values)
# Calculate the total width of the x-axis range
total_width = x_values[-1] - x_values[0]
# Calculate the normalized integral
normalized_integral = area / total_width
normalized_text = self.ax.text(min(x_values)+(max(x_values)-min(x_values))/2, normalized_integral / 2 ,
f"R = {normalized_integral:.2f}",
ha='center', va='center',
color=self.scatter_cmap(position), alpha = 1,
weight='bold', zorder = 1)
self.InteractiveElements.append(normalized_text)
# Set alpha and zorder for scatter points of non-selected scenarios
for scatter in self.scatter_objects:
if scatter.get_label() != selected_label:
scatter.set_alpha(0.2)
scatter.set_zorder(0)
else:
scatter.set_alpha(1)
scatter.set_zorder(1)
for text in self.ax.texts:
if text not in self.InteractiveElements:
text.set_alpha(0.2)
text.set_fontweight('normal')
text.set_zorder(0)
# Redraw the canvas to reflect the changes
self.ax.figure.canvas.draw()
# # Calculate the midpoint between the baseline scatter and the other scatter
# x_baseline = baseline_value
# x_other = value
# y = i
# x_midpoint = (x_baseline + x_other) / 2
# y_midpoint = y
# # Determine the line style and color based on the percentage change
# line_style = '-'
# line_color = 'green' if percentage_change > 0 else 'red'
# # Draw the line between the two points
# hline = self.ax.plot([x_baseline, x_other], [y, y], color=line_color, linewidth=1.5, linestyle=line_style, zorder=2)
# self.InteractiveElements[legend_label].append(hline)
# # Set the position of the text slightly above the midpoint
# text_x = x_midpoint
# text_y = y_midpoint + 0.05 * (len(self.categories) - 1 )
# # Add the text for the percentage change with "+" sign for positive values
# if percentage_change > 0:
# text = self.ax.text(text_x, text_y, f'+{int(percentage_change)}%', ha='center', va='center', fontsize='x-small', weight='bold', color=line_color, zorder = 3)
# self.InteractiveElements[legend_label].append(text)
# else:
# text = self.ax.text(text_x, text_y, f'{int(percentage_change)}%', ha='center', va='center', fontsize='x-small', weight='bold', color=line_color, zorder = 3)
# self.InteractiveElements[legend_label].append(text)
def clearSelected_lines_and_text(self):
element_to_remove = []
for element in self.InteractiveElements:
if element in self.ax.lines:
element.remove()
element_to_remove.append(element)
elif element in self.ax.texts:
element.remove()
element_to_remove.append(element)
self.InteractiveElements = list(set(self.InteractiveElements) - set(element_to_remove))
for text in self.ax.texts:
text.set_alpha(1)
text.set_zorder(1)
text.set_fontweight('bold')
for scatter in self.scatter_objects:
scatter.set_alpha(1)
scatter.set_zorder(1)
# Redraw the canvas to reflect the changes
self.ax.figure.canvas.draw()
def clear_hlines_and_texts(self, data_series_name):
for key, elements in self.InteractiveElements.items():
if key == data_series_name:
for element in elements:
element.remove()
self.canvas.draw()
class BarPerformancePlotWidget(QWidget):
def __init__(self, dataframe: pd.DataFrame, legend: pd.DataFrame):
super().__init__()
self.df = dataframe.copy()
self.legend = legend
self.initUI()
def initUI(self):
# Create a figure and axes
self.fig = Figure(layout = "tight")
self.fig.patch.set_facecolor("none")
self.ax = self.fig.add_subplot(111)
self.ax.set_facecolor('none')
self.ax.xaxis.set_tick_params(labelsize="small")
self.ax.yaxis.set_tick_params(labelsize="small")
# self.ax.set_xlim(max(0, round(x_min - 5, 1)), round(x_max + 5, 1))
self.ax.set_ylim(0, 1.1)
# Hide the top and right spines
self.ax.spines['top'].set_visible(False)
self.ax.spines['right'].set_visible(False)
# Hide vertical gridlines
self.ax.grid(False, axis='y')
# Create a colormap with unique colors for each row
self.scatter_cmap = plt.get_cmap('tab10', len(self.df.columns))
# Get the colors for the average
self.cmap = cm.get_cmap('RdYlGn')
self.norm = plt.Normalize(0, 1)
# Set the area under the stackplot
y_values = self.df.values[0, :-1].astype(float)
x_values = range(1, len(y_values)+1)
x_colors = range(0, len(y_values))
x_labels = self.legend[self.legend.index.isin(self.df.columns)]["ShowName"].values
# Set X-axis ticks on data X values
self.ax.set_xticks(x_values)
self.ax.set_xticklabels(x_labels)
# Calculate the average of the y_values -< Resilience Index
ResilienceIndex = self.df.values[0, -1]
R_line = self.ax.axhline(ResilienceIndex,
alpha = 1,
color = self.cmap(self.norm(ResilienceIndex)),
linewidth = 2
)
# Write the value of the normalized integral at the right of the line
self.normalized_value = self.ax.text(max(x_values) + 0.4,
ResilienceIndex,
f"R = {ResilienceIndex:.2f}",
color = self.cmap(self.norm(ResilienceIndex)),
ha='left', va='center',
weight = "bold")
background_bars = self.ax.bar(x = x_values,
height = 1,
color = "#D6DBDF",
width = 0.5,
alpha = 1,
edgecolor = 'none',
zorder = 0)
# Store scatter objects and legend entries
self.plot_objects = []
self.legend_entries = []
marker_size = 30
bar = self.ax.bar(x = x_values,
height = y_values,
color = self.scatter_cmap(x_colors),
width = 0.5,
alpha = 1,
edgecolor = 'none',
zorder = 1)
self.plot_objects.append(bar)
self.SelectedSeries = None
self.InteractiveElements = []
# Create a canvas and layout for the widget
self.canvas = FigureCanvas(self.fig)
self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.canvas.setStyleSheet("background-color: transparent;")
layout = QVBoxLayout()
layout.addWidget(self.canvas)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
layout.setSizeConstraint(QLayout.SetMinimumSize)
self.setLayout(layout)
class _OLD_ScatterPlotWidget(QWidget):
def __init__(self, dataframe: pd.DataFrame(), xmax: int):
super().__init__()
self.df = dataframe.copy()
self.xmax = xmax
self.initUI()
def initUI(self):
self.LinesToKeep = []
# Create a figure and axes
self.fig = Figure(constrained_layout=True)
self.ax = self.fig.add_subplot(111)
self.ax.xaxis.set_tick_params(labelsize = "small")
self.ax.yaxis.set_tick_params(labelsize = "small")
# Set initial plot limits based on the data range
min_value = self.df.iloc[:, :].astype(float).min().min()
max_value = self.df.iloc[:, :].astype(float).max().max()
self.ax.set_xlim(max(0, round(min_value - 0.1, 1)), min(1, round(max_value + 0.1), 1))
#self.ax.set_xlim(0, self.xmax)
#self.ax.set_xticks(np.arange(0, 1.01, 0.25))
#self.ax.set_xticklabels([f"{tick}" for tick in np.arange(0, 1.01, 0.25)])
# Get the categories (indicators) from the DataFrame columns
self.categories = self.df.columns
# Set the number of y values
self.ax.set_yticks(range(len(self.categories)))
self.ax.set_yticklabels(self.categories, weight='bold')
self.ax.set_ylim(range(len(self.categories))[0] - 0.5, range(len(self.categories))[-1] + 0.5)
# Hide the top and bottom axis lines
self.ax.spines['top'].set_visible(False)
self.ax.spines['bottom'].set_visible(False)
# Hide vertical gridlines
self.ax.grid(False)
# Set the background color with 50% transparency