-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgradeAnalysisWidgets.py
1655 lines (1341 loc) · 62.8 KB
/
gradeAnalysisWidgets.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 tkinter as tk
from tkinter import ttk
from tkinter import simpledialog
from functools import partial
import mplcursors
import sys
import logging
import platform
import numpy as np
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from tkinter.filedialog import asksaveasfilename
from pandas.core.base import NoNewAttributesMixin
from ttkwidgets import autocomplete
import os
import subprocess
import matplotlib.colors as mcolors
import random
import seaborn
from matplotlib.backend_bases import MouseButton
from sklearn.preprocessing import (
StandardScaler,
MinMaxScaler,
RobustScaler,
MaxAbsScaler,
Normalizer,
)
from matplotlib.backend_bases import MouseButton
import pandas as pd
import tkinter.scrolledtext as tkst
from functools import partial
from tkinter import colorchooser
import dictionary
import csv
import gradeAnalysisFunc
from matplotlib.lines import Line2D
import webcolors
import copy
def popup(self, title="", popup_text=""):
self.logger.info(f"Creating popup with title: '{title}'")
messageBox = tk.Toplevel()
label = tk.Label(messageBox, text=title)
label.pack()
self.logger.debug("Popup title label created")
show_help_info = tk.Label(messageBox, text=popup_text, justify="left")
show_help_info.pack()
self.logger.debug("Popup text label created")
button_close = tk.Button(messageBox, text="Close", command=messageBox.destroy)
button_close.pack()
self.logger.debug("Close button created for popup")
self.logger.info("Popup created and displayed successfully")
def name_to_hex(color_name):
return webcolors.name_to_hex(color_name)
##For matplotlib uses
def get_non_red_colors():
css4_colors = mcolors.CSS4_COLORS
def hex_to_rgb(hex_color):
"""Convert hex color to RGB."""
hex_color = hex_color.lstrip('#')
return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
def calculate_brightness(rgb_color):
"""Calculate the perceived brightness of an RGB color."""
r, g, b = rgb_color
return (0.299 * r + 0.587 * g + 0.114 * b)
non_red_colors = [
(name, hex) for name, hex in css4_colors.items()
if "red" not in name.lower() and calculate_brightness(hex_to_rgb(hex)) <= 200
]
non_red_colors = [i[0] for i in non_red_colors]
non_red_colors.remove('rebeccapurple')
return non_red_colors
def get_non_red_colors_name_hex():
css4_colors = mcolors.CSS4_COLORS
non_red_colors = {
name: hex for name, hex in css4_colors.items() if "red" not in name.lower()
}
return non_red_colors
def get_nonseaborn_styles():
plot_styles = plt.style.available
non_seaborn_styles = [
color for color in plot_styles if "seaborn" not in color.lower()
]
return non_seaborn_styles
def get_random_values(input_list, number_of_values=7):
if len(input_list) < number_of_values:
raise ValueError(
f"Input list must contain at least {number_of_values} elements."
)
return random.sample(input_list, number_of_values)
def normalize_dataframe_column(dataframe, column, normalization_type):
if column not in dataframe.columns:
print(f"Column '{column}' not found in the dataframe.")
return
print(f"Normalizing column '{column}' using '{normalization_type}' method.")
normalization_functions = {
"minmax": lambda x: MinMaxScaler().fit_transform(x),
"zscore": lambda x: StandardScaler().fit_transform(x),
"robust": lambda x: RobustScaler().fit_transform(x),
"maxabs": lambda x: MaxAbsScaler().fit_transform(x),
"log": lambda x: np.log(
x - np.min(x) + 1
), # Log scaling with shift to handle non-positive values
}
if normalization_type in normalization_functions:
# Normalize the column and add the normalized column to the dataframe
scaled_data = normalization_functions[normalization_type](dataframe[[column]])
dataframe[f"{normalization_type}Normalized{column}"] = (
scaled_data.squeeze()
) # Use squeeze to ensure correct dimensionality
else:
print(f"Normalization type '{normalization_type}' is not supported.")
class Logger(logging.Logger):
_file_handler_created = False # Class-level attribute
def __init__(self, name, level=logging.DEBUG, log_file=".log.log"):
super().__init__(name, level)
stream_handler = logging.StreamHandler()
formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt="%m/%d/%Y, [%H:%M:%S]",
)
stream_handler.setFormatter(formatter)
self.addHandler(stream_handler)
if not Logger._file_handler_created:
file_handler = logging.FileHandler(log_file, mode="w")
Logger._file_handler_created = True
else:
# Subsequent logger instances should append to the file
file_handler = logging.FileHandler(log_file, mode="a")
file_handler.setFormatter(formatter)
self.addHandler(file_handler)
self.setLevel(level)
def debug(self, message):
self.log(logging.DEBUG, message)
def info(self, message):
self.log(logging.INFO, message)
def warning(self, message):
self.log(logging.WARNING, message)
def error(self, message):
self.log(logging.ERROR, message)
def critical(self, message):
self.log(logging.CRITICAL, message)
class ConfirmButton:
def __init__(self):
self.logger = Logger(__name__) # Create a logger using the custom Logger class
self.confirm_button = None
self.logger.info("ConfirmButton instance initialized")
def make_confirm_button(
self, where, title="Confirm", command=None, row=int, column=int, helptip=""
):
self.logger.info(
f"Creating confirm button titled '{title}' at row {row}, column {column}"
)
self.confirm_button = tk.Button(where, text=title, command=command)
self.confirm_button.grid(row=row, column=column)
self.bind_tooltip_events(self.confirm_button, helptip)
self.logger.debug("Confirm button created and grid placement set")
def destroy(self):
self.logger.debug("Destroying confirm button")
if self.confirm_button is not None:
self.confirm_button.destroy()
self.logger.info("Confirm button destroyed")
def bind_tooltip_events(self, widget, text):
self.logger.debug(
f"Binding tooltip events to widget with tooltip text: '{text}'"
)
tooltip = ToolTip(widget, text)
widget.bind("<Enter>", lambda event: tooltip.showtip())
widget.bind("<Leave>", lambda event: tooltip.hidetip())
self.logger.debug("Tooltip events bound successfully")
class TableWidget:
def __init__(self):
self.logger = Logger(__name__) # Create a logger for this class
self.table = None
self.logger.info("TableWidget instance initialized")
def generic_tableview_widget(
self, where, row=int, column=int, title="", colHeading="", helptip=""
):
self.logger.info(
f"Creating table view widget titled '{title}' with columns '{colHeading}' at row {row}, column {column}"
)
self.table = ttk.Treeview(
where, columns=colHeading, show="headings", selectmode=tk.BROWSE
)
self.table.grid(row=row, column=column)
self.table.heading(colHeading, text=title)
self.bind_tooltip_events(self.table, helptip)
self.logger.debug("Table view widget created and configured")
return self.table
def insert(self, parent, index, values=()):
if self.table is not None:
self.table.insert(parent=parent, index=index, values=values)
else:
self.logger.warning("Attempted to insert into uninitialized table")
def selection(self):
self.logger.debug("Getting selected item from table")
if self.table is not None:
selected = self.table.selection()
if selected:
self.logger.info(f"Selected item: {selected}")
return selected
else:
self.logger.warning("No selection found")
else:
self.logger.error("Table is not initialized")
def item(self, selected_item):
self.logger.debug(f"Getting item info for: {selected_item}")
if self.table is not None:
item_info = self.table.item(selected_item)
values = item_info.get("values", ())
if values:
self.logger.info(f"Values for item {selected_item}: {values}")
return values[0]
else:
self.logger.warning(f"No values found for item: {selected_item}")
else:
self.logger.error("Table is not initialized")
def destroy(self):
self.logger.debug("Destroying table widget")
if self.table is not None:
self.table.destroy()
def grid_forget(self):
self.logger.debug("Forgetting grid placement of table")
if self.table is not None:
self.table.grid_forget()
def bind_tooltip_events(self, widget, text):
self.logger.debug(
f"Binding tooltip events to widget with tooltip text: '{text}'"
)
tooltip = ToolTip(widget, text)
widget.bind("<Enter>", lambda event: tooltip.showtip())
widget.bind("<Leave>", lambda event: tooltip.hidetip())
self.logger.debug("Tooltip events bound successfully")
class ThresholdWidget:
def __init__(self):
self.logger = Logger(__name__) # Create a logger for this class
self.label = None
self.entry = None
self.logger.info("ThresholdWidget instance initialized")
def generic_thresholds_widget(
self, where, state=str, text=str, row=int, column=int, help=str
):
self.logger.info(
f"Creating threshold widget with label '{text}' at row {row}, column {column}"
)
x_pad = len(text) * 7
self.label = tk.Label(where, text=text)
self.label.grid(row=row, column=column, sticky=tk.W)
self.entry = tk.Entry(where, width=3)
self.entry.config(state=state)
self.entry.grid(row=row, column=column, sticky=tk.W, padx=(x_pad, 0))
self.bind_tooltip_events(self.entry, help)
self.logger.debug("Threshold widget created and configured")
def get_entry_value(self):
if self.entry is None or self.label is None:
self.logger.error("Entry is not initialized")
return
entry_value = self.entry.get()
if entry_value != "":
self.logger.debug(f"Retrieving entry value: {entry_value}")
return int(entry_value)
else:
self.logger.warning("Entry value is empty")
return
def destroy(self):
self.logger.debug("Destroying threshold widget components")
if self.label is not None:
self.label.destroy()
if self.entry is not None:
self.entry.destroy()
self.logger.info("Threshold widget components destroyed")
def bind_tooltip_events(self, widget, text):
self.logger.debug(
f"Binding tooltip events to widget with tooltip text: '{text}'"
)
tooltip = ToolTip(widget, text)
widget.bind("<Enter>", lambda event: tooltip.showtip())
widget.bind("<Leave>", lambda event: tooltip.hidetip())
self.logger.debug("Tooltip events bound successfully")
class CheckboxWidget:
def __init__(self):
self.logger = Logger(__name__) # Create a logger for this class
self.checkboxes = {}
self.logger.info("CheckboxWidget instance initialized")
def create_checkbox(self, text, help_text, state, where, row, column):
self.logger.info(f"Creating checkbox '{text}' at row {row}, column {column}")
checkbox_state = tk.BooleanVar()
checkbox = tk.Checkbutton(
where, state=state, text=text, variable=checkbox_state
)
checkbox.grid(row=row, column=column, sticky=tk.W)
self.bind_tooltip_events(checkbox, help_text)
self.checkboxes[text] = (checkbox, checkbox_state)
self.logger.debug(f"Checkbox '{text}' created")
def create_multiple_checkboxes(self, options, flags, state, where, row, column):
self.logger.info("Creating multiple checkboxes")
current_row = row
for (text, help_text), flag in zip(options.items(), flags):
if flag:
self.create_checkbox(text, help_text, state, where, current_row, column)
current_row += 1
self.logger.debug("Multiple checkboxes created")
def get_dict_of_checkbox(self):
self.logger.debug("Retrieving selected checkboxes")
selected = {text: state.get() for text, (_, state) in self.checkboxes.items()}
self.logger.info(f"Selected checkboxes: {selected}")
return selected
def destroy(self):
self.logger.debug("Destroying all checkboxes")
for checkbox, _ in self.checkboxes.values():
checkbox.destroy()
self.checkboxes.clear()
self.logger.info("All checkboxes destroyed")
def bind_tooltip_events(self, widget, text):
self.logger.debug(
f"Binding tooltip events to widget '{widget}' with tooltip text: '{text}'"
)
tooltip = ToolTip(widget, text)
widget.bind("<Enter>", lambda event: tooltip.showtip())
widget.bind("<Leave>", lambda event: tooltip.hidetip())
self.logger.debug(f"Tooltip events bound to widget '{widget}'")
class Console(tk.Text):
def __init__(self, *args, **kwargs):
self.logger = Logger(__name__) # Create a logger for this class
kwargs.update({"state": "disabled"})
tk.Text.__init__(self, *args, **kwargs)
self.bind("<Destroy>", self.reset)
self.old_stdout = sys.stdout
sys.stdout = self
self.logger.info("Console widget initialized and stdout redirected")
def delete(self, *args, **kwargs):
self.logger.debug("Clearing console text")
self.config(state="normal")
super().delete(*args, **kwargs) # Use super() to avoid recursion
self.config(state="disabled")
def write(self, content):
self.config(state="normal")
self.insert(tk.END, content)
self.see(tk.END)
self.config(state="disabled")
def reset(self, event):
sys.stdout = self.old_stdout
self.logger.info("Console widget destroyed and stdout reset")
class ToolTip:
def __init__(self, widget, text):
self.widget = widget
self.text = text
self.tooltip_window = None
def showtip(self):
# Method to show tooltip on hover
self.tooltip_window = tk.Toplevel(self.widget)
tooltip_label = tk.Label(self.tooltip_window, text=self.text)
tooltip_label.pack()
self.tooltip_window.overrideredirect(True)
x = self.widget.winfo_rootx() + 50
y = self.widget.winfo_rooty() + 50
self.tooltip_window.geometry(f"+{x}+{y}")
def hidetip(self):
# Method to hide tooltip when not hovering
if self.tooltip_window:
self.tooltip_window.destroy()
self.tooltip_window = None
class FileOpener:
def __init__(self, file_path):
self.logger = Logger(__name__)
self.file_path = file_path
self.logger.info(f"FileOpener instance created for file: {file_path}")
def print(self):
self.logger.debug(f"Printing file path: {self.file_path}")
print(self.file_path)
def open_file(self, *args):
current_platform = platform.system()
self.logger.info(f"Attempting to open file on {current_platform} platform")
if current_platform == "Linux":
subprocess.Popen(["xdg-open", self.file_path])
self.logger.debug("Opened file using xdg-open")
elif current_platform == "Windows":
subprocess.Popen(["cmd", "/c", "start", self.file_path], shell=True)
self.logger.debug("Opened file using Windows cmd")
elif current_platform == "Darwin": # macOS
subprocess.Popen(["open", self.file_path])
self.logger.debug("Opened file on macOS using open")
else:
self.logger.warning("Unsupported platform for file opening")
return
class tkMatplot:
def __init__(
self,
title="",
window_width=800,
window_height=700,
df=None,
x_label=None,
y_label=None,
plot_type=None,
color=None,
colors=None,
legend=None,
x_plot=None,
y_plot=None,
data_type=None,
output_directory=None,
):
self.logger = Logger(__name__)
self.logger.info("Initializing tkMatplot class")
self.root = tk.Tk()
self.root.wm_title(title)
self.logger.info("Initializing tkMatplot class")
self.root.geometry(f"{window_width}x{window_height}")
self.logger.info(f"Setting window size to {window_width}x{window_height}")
self.fig = Figure(figsize=(5, 4), dpi=100)
self.canvas = FigureCanvasTkAgg(self.fig, master=self.root)
self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
button_quit = tk.Button(
master=self.root, text="Quit", command=self.root.destroy
)
button_quit.pack(side=tk.BOTTOM, fill=tk.X)
self.x_label = x_label
self.y_label = y_label
self.plot_type = plot_type
self.color = color
self.x_plot = x_plot
self.y_plot = y_plot
self.legend = legend
self.df = df
self.original_index = self.df.index.copy()
self.title = title
self.tree = None
self.highlighted_point = None
self.ax = None
self.default_directory = os.path.join(output_directory, 'Binexport.txt') if output_directory else (os.getcwd(), 'Binexport.txt')
self.left_frame = None
self.right_frame = None
self.plot_options = None
self.plot_colors = None
self.scale_options = None
self.scale = "linear"
self.accept_change_button = None
self.toolbar = None
self.plot_style = "ggplot"
self.plot_style_options = None
self.change_sort_order = None
self.sort_order = "none"
self.normalize_column_options = None
self.normalize_option = "none"
self.data_type = data_type
self.graphing_bin_check = False
self.numerical_bin_check = False
self.use_color_groups = False
self.bin_selected_groups = None
self.reset_tuple = (
copy.deepcopy(title),
copy.deepcopy(window_width),
copy.deepcopy(window_height),
copy.deepcopy(df),
copy.deepcopy(x_label),
copy.deepcopy(y_label),
copy.deepcopy(plot_type),
copy.deepcopy(color),
copy.deepcopy(colors),
copy.deepcopy(x_plot),
copy.deepcopy(y_plot),
copy.deepcopy(data_type),
copy.deepcopy(self.scale),
copy.deepcopy(self.plot_style),
copy.deepcopy(self.sort_order),
copy.deepcopy(self.normalize_option),
copy.deepcopy(self.legend),
)
self.help_button = None
self.logger.info("tkMatplot class initialized")
def sort_dataframe(self, df, sort_order: str = 'descending', by: str = ''):
if self.sort_order == "ascending":
df.sort_values(by=by, ascending=True, inplace=True)
elif self.sort_order == "descending":
df.sort_values(by=by, ascending=False, inplace=True)
elif self.sort_order == "random":
df = df.sample(frac=1).reset_index(drop=True)
elif self.sort_order == "none":
df = df.loc[self.original_index]
return df
def plot(self):
self.logger.info("Creating plot")
self.fig.clear()
if self.toolbar is None:
self.set_toolbar()
plt.style.use(self.plot_style)
self.ax = self.fig.add_subplot()
self.ax.ticklabel_format(useOffset=False, style="plain", axis="both")
df = self.df
current_yplot = self.y_plot
self.logger.info(f"Plotting data using {self.plot_type} plot type")
if self.graphing_bin_check:
df = self.custom_bin_agg(df, self.bin_selected_groups)
self.logger.info("Creating plot with custom bin aggregation")
self.logger.info(f"Sort order: {self.sort_order}")
df = self.sort_dataframe(df, sort_order=self.sort_order, by=current_yplot)
if self.normalize_option != "none":
self.logger.info(f"Normalizing data using '{self.normalize_option}' method")
normalize_dataframe_column(df, current_yplot, self.normalize_option)
current_yplot = f"{self.normalize_option}Normalized{current_yplot}"
self.logger.info(f"Normalized column: {current_yplot}")
x_data = df['Bin']
y_data = df[current_yplot]
colors = df['Color']
self.legend = dict(zip(df['Color'], df['Bin']))
if self.plot_type == "line":
line_plot = self.ax.plot(x_data, y_data, marker="o", linestyle='-', color='black')
cursor = mplcursors.cursor(line_plot, hover=True)
elif self.plot_type == "scatter":
scatter_plot = self.ax.scatter(x_data, y_data, c=colors, label='Bins')
cursor = mplcursors.cursor(scatter_plot, hover=True)
elif self.plot_type == "bar":
bar_plot = self.ax.bar(x_data, y_data, color=colors, align='center')
cursor = mplcursors.cursor(bar_plot, hover=True)
elif self.numerical_bin_check and self.bin_selected_groups is not None and not self.use_color_groups:
self.logger.info("Creating plot with numerical bin aggregation")
df = self.bin_agg_tuples(df, self.bin_selected_groups, self.x_plot)
self.logger.info(f"Sort order: {self.sort_order}")
df = self.sort_dataframe(df, self.sort_order, current_yplot)
if self.normalize_option != "none":
self.logger.info(f"Normalizing data using '{self.normalize_option}' method")
normalize_dataframe_column(df, current_yplot, self.normalize_option)
current_yplot = f"{self.normalize_option}Normalized{current_yplot}"
self.logger.info(f"Normalized column: {current_yplot}")
for bin_data in df.iterrows():
bin_name = bin_data[1]['Bin']
x_data = [bin_name]
y_data = [bin_data[1][current_yplot]]
if self.plot_type == "line":
line_plot = self.ax.plot(x_data, y_data, marker="o", label=bin_name)
cursor = mplcursors.cursor(line_plot, hover=True)
elif self.plot_type == "scatter":
scatter_plot = self.ax.scatter(x_data, y_data, label=bin_name)
cursor = mplcursors.cursor(scatter_plot, hover=True)
elif self.plot_type == "bar":
bar_plot = self.ax.bar(x_data, y_data, label=bin_name)
cursor = mplcursors.cursor(bar_plot, hover=True)
else:
self.logger.info("Creating plot without bin aggregation")
if self.use_color_groups:
df = self.color_bin_agg(self.df)
df['legend'] = df['color'].map(self.legend)
self.logger.info(f"Sort order: {self.sort_order}")
self.original_index = df.index.copy()
df = self.sort_dataframe(df, sort_order=self.sort_order, by=current_yplot)
if self.normalize_option != "none":
self.logger.info(f"Normalizing data using '{self.normalize_option}' method")
normalize_dataframe_column(df, current_yplot, self.normalize_option)
current_yplot = f"{self.normalize_option}Normalized{current_yplot}"
self.logger.info(f"Normalized column: {current_yplot}")
x_data = df['legend'] if self.use_color_groups else df[self.x_plot]
if self.plot_type == "line":
line_plot = self.ax.plot(x_data, df[current_yplot], color=df['color'].iloc[0])
cursor = mplcursors.cursor(line_plot, hover=True)
elif self.plot_type == "scatter":
scatter_plot = self.ax.scatter(x_data, df[current_yplot], color=df['color'])
cursor = mplcursors.cursor(scatter_plot, hover=True)
elif self.plot_type == "bar":
bar_plot = self.ax.bar(x_data, df[current_yplot], color=df['color'])
cursor = mplcursors.cursor(bar_plot, hover=True)
self.ax.set_ylim(0, df[current_yplot].max() + 1)
if cursor:
@cursor.connect("add")
def on_add(sel):
index = sel.index
annotation_text = []
excluded_columns = [
'kurtosis', 'skewness', 'CoV(%)', 'ModeGPA', 'A', 'A-', 'B+', 'B', 'B-',
'C+', 'C', 'C-', 'D', 'F', 'color', 'avg_gpa_change', 'avg_gpaw_change'
]
for col in df.columns:
if col not in excluded_columns:
col_value = df[col].iloc[index]
annotation_text.append(f"{col}: {col_value}")
sel.annotation.set_text("\n".join(annotation_text))
legend_elements = [
Line2D([0], [0], color=color, lw=4, label=label)
for color, label in self.legend.items()
]
self.ax.legend(handles=legend_elements, title="Legend")
self.ax.set_xlabel(self.x_label, fontsize=12)
self.ax.set_ylabel(current_yplot, fontsize=12)
self.ax.set_title(self.title, fontsize=14)
self.ax.grid(True)
self.ax.tick_params(axis="x", rotation=90, labelsize=9)
self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
self.ax.set_yscale(self.scale)
self.canvas.draw()
if self.graphing_bin_check:
xplot='Bin'
elif self.use_color_groups:
xplot='legend'
else:
xplot=self.x_plot
if self.left_frame is not None:
self.left_frame.destroy()
self.add_table(df=df, xplot=xplot ,yplot=current_yplot)
if self.right_frame is not None:
self.right_frame.destroy()
self.change_graph_options()
self.accept_change_button.config(state="disabled")
self.fig.tight_layout(rect=[1,1,1,1])
self.canvas.draw()
def change_plot_type(self):
if self.plot_type != self.plot_options.get_selected_option():
self.plot_type = self.plot_options.get_selected_option()
if self.scale != self.scale_options.get_selected_option():
self.scale = self.scale_options.get_selected_option()
if self.plot_style != self.plot_style_options.get_selected_option():
self.plot_style = self.plot_style_options.get_selected_option()
if self.sort_order != self.change_sort_order.get_selected_option():
self.sort_order = self.change_sort_order.get_selected_option()
if self.normalize_option != self.normalize_column_options.get_selected_option():
self.normalize_option = self.normalize_column_options.get_selected_option()
self.plot()
def reset_state(self):
(
title,
window_width,
window_height,
df,
x_label,
y_label,
plot_type,
color,
colors,
x_plot,
y_plot,
data_type,
scale,
plot_style,
sort_order,
normalize_option,
legend,
) = self.reset_tuple
self.root.wm_title(title)
self.root.geometry(f"{window_width}x{window_height}")
self.df = df
self.x_label = x_label
self.y_label = y_label
self.plot_type = plot_type
self.color = color
self.colors = colors
self.x_plot = x_plot
self.y_plot = y_plot
self.title = title
self.scale = scale
self.plot_style = plot_style
self.sort_order = sort_order
self.normalize_option = normalize_option
self.data_type = data_type
self.numerical_bin_check = False
self.graphing_bin_check = False
self.legend = legend
self.use_color_groups = False
self.plot()
def change_legend_plot_colors(self):
selected_color = colorchooser.askcolor(title="Choose color")[1]
target_color = self.plot_colors.get_selected_option()
self.df['color'] = self.df['color'].apply(
lambda x: selected_color if x == target_color else x)
for old_color, label in list(self.legend.items()):
if old_color == target_color:
del self.legend[old_color]
self.legend[selected_color] = label
break
self.plot_colors.update_options(list(self.df['color'].unique()), {x: x for x in self.df['color'].unique()})
self.accept_change_button.config(state=tk.NORMAL)
def change_graph_options(self):
self.logger.info("Creating graph options")
self.right_frame = tk.Frame(self.root)
self.right_frame.pack(side=tk.RIGHT, fill="both", expand=True)
self.logger.info("Creating Plot Type Options")
self.plot_options = tkOptionMenu(
master=self.right_frame,
options=["line", "scatter", "bar"],
pre_selected=f"{self.plot_type}",
label_text="Change Plot Type",
command=self.set_normal_state,
)
self.plot_options.grid(row=1, column=1, padx=(0, 20))
self.logger.info("Plot Type Options created")
self.logger.info("Creating Plot Color Options")
self.plot_colors = tkOptionMenu(
master=self.right_frame,
options=self.df['color'].unique(),
pre_selected=f"{list(self.df['color'].unique())[0]}",
label_text="Change Plot Colors",
command=self.change_legend_plot_colors,
colors={x: x for x in self.df['color'].unique()},
)
self.plot_colors.grid(row=1, column=3, padx=(20, 0))
self.logger.info("Plot Color Options created")
self.logger.info("Creating Axis Scale Options")
self.scale_options = tkOptionMenu(
master=self.right_frame,
options=[
"linear",
"log",
"symlog",
"asinh",
],
pre_selected=self.scale,
label_text="Axis Scale",
command=self.set_normal_state,
)
self.scale_options.grid(row=3, column=1)
self.logger.info("Axis Scale Options created")
self.logger.info("Creating Plot Style Options")
self.plot_style_options = tkOptionMenu(
master=self.right_frame,
options=get_random_values(get_nonseaborn_styles()),
pre_selected=self.plot_style,
label_text="Change Plot Style",
command=self.set_normal_state,
)
self.plot_style_options.grid(row=3, column=3)
self.logger.info("Plot Style Options created")
self.accept_change_button = tk.Button(
self.right_frame,
text="Accept",
command=self.change_plot_type,
)
self.logger.info("Creating Sort Order Options")
self.change_sort_order = tkOptionMenu(
master=self.right_frame,
options=["ascending", "descending", "random", 'none'],
pre_selected=self.sort_order,
label_text="Sort Order",
command=self.set_normal_state,
)
self.change_sort_order.grid(row=5, column=1)
self.logger.info("Sort Order Options created")
self.logger.info("Creating Normalize Column Options")
self.normalize_column_options = tkOptionMenu(
master=self.right_frame,
options=["none", "minmax", "zscore", "robust", "maxabs", "log"],
pre_selected=self.normalize_option,
label_text="Normalize Option",
command=self.set_normal_state,
)
self.logger.info("Normalize Column Options created")
self.normalize_column_options.grid(row=5, column=3)
self.reset_button = tk.Button(self.right_frame, text='Reset Plot', command = self.reset_state)
self.reset_button.grid(row=6, column=3)
self.accept_change_button.grid(row=8, column=2)
self.help_button = tk.Button(self.right_frame, text='Help', command = self.help_create)
self.help_button.grid(row=8, column=5)
if self.df[self.x_plot].dtype == "object":
self.logger.info("Creating Bin Button")
self.bin_button = tkOptionMenu(master=self.right_frame, options=['Manual', 'By Colors'], pre_selected='Manual', command=self.str_bin_creation, label_text='Create Groupings')
self.bin_button.grid(row=6, column=1)
else:
self.logger.info("Creating Numerical Bin Button")
self.bin_button = tkOptionMenu(master=self.right_frame, options=['Manual', 'By Colors'], pre_selected='Manual', command=self.num_bin_creation, label_text='Create Groupings')
self.bin_button.grid(row=6, column=1)
self.logger.info("Bin Button created")
def help_create(self):
self.logger.info("Creating Help Popup")
popup(self, title='Help', popup_text=
"""
1. Change Plot Type: Allows you to select between bar, scatter, or line plots\n
2. Axis Scale: Scales the axis on the selected option\n
3. Sort Order: Sort the graph on the selected option\n
4. Change Plot Color: Changes the plot color based on the selected color\n
5. Change Plot Style: Changes background plot design\n
6. Normalize option: Normalizes the plots yaxis\n
""")
self.logger.info("Help Popup created")
def num_bin_creation(self):
if self.bin_button.get_selected_option() == 'Manual':
self.numbin = NumericalBinApp(self.right_frame, row=7, column=1, set_low=min(self.df[self.x_plot]), set_high=max(self.df[self.x_plot]))
self.numbin.set_callback(self.on_bins_created)
self.use_color_groups = False
self.logger.info("Numerical Bin Button created")
else:
self.use_color_groups = True
self.plot()
def str_bin_creation(self):
if self.bin_button.get_selected_option() == 'Manual':
self.df
bin_popup = BinPopup(self.root, {key: False for key in self.df[self.x_plot]}, callback=self.on_bins_created, path=self.default_directory)
self.use_color_groups = False
else:
self.use_color_groups = True
self.plot()
self.logger.info("Creating Bin Popup")
def on_bins_created(self, selected_groups):
if self.df[self.x_plot].dtype == "object":
self.graphing_bin_check = True
else:
self.numerical_bin_check = True
self.bin_selected_groups = selected_groups
self.plot()
if self.numerical_bin_check:
self.numbin.destroy()
def set_normal_state(self):
self.accept_change_button.config(state=tk.NORMAL)
def set_toolbar(self):
self.logger.info("Creating toolbar")
self.toolbar = NavigationToolbar2Tk(self.canvas, self.root, pack_toolbar=False)
self.toolbar.pack(side=tk.TOP, fill=tk.X)
self.toolbar.update()
self.logger.info("Toolbar created")
def add_table(self, df,xplot, yplot):
self.logger.info("Creating table")
self.left_frame = tk.Frame(self.root)
self.left_frame.pack(side=tk.LEFT, fill="both", expand=True)
self.tree = ttk.Treeview(self.left_frame)
self.tree["columns"] = ("X-Value", "Y-Value")
self.tree.column("#0", width=0, stretch=tk.NO)
self.tree.column("X-Value", anchor=tk.W, width=80)
self.tree.column("Y-Value", anchor=tk.W, width=80)
self.tree.heading("#0", text="", anchor=tk.W)
self.tree.heading("X-Value", text=self.x_label, anchor=tk.W)
self.tree.heading("Y-Value", text=self.y_label, anchor=tk.W)
self.logger.info("Inserting data into table")