-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoh_plotting.py
2510 lines (2201 loc) · 96.7 KB
/
coh_plotting.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
"""Classes for plotting results.
CLASSES
-------
Plotting : Abstract Base Class
- Abstract class for plotting results.
LinePlot : subclass of Plotting
- Class for plotting results on line plots.
BoxPlot : subclass of Plotting
- Class for plotting results on box plots.
"""
from abc import ABC, abstractmethod
from copy import deepcopy
from typing import Union
from matplotlib import pyplot as plt
import numpy as np
from coh_exceptions import EntryLengthError
from coh_handle_entries import (
check_master_entries_in_sublists,
check_non_repeated_vals_lists,
check_vals_identical_list,
combine_col_vals_df,
get_eligible_idcs_lists,
get_group_names_idcs,
loop_index,
reorder_rows_dataframe,
sort_inputs_results,
dict_to_df,
)
from coh_handle_plots import get_plot_colours, maximise_figure_windows
from coh_saving import check_before_overwrite
class Plotting(ABC):
"""Abstract class for plotting results.
PARAMETERS
----------
results : dict
- A dictionary containing results to process.
- The entries in the dictionary should be either lists, numpy arrays, or
dictionaries.
- Entries which are dictionaries will have their values treated as being
identical for all values in the 'results' dictionary, given they are
extracted from these dictionaries into the results.
- Keys ending with "_dimensions" are treated as containing information
about the dimensions of other attributes in the results, e.g.
'X_dimensions' would specify the dimensions for attribute 'X'. The
dimensions should be a list of strings containing the values "channels"
and "frequencies" in the positions corresponding to the axis of these
dimensions in 'X'. A single list should be given, i.e. 'X_dimensions'
should hold for all entries of 'X'.If no dimensions, are given, the 0th
axis is assumed to correspond to channels and the 1st axis to
frequencies.
- E.g. if 'X' has shape [25, 10, 50, 300] with an 'X_dimensions' of
['epochs', 'channels', 'frequencies', 'timepoints'], the shape of 'X'
would be rearranged to [10, 50, 25, 300], corresponding to the
dimensions ["channels", "frequencies", "epochs", "timepoints"].
extract_from_dicts : dict[list[str]] | None; default None
- The keys of dictionaries within 'results' to include in the processing.
- Keys which are extracted are treated as being identical for all values
in the 'results' dictionary.
identical_keys : list[str] | None; default None
- The keys in 'results' which are identical across channels and for which
only one copy is present.
- If any dimension attributes are present, these should be included as an
identical entry, as they will be added automatically.
discard_keys : list[str] | None; default None
- The keys which should be discarded immediately without processing.
verbose : bool; default True
- Whether or not to print updates about the plotting process.
METHODS
-------
plot
- Abstract method for plotting the results.
"""
def __init__(
self,
results: dict,
extract_from_dicts: Union[dict[list[str]], None] = None,
identical_keys: Union[list[str], None] = None,
discard_keys: Union[list[str], None] = None,
verbose: bool = True,
) -> None:
# Initialises inputs of the object.
results = sort_inputs_results(
results=results,
extract_from_dicts=extract_from_dicts,
identical_keys=identical_keys,
discard_keys=discard_keys,
verbose=verbose,
)
self._results = dict_to_df(obj=results)
self._verbose = verbose
# Initialises input settings for plotting.
self.x_axis_var = None
self.y_axis_vars = None
self.x_axis_label = None
self.y_axis_limits = None
self.y_axis_labels = None
self.y_axis_tick_intervals = None
self.y_axis_cap_max = None
self.y_axis_cap_min = None
self.x_axis_scale = None
self.y_axis_scales = None
self.y_axis_limits_grouping = None
self.var_measure = None
self.figure_grouping = None
self.subplot_grouping = None
self.analysis_keys = None
self.legend_properties = None
self._legend_location = None
self._legend_font_properties = None
self.identical_keys = None
self.eligible_values = None
self.order_values = None
self.figure_layout = None
self.average_as_equal = None
self.save = None
self.save_folderpath = None
self.save_ftype = None
self._special_values = None
# Initialises aspects of the object that will be filled with information
# as the results are plotted.
self._plot_type = None
self._eligible_idcs = None
self._y_axis_limits_idcs = None
self._plot_grouping = None
# Initialises aspects of the object that indicate which methods have
# been called (starting as 'False'), which can later be updated.
self._plotted = False
@abstractmethod
def plot(self) -> None:
"""Abstract method for plotting the results."""
def _reinitialise_aspects(self) -> None:
"""Reinitialises aspects of the object that will be filled with
information as the results are plotted by setting the aspects to
'None'."""
self._eligible_idcs = None
self._y_axis_limits_idcs = None
self._plot_grouping = None
def _sort_plot_inputs(self) -> None:
"""Sorts the plotting settings."""
if self.legend_properties is not None:
self._sort_legend_properties()
self._sort_special_indexing_values()
self._sort_saving_inputs()
self._sort_values_order()
self._discard_keys(keys=self._get_missing_keys())
self._check_identical_keys()
self._get_eligible_indices()
self._sort_y_axis_limits_grouping()
self._sort_y_axis_labels()
self._sort_y_axis_tick_intervals()
self._sort_y_axis_scales_inputs()
def _sort_legend_properties(self) -> None:
"""Sorts the inputs for legend properties into a form accepted by
matplotlib."""
font_properties_params = [
"family",
"style",
"variant",
"weight",
"stretch",
"size",
"fname",
"math_fontfamily",
]
for param in self.legend_properties.keys():
if param not in font_properties_params and param != "loc":
raise ValueError(
f"The parameter '{param}' is not recognised as a "
"matplotlib FontProperties class parameter. The accepted "
f"parameters are: {font_properties_params}"
)
self._legend_font_properties = {
key: None for key in font_properties_params
}
for param, value in self.legend_properties.items():
if param == "loc":
self._legend_location = value
else:
self._legend_font_properties[param] = value
def _sort_special_indexing_values(self) -> None:
"""Sorts special values to use when finding rows of results that belong
to the same group.
If 'average_as_equal' is 'True', converts any string beginning with
"avg[" (indicating that data has been averaged across multipleresult
types) in the columns into the string "avg_", followed by the name of
the column, thereby allowing averaged results to be treated as belonging
to the same type, regardless of the specific types of results they were
averaged from.
"""
if self.average_as_equal:
self._special_values = {"avg[": "avg_"}
else:
self._special_values = None
def _sort_saving_inputs(self) -> None:
"""Sorts the inputs associated with saving figures, making sure they are
in the correct format.
RAISES
------
ValueError
- Raised if the figures will be saved, but no folderpath is given.
- Raised if the figures will be saved, but no filetype extension is
given.
"""
if self.save:
if self.save_folderpath is None:
raise ValueError(
"Error when trying to plot results:\nIt has been requested "
"for the figures to be saved, but no folderpath for saving "
"has been specified."
)
if self.save_ftype is None:
raise ValueError(
"Error when trying to plot results:\nIt has been requested "
"for the figures to be saved, but no filetype extension "
"for saving has been specified."
)
def _sort_values_order(self) -> None:
"""Reorders the rows in the results based on the order of the values in
the key specified in 'self.order_values', such that results belonging to
certain values are plotted in a certain order."""
if self.order_values is not None:
self._results = reorder_rows_dataframe(
dataframe=self._results,
key=list(self.order_values.keys())[0],
values_order=list(self.order_values.values())[0],
)
def _get_missing_keys(self) -> list[str]:
"""Finds which keys in the results are not accounted for in the plotting
settings.
RETURNS
-------
list[str]
- Names of keys in the results not accounted for by the plotting
settings.
"""
return [
key
for key in self._results.keys()
if key not in self._get_present_keys()
]
def _get_present_keys(self) -> list[str]:
"""Finds which keys in the results have been accounted for in the
plotting settings.
RETURNS
-------
present_keys : list[str]
- Names of the keys in the results accounted for by the plotting
settings.
"""
settings_inputs = [
"x_axis_var",
"y_axis_vars",
"y_axis_limits_grouping",
"figure_grouping",
"subplot_grouping",
"analysis_keys",
"identical_keys",
]
present_keys = ["n_from"]
if self.eligible_values is not None:
present_keys.extend(list(self.eligible_values.keys()))
for setting in settings_inputs:
key = getattr(self, setting)
if key is not None:
if isinstance(key, list):
present_keys.extend(key)
else:
present_keys.append(key)
add_keys = []
for key in present_keys:
if f"{key}_dimensions" in self._results.keys():
add_keys.append(f"{key}_dimensions")
if self.var_measure is not None:
if f"{key}_{self.var_measure}" in self._results.keys():
add_keys.append(f"{key}_{self.var_measure}")
present_keys.extend(add_keys)
return present_keys
def _discard_keys(self, keys: list[str]) -> None:
"""Drops keys from the results DataFrame and resets the DataFrame
index."""
self._results = self._results.drop(columns=keys)
self._results = self._results.reset_index()
if self._verbose:
print(f"Discarding the following keys from the results: {keys}\n")
def _check_identical_keys(self) -> None:
"""Checks that keys in the results marked as identical are identical."""
for key in self.identical_keys:
values = deepcopy(self._results[key])
if self.average_as_equal:
for i, val in enumerate(values):
if isinstance(val, str):
if val[:4] == "avg[":
values[i] = f"avg_{key}"
is_identical, vals = check_vals_identical_list(to_check=values)
if not is_identical:
raise ValueError(
"Error when trying to plot the results:\nThe results key "
f"'{key}' is marked as an identical key, however its "
"values are not identical for all results:\n- Unique "
f"values: {vals}\n"
)
def _get_eligible_indices(self) -> None:
"""Finds which indices in the results contain values designated as
eligible for plotting."""
if self.eligible_values is not None:
to_check = {
key: self._results[key] for key in self.eligible_values.keys()
}
self._eligible_idcs = get_eligible_idcs_lists(
to_check=to_check, eligible_vals=self.eligible_values
)
else:
self._eligible_idcs = np.arange(len(self._results.index)).tolist()
def _sort_y_axis_limits_grouping(self) -> None:
"""Finds the names and indices of groups that will share y-axis limits.
RAISES
------
ValueError
- Raised if an entry of the grouping factor for the y-axis limits is
missing from the grouping factors for the figures or subplots.
"""
self._y_axis_limits_idcs = {}
if self.y_axis_limits_grouping is not None:
all_present, absent_entries = check_master_entries_in_sublists(
master_list=self.y_axis_limits_grouping,
sublists=[self.figure_grouping, self.subplot_grouping],
allow_duplicates=False,
)
if not all_present:
raise ValueError(
"Error when trying to plot results:\nThe entry(ies) in the "
f"results {self.y_axis_limits_grouping} for creating "
"groups that will share the y-axis limits must also be "
"accounted for in the entry(ies) for creating groups that "
"will be plotted on the same figures/subplots, as plotting "
"results with multiple y-axes on the same plot is not yet "
"supported.\nThe following entries are unaccounted for: "
f"{absent_entries}\n"
)
grouping_entries = [
entry
for entry in self.y_axis_limits_grouping
if entry != "Y_AXIS_VARS"
]
if grouping_entries != []:
self._y_axis_limits_idcs = get_group_names_idcs(
dataframe=self._results,
keys=grouping_entries,
eligible_idcs=self._eligible_idcs,
replacement_idcs=self._eligible_idcs,
special_vals=self._special_values,
)
if not self._y_axis_limits_idcs:
self._y_axis_limits_idcs["ALL"] = deepcopy(self._eligible_idcs)
def _sort_y_axis_limits(self) -> None:
"""Checks that the limits for the y-axis variables are in the correct
format.
RAISES
------
KeyError
- Raised if the keys of the dictionary in the provided 'y_axis_limits'
do not match the names of the groups in the
automatically-generated y-axis limit group indices.
- Raised if the keys of the dictionary within each group dictionary do
not contain the names (and hence limits) for each y-axis variable
being plotted.
"""
all_repeated = check_non_repeated_vals_lists(
lists=[
self.y_axis_limits.keys(),
self._y_axis_limits_idcs.keys(),
],
allow_non_repeated=True,
)
if not all_repeated:
raise KeyError(
"Error when trying to plot results:\nNames of the groups "
"in the specified y-axis limits do not match those "
"generated from the results:\n- Provided names: "
f"{self.y_axis_limits.keys()}\n- Names should be: "
f"{self._y_axis_limits_idcs.keys()}\n"
)
for group_name, var_lims in self.y_axis_limits.items():
for var in self.y_axis_vars:
if var not in var_lims.keys():
raise KeyError(
"Error when trying to plot results:\nMissing "
f"limits for the y-axis variable '{var}' in the "
f"group '{group_name}'.\n"
)
def _sort_y_axis_tick_intervals(self) -> None:
"""Checks that the tick intervals for the y-axis variables are in the
correct format.
RAISES
------
KeyError
- Raised if the keys of the dictionary in the provided
'y_axis_tick_intervals' do not match the names of the groups in the
automatically-generated y-axis group indices.
- Raised if the keys of the dictionary within each group dictionary do
not contain the names (and hence tick intervals) for each y-axis
variable being plotted.
"""
if self.y_axis_tick_intervals:
all_repeated = check_non_repeated_vals_lists(
lists=[
self.y_axis_tick_intervals.keys(),
self._y_axis_limits_idcs.keys(),
],
allow_non_repeated=True,
)
if not all_repeated:
raise KeyError(
"Error when trying to plot results:\nNames of the groups "
"in the specified y-axis limits do not match those "
"generated from the results:\n- Provided names: "
f"{list(self.y_axis_tick_intervals.keys())}\n- Names "
f"should be: {list(self._y_axis_limits_idcs.keys())}\n"
)
for group_name, var_lims in self.y_axis_tick_intervals.items():
for var in self.y_axis_vars:
if var not in var_lims.keys():
raise KeyError(
"Error when trying to plot results:\nMissing "
f"tick interval for the y-axis variable '{var}' in "
f"the group '{group_name}'.\n"
)
else:
self.y_axis_tick_intervals = {}
for group in self._y_axis_limits_idcs.keys():
self.y_axis_tick_intervals[group] = {}
for var in self.y_axis_vars:
self.y_axis_tick_intervals[group][var] = None
def _sort_y_axis_limits_inputs(self) -> tuple[bool, list[list[str]]]:
"""Sorts inputs for setting the y-axis limits.
RETURNS
-------
share_across_vars : bool
- Whether or not the y-axis limits should be shared across all
variables being plotted on the y-axes.
extra_vars : list[list[str]]
- Additional values to combine with those of the variables being
plotted on the y-axes (such as standard error or standard deviation
values) when determining the y-axis limits.
"""
if self.y_axis_cap_min is None:
self.y_axis_cap_min = float("-inf")
if self.y_axis_cap_max is None:
self.y_axis_cap_max = float("inf")
share_across_vars = True
if self.y_axis_limits_grouping is not None:
if "Y_AXIS_VARS" in self.y_axis_limits_grouping:
share_across_vars = False
if self.var_measure is not None:
extra_vars = [
f"{var}_{self.var_measure}" for var in self.y_axis_vars
]
else:
extra_vars = None
return share_across_vars, extra_vars
def _sort_y_axis_labels(self) -> None:
"""Checks that y-axis labels are in the appropriate format,
automatically generating them based on the variables being plotted if
the labels are not specified.
RAISES
------
EntryLengthError
- Raised if the lengths of the y-axis labels does not match the number
of different variables being plotted on the y-axes. Only raised if
the y-axis labels are not 'None'.
- Raised if multiple variables are being plotted on the same y-axis,
but more than one y-axis label is given. Only raised if the y-axis
labels are not 'None'.
"""
if self.y_axis_labels is None:
if (
"Y_AXIS_VARS" in self.figure_grouping
or "Y_AXIS_VARS" in self.subplot_grouping
):
self.y_axis_labels = self.y_axis_vars
else:
self.y_axis_labels = [""]
self.y_axis_labels.extend(
f"{var} / " for var in self.y_axis_vars
)
self.y_axis_labels = self.y_axis_labels[:-3]
else:
if (
"Y_AXIS_VARS" in self.figure_grouping
or "Y_AXIS_VARS" in self.subplot_grouping
):
if len(self.y_axis_labels) != len(self.y_axis_vars):
raise EntryLengthError(
"Error when trying to plot results:\nThe number of "
"different variables being plotted separately on the "
f"y-axes ({len(self.y_axis_vars)}) and the number of "
f"y-axis labels ({len(self.y_axis_labels)}) do not "
"match."
)
else:
if len(self.y_axis_labels) != 1:
raise EntryLengthError(
"Error when trying to plot results:\nThe different "
"variables are being plotted together on the y-axes, "
"and so there can only be a single y-axis label, but "
f"there are {len(self.y_axis_labels)} labels."
)
def _sort_y_axis_scales_inputs(self) -> None:
"""Checks that y-axis scales are in the appropriate format,
automatically generating them based on the variables being plotted if
the scales are not specified.
RAISES
------
EntryLengthError
- Raised if the lengths of the y-axis scales do not match the number
of different variables being plotted on the y-axes. Only raised if
the y-axis scales are not 'None'.
- Raised if multiple variables are being plotted on the same y-axis,
but more than one y-axis scale is given. Only raised if the y-axis
scales are not 'None'.
"""
if self.y_axis_scales is None:
self.y_axis_scales = ["linear" for var in self.y_axis_vars]
else:
if (
"Y_AXIS_VARS" in self.figure_grouping
or "Y_AXIS_VARS" in self.subplot_grouping
):
if len(self.y_axis_scales) != len(self.y_axis_vars):
raise EntryLengthError(
"Error when trying to plot results:\nThe number of "
"different variables being plotted separately on the "
f"y-axes ({len(self.y_axis_vars)}) and the number of "
f"y-axis scales ({len(self.y_axis_labels)}) do not "
"match."
)
else:
if len(self.y_axis_scales) != 1:
raise EntryLengthError(
"Error when trying to plot results:\nThe different "
"variables are being plotted together on the y-axes, "
"and so there can only be a single y-axis scale, but "
f"there are {len(self.y_axis_labels)} scales."
)
def _sort_plot_grouping(self) -> None:
"""Sorts the figure and subplot groups, finding the indices of the
corresponding rows in the results."""
self._plot_grouping = {}
self._sort_figure_grouping()
self._sort_subplot_grouping()
def _sort_figure_grouping(self) -> None:
"""Sorts the groups for which indices of rows in the results should be
plotted on the same set of figures."""
if self.figure_grouping is not None:
figure_grouping_entries = [
entry
for entry in self.figure_grouping
if entry != "Y_AXIS_VARS"
]
else:
figure_grouping_entries = []
if figure_grouping_entries != []:
self._plot_grouping = get_group_names_idcs(
dataframe=self._results,
keys=figure_grouping_entries,
eligible_idcs=self._eligible_idcs,
replacement_idcs=self._eligible_idcs,
special_vals=self._special_values,
)
else:
self._plot_grouping["ALL"] = self._eligible_idcs
def _sort_subplot_grouping(self) -> None:
"""Sorts the groups for which indices of rows in the results should be
plotted on the same subplots on each set of figures."""
if self.subplot_grouping is not None:
subplot_grouping_entries = [
entry
for entry in self.subplot_grouping
if entry != "Y_AXIS_VARS"
]
else:
subplot_grouping_entries = []
for fig_group, idcs in self._plot_grouping.items():
if subplot_grouping_entries != []:
self._plot_grouping[fig_group] = get_group_names_idcs(
dataframe=self._results,
keys=subplot_grouping_entries,
eligible_idcs=self._plot_grouping[fig_group],
replacement_idcs=self._plot_grouping[fig_group],
special_vals=self._special_values,
)
else:
self._plot_grouping[fig_group] = {"ALL": deepcopy(idcs)}
def _plot_results(self) -> None:
"""Plots the results of the figure and subplot groups."""
if self.figure_layout is None:
self.figure_layout = [1, 1]
for figure_group, _ in self._plot_grouping.items():
if "Y_AXIS_VARS" in self.figure_grouping:
for y_axis_var in self.y_axis_vars:
self._plot_figure(
figure_group_name=figure_group,
y_axis_vars=[y_axis_var],
)
else:
self._plot_figure(
figure_group_name=figure_group,
y_axis_vars=self.y_axis_vars,
)
def _plot_figure(
self, figure_group_name: str, y_axis_vars: list[str]
) -> None:
"""Plots the results of the subplot groups belonging to a specified
figure group.
PARAMETERS
----------
figure_group_name : str
- Name of the figure group whose results should be plotted.
y_axis_vars : list[str]
- Names of the y-axis variables to plot on the same figure group.
"""
(
subplot_group_names,
subplot_group_indices,
) = self._get_subplot_group_info(
figure_group_name=figure_group_name, n_y_axis_vars=len(y_axis_vars)
)
n_subplot_groups = len(subplot_group_names)
n_subplots_per_fig = self.figure_layout[0] * self.figure_layout[1]
n_figs = int(np.ceil(n_subplot_groups / n_subplots_per_fig))
n_rows = self.figure_layout[0]
n_cols = self.figure_layout[1]
if self._verbose:
print(
f"Plotting {n_subplot_groups} subplot group(s) in a {n_rows} "
f"by {n_cols} pattern across {n_figs} figure(s).\n- Figure "
f"group: {figure_group_name}\n- Subplot groups: "
f"{subplot_group_names}\n"
)
still_to_plot = True
for fig_i in range(n_figs):
fig, axes = self._establish_figure(
n_rows=n_rows, n_cols=n_cols, title=figure_group_name
)
subplot_group_i = 0
for row_i in range(n_rows):
for col_i in range(n_cols):
if still_to_plot:
subplot_group_name = subplot_group_names[
subplot_group_i
]
subplot_group_idcs = subplot_group_indices[
subplot_group_i
]
self._plot_subplot(
axes[row_i, col_i],
subplot_group_name,
subplot_group_idcs,
y_axis_vars,
)
subplot_group_i += 1
if subplot_group_i == n_subplot_groups:
still_to_plot = False
extra_subplots = (
n_subplots_per_fig * n_figs - n_subplot_groups
)
else:
if extra_subplots > 0:
fig.delaxes(axes[row_i, col_i])
try:
maximise_figure_windows()
except NotImplementedError:
print(
"The figure could not be made fullscreen automatically "
"with the current combination of operating system and "
"plotting backend."
)
plt.tight_layout()
plt.show()
if self.save:
self._save_figure(
figure=fig,
figure_group=figure_group_name,
figure_n=fig_i + 1,
n_figures=n_figs,
y_axis_vars=y_axis_vars,
)
def _get_subplot_group_info(
self, figure_group_name: str, n_y_axis_vars: int
) -> tuple[list[str], list[list[int]]]:
"""Gets information about subplot groups for a given figure group.
PARAMETERS
----------
figure_group_name : str
- Name of the figure group.
n_y_axis_vars : int
- Number of y-axis variables being plotted.
- If multiple y-axis variables are not being plotted on the same
subplots, subplot group names and indices are multiplied by how many
y-axis variables are being plotted so that the correct number of
subplots allowing each y-axis variable to be plotted on a separate
subplot are created.
RETURNS
-------
subplot_group_names : list[str]
- Names of the subplot groups to plot.
subplot_group_indices : list[str]
- Indices of the rows of results in the subplot groups to plot.
"""
if "Y_AXIS_VARS" in self.subplot_grouping:
subplot_group_names = []
subplot_group_indices = []
subplot_group_names.extend(
[
[name] * n_y_axis_vars
for name in self._plot_grouping[figure_group_name].keys()
]
)
subplot_group_indices.extend(
[
[idcs] * n_y_axis_vars
for idcs in self._plot_grouping[figure_group_name].values()
]
)
else:
subplot_group_names = list(
self._plot_grouping[figure_group_name].keys()
)
subplot_group_indices = list(
self._plot_grouping[figure_group_name].values()
)
return subplot_group_names, subplot_group_indices
def _establish_figure(
self, n_rows: int, n_cols: int, title: str
) -> tuple[plt.figure, plt.Axes]:
"""Creates a figure with the desired number of subplot rows and columns,
with a specified title.
PARAMETERS
----------
n_rows : int
- Number of subplot rows in the figure.
n_cols : int
- Number of subplot columns in the figure.
title : str
- Title of the figure.
RETURNS
-------
fig : matplotlib pyplot figure
- The created figure.
axes : matplotlib pyplot Axes
- The Axes object of subplots on the figure.
"""
fig, axes = plt.subplots(n_rows, n_cols)
plt.tight_layout()
fig.suptitle(self._get_figure_title(group_name=title), fontsize=10)
axes = self._sort_figure_axes(axes=axes, n_rows=n_rows, n_cols=n_cols)
return fig, axes
def _get_figure_title(self, group_name: str) -> str:
"""Generates a title for a figure based on the identical entries in the
results (if any), and the group of results being plotted on the figure.
PARAMETERS
----------
group_name : str
- Name of the group of results being plotted on the figure.
RETURNS
-------
str
- Title of the figure in two lines. Line one: identical entry names
and values. Line two: group name.
"""
if self.identical_keys is not None:
identical_entries_title = combine_col_vals_df(
dataframe=self._results,
keys=self.identical_keys,
idcs=[0],
special_vals=self._special_values,
)[0]
else:
identical_entries_title = ""
return f"{identical_entries_title}\n{group_name}"
def _sort_figure_axes(
self, axes: plt.Axes, n_rows: int, n_cols: int
) -> plt.Axes:
"""Sorts the pyplot Axes object by adding an additional row and/or
column if there is only one row and/or column in the object, useful for
later indexing.
PARAMETERS
----------
axes : matplotlib pyplot Axes
- The axes to sort.
n_rows : int
- Number of rows in the axes.
n_cols : int
- Number of columns in the axes.
RETURNS
-------
axes : matplotlib pyplot Axes
- The sorted axes.
"""
if n_rows == 1 and n_cols == 1:
axes = np.asarray([[axes]])
elif n_rows == 1 and n_cols > 1:
axes = np.vstack((axes, [None] * n_cols))
elif n_cols == 1 and n_rows > 1:
axes = np.vstack((axes, [None] * n_rows)).T
return axes
@abstractmethod
def _plot_subplot(
self,
subplot: plt.Axes,
group_name: str,
group_idcs: list[int],
y_axis_vars: list[str],
) -> None:
"""Plots the results of a specified subplot group belonging to a single
figure group.
PARAMETERS
----------
subplot : matplotlib pyplot Axes
- The subplot to add features to.
group_name : str
- Name of the subplot group whose results are being plotted.
group_idcs : list[int]
- Indices of the results in the subplot group to plot.
y_axis_vars : list[str]
- Names of the y-axis variables to plot on the same figure group.
"""
def _establish_subplot(
self,
subplot: plt.Axes,
title: str,
y_axis_vars: list[str],
) -> None:
"""Adds a title and axis labels to the subplot.
PARAMETERS
----------
subplot : matplotlib pyplot Axes
- The subplot to add features to.
title : str
- Title of the subplot.
y_axis_vars : list[str]
- Names of the y-axis variables being plotted, used to generate the
y-axis label.
"""
subplot.set_title(title)
subplot.set_xlabel(self.x_axis_label)
if self.x_axis_scale is not None:
subplot.set_xscale(self.x_axis_scale)
if len(y_axis_vars) == 1:
y_label = self.y_axis_labels[self.y_axis_vars.index(y_axis_vars[0])]
y_scale = self.y_axis_scales[self.y_axis_vars.index(y_axis_vars[0])]
else:
y_label = self.y_axis_labels
y_scale = self.y_axis_scales
subplot.set_ylabel(y_label)
subplot.set_yscale(y_scale)
def _get_y_axis_limits_group(self, idcs: list[int]) -> str:
"""Finds which y-axis limit group the results of the given indices
belongs to.
PARAMETERS
----------
idcs : list[int]
- Indices in the results to find their y-axis limit group.
RETURNS
-------
group_name : str
- Name of the y-axis limit group.
RAISES
------
ValueError
- Raised if the indices do not belong to any y-axis limit group.
"""
group_found = False
for group_name, group_val in self._y_axis_limits_idcs.items():
if set(idcs) <= set(group_val):
group_found = True
break
if not group_found:
raise ValueError(
"Error when trying to plot the results:\nThe row indices of "
f"results {idcs} are not present in any of the y-axis limit "
"groups."
)
return group_name
def _set_y_axis_tick_interval(
self, subplot: plt.Axes, interval: Union[int, float, None]
) -> None:
"""Sets the tick intervals for the y-axis of a subplot.
PARAMETERS
----------
subplot : matplotlib pyplot Axes
- The subplot to add features to.
interval : int | float | None