forked from sythello/ChartDialog
/
plotter.py
2049 lines (1801 loc) · 74.2 KB
/
plotter.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 matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import json
import os
from tqdm import tqdm
import pickle
from collections import OrderedDict
import argparse
'''
Param name design: natural name k_nat = k.capitalize().split('_')
About None:
Empty string '' should never be passed in; should use None, which will be treated as ''.
Otherwise, when None is in the valid value set and means empty, no ambiguity.
When None is not in the valid value set and means default, be careful... (see following)
For params of '...size' and '...width', use 0 to specify disabling it. For example, line_width=0 means no line.
When None is not in the valid value set, None shoule be passed in when not applicable or disabled by other slots.
For example, when marker_size=0, marker_edge_width=None; when plot_type=line, bin_edge_width=None.
Default value: used to make an empty or default plot, especially when plot type is wrong.
'''
PLOT_TYPES = [
'line',
'histogram',
'scatter',
'bar',
'matrix_display',
'contour',
'streamline',
'surface_3d',
'pie'
]
PLOT_TYPE_GROUPS = [
['bar plot', 'line chart', 'pie chart'],
['streamline plot', 'contour plot'],
['histogram', 'scatter plot'],
['3D surface', 'matrix display'] # Easy group
]
TUTORIAL_TYPE_GROUPS = [
['bar plot', 'line chart', 'pie chart'],
['streamline plot', 'contour plot', 'contour plot'],
['histogram', 'scatter plot', 'scatter plot'],
['3D surface', 'matrix display'] # Easy group
]
# Assume 3rd tutorial polarized
def plotter(
x, y=None, z=None, u=None, v=None, c_type=None, # c_type: the correct type for input data
plot_type=None, # User specified type
# ------- Line -------
line_color=None, # {None, colors...}
line_style=None, # {None (''), '-', '--', '-.', ':'}
line_width=None, # {1, 3, 5}
marker_type=None, # {None, 'o', 'v', '^', 'D'}
marker_size=None, # {5, 9, 13}
marker_edge_width=None, # {1, 3}
marker_edge_color=None,
marker_face_color=None, # {None, colors...}
marker_interval=None, # {1, 2, 5}
# ------- Histogram -------
hist_range=(140, 200), # Fixed to correct value
number_of_bins=None, # {6, 8, 10, 12}
bar_relative_width=None, # {0.6, 0.8, 1}, already natural
bar_edge_width=0, # {1, 3}
bar_edge_color=None,
bar_face_color=None,
# ------- Scatter -------
## marker_type=None, # {'o', 'v', '^', 'D'}
## marker_size=0, # {5, 9, 13, diff}
## marker_edge_width=None, # {1, 3}
## marker_edge_color=None,
## marker_face_color=None, # {colors..., diff}
color_map=None,
# ------- Bar -------
bar_base=None, # Fixed to correct value (min - c)
bar_orientation='vertical',
bar_width=None, # {0.6, 0.8, 1}, already natural
bar_height=None, # {0.6, 0.8, 1}, already natural
## bar_edge_width=0, # {1, 3}
## bar_edge_color=None,
## bar_face_color=None,
# ------- Matrix_display (imshow) -------
## color_map=None,
# ------- Contour -------
contour_plot_type=None, # {'lined', 'filled'}
## color_map=None,
number_of_levels=None, # {6, 10, 15}, natural
## line_style=None, # {'-', '--', '-.', ':'}
## line_width=0, # {1, 3, 5}
# ------- Streamline -------
density=0.5, # {0.25, 0.5, 0.75}
## line_color=None, # {colors..., diff}
## color_map=None,
## line_width=None, # {1, 3, 5, diff}
arrow_size=None, # {1, 3}
arrow_style=None, # {lined('->'), solid('-|>')}
# ------- surface_3d -------
surface_color=None, # {colors..., diff}
## color_map=None,
# ------- Pie -------
explode=None, # {None, 0.03, 0.1}
precision_digits=0, # {0, 1, 2, 3}
percentage_distance_from_center=0.6, # {0.45, 0.6, 0.75}
label_distance_from_center=1.1, # {1.1, 1.25}
radius=None, # {0.75, 1, 1.25}
section_edge_width=None, # {None, 1, 3}
section_edge_color=None,
# ------- Errorbar -------
show_error_bar=False,
error_bar_cap_size=0, # {3, 6, 10}
error_bar_cap_thickness=0, # {1, 3}
error_bar_color=None,
# ------- Colorbar -------
color_bar_orientation='vertical',
color_bar_length=None, # {0.8, 1}, ratio of length vs. plot height/width
color_bar_thickness=None, # {0.1, 0.05, 0.033}, ratio of width vs. length
# ------- Shared -------
# plot_title=None, # Active: all (plot_type.capitalize() + '\n\n\n')
# x_axis_label=None, # Fixed to 'X': line, hist, scatter, bar, contour, streamline, surface_3d
# y_axis_label=None, # Fixed to 'Y': line, hist, scatter, bar, contour, streamline, surface_3d
# z_axis_label=None, # Fixed to 'Z': surface_3d
data_series_name=None, # Active: line, hist, scatter (but not vary), bar
font_size=None, # {8, 10, 12}; active: all
invert_x_axis=False, # Active: line, hist, scatter, bar, contour, streamline, surface_3d
invert_y_axis=False, # Active: line, hist, scatter, bar, contour, streamline, surface_3d
invert_z_axis=False, # Active: surface_3d
## Grid lines: active: line, histogram, scatter, bar, contour, streamline
grid_line_type=None, # {None, 'horizontal', 'vertical', 'both'} -> Primary
grid_line_color=None, # {colors..., favor black & gray}
grid_line_style=None, # {'-', '--', '-.', ':'}
grid_line_width=None, # {0.5, 1}
## Axis position: active: line, histogram, scatter, bar, imshow, contour, streamline
x_axis_position='bottom',
y_axis_position='left',
## Scale: active: line, scatter, contour (both axis); bar (non-base axis); histogram, imshow, streamline, surface_3d (always linear)
x_axis_scale='linear',
y_axis_scale='linear',
polarize=False, # Active: line, hist, contour (can be True); scatter, bar, streamline (always False)
save_legend=False):
fig = plt.figure(figsize=(8, 6))
if polarize and plot_type not in {'line', 'scatter', 'contour'}:
print('Invalid: polarize = True with plot_type = {}'.format(plot_type))
if polarize and plot_type in {'line', 'scatter', 'contour'}:
ax = fig.gca(projection='polar')
elif plot_type == 'surface_3d':
ax = fig.gca(projection='3d')
else:
ax = fig.gca()
# Dummy data, avoiding error
# if y is None:
# y = x
# if z is None:
# z = np.zeros_like(x)
# if u is None:
# u = np.zeros_like(x)
# if v is None:
# v = np.zeros_like(y)
if plot_type is not None and c_type != plot_type:
print('Type error: c_type = {}, plot_type = {}. Forcing plot_type = None'.format(c_type, plot_type))
plot_type = None
# Universal None transforming (for -style, -size, -width)
if line_style is None:
line_style = ''
if line_width is None:
line_width = 0
if marker_size is None:
marker_size = 0
if marker_edge_width is None:
marker_edge_width = 0
if bar_edge_width is None:
bar_edge_width = 0
if explode is None:
explode = 0
artist = None
# Do plotting based on type
if plot_type == 'line':
plot_func_kwargs = {
'color' : line_color,
'linestyle' : line_style,
'linewidth' : line_width,
'marker' : marker_type,
'markersize' : marker_size,
'markeredgewidth' : marker_edge_width,
'markeredgecolor' : marker_edge_color,
'markerfacecolor' : marker_face_color,
'markevery' : marker_interval,
'label' : data_series_name}
artist = ax.plot(x, y, **plot_func_kwargs)
if show_error_bar:
# Can show error bar w/o markers
errorbar_func_kwargs = {
'capsize': error_bar_cap_size,
'capthick': error_bar_cap_thickness,
'ecolor': error_bar_color,
'elinewidth': 3,
# 'markeredgewidth': 3,
'errorevery': 1 if marker_interval is None else marker_interval,
'linestyle': '',
}
ax.errorbar(x, y, yerr=z, **errorbar_func_kwargs)
elif plot_type == 'histogram':
func_kwargs = {
'bins' : number_of_bins,
'range' : hist_range,
'rwidth' : bar_relative_width,
'color' : bar_face_color,
'linewidth' : bar_edge_width,
'edgecolor' : bar_edge_color,
'label' : data_series_name}
ax.hist(x, **func_kwargs)
artist = Rectangle((0,0), 1, 1, facecolor=bar_face_color, edgecolor=bar_edge_color, linewidth=bar_edge_width) # Fake artist for legend
elif plot_type == 'scatter':
# slots: [marker_type, marker_size, marker_edge_width, marker_edge_color, marker_face_color, color_map]
func_kwargs = {
'marker' : marker_type,
's' : (z ** 2) if marker_size == 'diff' else (marker_size ** 2),
'c' : z if marker_face_color == 'diff' else marker_face_color,
'linewidths' : marker_edge_width,
'edgecolors' : marker_edge_color,
'label' : data_series_name}
if marker_face_color == 'diff':
func_kwargs['cmap'] = color_map
artist = ax.scatter(x, y, **func_kwargs)
elif plot_type == 'bar':
# slots: [bar_orientation, bar_relative_width, bar_relative_height, bar_edge_width, bar_edge_color, bar_face_color]
func_kwargs = {
'color' : bar_face_color,
'linewidth' : bar_edge_width,
'edgecolor' : bar_edge_color,
'label' : data_series_name,
'error_kw' : {'capsize': error_bar_cap_size, 'capthick': error_bar_cap_thickness, 'ecolor': error_bar_color}}
if isinstance(x[0], str):
print('X are strings, can\'t have error bar')
if bar_orientation == 'horizontal':
# print('--- bar-horizontal ---')
func_kwargs['height'] = bar_height
func_kwargs['left'] = bar_base
artist = ax.barh(x, y, xerr=z if show_error_bar else None, **func_kwargs)
elif bar_orientation == 'vertical':
# print('--- bar-vertical ---')
func_kwargs['width'] = bar_width
func_kwargs['bottom'] = bar_base
artist = ax.bar(x, y, yerr=z if show_error_bar else None, **func_kwargs)
else:
print('Invalid bar_orientation: {}'.format(bar_orientation))
elif plot_type == 'matrix_display':
artist = ax.imshow(x, cmap=color_map)
elif plot_type == 'contour':
func_kwargs = {
# 'levels': number_of_levels,
'levels': np.linspace(z.min(), z.max(), number_of_levels + 1),
'cmap': color_map
}
if contour_plot_type == 'filled':
artist = ax.contourf(x, y, z, **func_kwargs)
elif contour_plot_type == 'lined':
func_kwargs['linewidths'] = line_width
func_kwargs['linestyles'] = line_style
artist = ax.contour(x, y, z, **func_kwargs)
else:
print('Invalid contour_plot_type: {}'.format(contour_plot_type))
elif plot_type == 'streamline':
func_kwargs = {
'color': z if line_color == 'diff' else line_color,
'linewidth': (0.5 + 4.5 * (z - z.min()) / (z.max() - z.min())) if line_width == 'diff' else line_width,
'density': density,
'arrowsize': arrow_size,
'arrowstyle': arrow_style
}
if line_color == 'diff':
func_kwargs['cmap'] = color_map
# print(func_kwargs)
artist_ = ax.streamplot(x, y, u, v, **func_kwargs)
artist = artist_.lines
elif plot_type == 'surface_3d':
if surface_color == 'diff':
artist = ax.plot_surface(x, y, z, cmap=color_map)
else:
artist = ax.plot_surface(x, y, z, color=surface_color)
elif plot_type == 'pie':
# slots: [explode, precision_digits, percentage_distance_from_center, label_distance_from_center, radius, section_edge_width, section_edge_color]
func_kwargs = {
'explode': [explode] * len(x),
'autopct': '%.{}f%%'.format(precision_digits),
'pctdistance': percentage_distance_from_center,
'labeldistance': label_distance_from_center,
'radius': radius,
'wedgeprops': {'edgecolor': section_edge_color, 'linewidth': section_edge_width},
'textprops': {'fontsize': font_size}
}
_wedges, _labels, _pcts = ax.pie(y, labels=x, **func_kwargs)
# Workaround for label fontsize problem
for _l in _labels:
_l.set_fontsize(font_size)
elif plot_type is not None:
print('Invalid plot type: {}'.format(plot_type))
return fig
if plot_type is not None and color_map is not None:
func_kwargs = {
'orientation': color_bar_orientation,
'shrink': color_bar_length,
'aspect': 1.0 / color_bar_thickness,
'pad': 0.15
}
fig.colorbar(artist, ax=ax, **func_kwargs)
if plot_type is not None:
plot_title = PLOT_TYPE_V2S[plot_type].capitalize() + '\n\n\n'
ax.set_title(plot_title)
if plot_type not in {'pie'}:
ax.tick_params(labelsize=font_size)
legend_possible = (plot_type in {'line', 'histogram', 'bar'}) or (plot_type == 'scatter' and marker_face_color != 'diff')
if data_series_name is not None:
if not legend_possible:
print('Invalid: data_series_name given for {}{}'.format(plot_type, '-diff' if plot_type == 'scatter' else ''))
else:
ax.legend(fontsize=font_size)
if x_axis_scale == 'log':
if (plot_type not in {'line', 'scatter', 'bar', 'contour'}) or (plot_type == 'bar' and bar_orientation == 'vertical'):
print('Invalid x_axis_scale: {} for {}{}'.format(x_axis_scale, plot_type, '-' + bar_orientation if plot_type == 'bar' else ''))
else:
ax.set_xscale('log')
if y_axis_scale == 'log':
if (plot_type not in {'line', 'scatter', 'bar', 'contour'}) or (plot_type == 'bar' and bar_orientation == 'horizontal'):
print('Invalid y_axis_scale: {} for {}{}'.format(y_axis_scale, plot_type, '-' + bar_orientation if plot_type == 'bar' else ''))
else:
ax.set_yscale('log')
x_axis_label = 'X'
y_axis_label = 'Y'
z_axis_label = 'Z'
if plot_type != 'pie' and (not polarize):
ax.set_xlabel(x_axis_label, fontsize=font_size)
if plot_type != 'pie' and (not polarize):
ax.set_ylabel(y_axis_label, fontsize=font_size)
if plot_type == 'surface_3d':
ax.set_zlabel(z_axis_label, fontsize=font_size)
if invert_x_axis:
if plot_type == 'pie':
print('Invalid: invert_x_axis set for {}'.format(plot_type))
elif plot_type == 'surface_3d':
ax.set_xlim3d(ax.get_xlim3d()[::-1])
else:
ax.invert_xaxis()
if invert_y_axis:
if plot_type == 'pie':
print('Invalid: invert_y_axis set for {}'.format(plot_type))
elif plot_type == 'surface_3d':
ax.set_ylim3d(ax.get_ylim3d()[::-1])
else:
ax.invert_yaxis()
if invert_z_axis:
if plot_type != 'surface_3d':
print('Invalid: invert_z_axis set for {}'.format(plot_type))
elif plot_type == 'surface_3d':
ax.set_zlim3d(ax.get_zlim3d()[::-1])
# else:
# ax.invert_zaxis()
if plot_type not in {'surface_3d', 'pie', 'matrix_display'}:
# Can add grid lines
if grid_line_type in {'vertical', 'both'}:
ax.xaxis.grid(True, color=grid_line_color, linewidth=grid_line_width, linestyle=grid_line_style)
else:
ax.xaxis.grid(False)
if grid_line_type in {'horizontal', 'both'}:
ax.yaxis.grid(True, color=grid_line_color, linewidth=grid_line_width, linestyle=grid_line_style)
else:
ax.yaxis.grid(False)
if plot_type in {'contour'}:
ax.set_axisbelow(False)
else:
ax.set_axisbelow(True)
if (plot_type not in {'surface_3d', 'pie'}) and (not polarize):
# Can do axis moving, ticklabels setting
if x_axis_position == 'top':
ax.xaxis.tick_top()
ax.xaxis.set_label_position('top')
elif x_axis_position == 'bottom':
ax.xaxis.tick_bottom()
ax.xaxis.set_label_position('bottom')
elif x_axis_position is not None:
print('Invalid x_axis_position: {}'.format(x_axis_position))
if y_axis_position == 'right':
ax.yaxis.tick_right()
ax.yaxis.set_label_position('right')
elif y_axis_position == 'left':
ax.yaxis.tick_left()
ax.yaxis.set_label_position('left')
elif y_axis_position is not None:
print('Invalid y_axis_position: {}'.format(y_axis_position))
# To solve title cutting-off
fig.tight_layout()
if save_legend:
fig_legend = plt.figure(figsize=(4, 0.5))
if legend_possible:
fig_legend.legend([artist], [label], loc='center', handlelength=12)
return fig, fig_legend
else:
return fig
### Constant global dictionaries for slot & value mapping, all slots
def _invert_dict(d):
return dict([(v, k) for k, v in d.items()])
## V: value, S: natural string
COLOR_V2S = {
'red': 'red',
'orange': 'orange',
'green': 'green',
'blue': 'blue',
'm': 'magenta',
'gray': 'gray',
'black': 'black',
'diff': 'different'
}
COLOR_S2V = _invert_dict(COLOR_V2S)
WIDTH_V2S = {
0.8: 'very thin',
1.2: 'thin',
3: 'medium',
5: 'thick',
'diff': 'different'
}
WIDTH_S2V = _invert_dict(WIDTH_V2S)
PLOT_TYPE_V2S = {
'line': 'line chart',
'histogram': 'histogram',
'scatter': 'scatter plot',
'bar': 'bar plot',
'matrix_display': 'matrix display',
'contour': 'contour plot',
'streamline': 'streamline plot',
'surface_3d': '3D surface',
'pie': 'pie chart'
}
PLOT_TYPE_S2V = _invert_dict(PLOT_TYPE_V2S)
LINE_STYLE_V2S = {
'-' : 'solid',
'--' : 'dashed',
'-.' : 'dashed dots',
':' : 'dotted',
}
LINE_STYLE_S2V = _invert_dict(LINE_STYLE_V2S)
MARKER_TYPE_V2S = {
'o' : 'circles',
'v' : 'down triangles',
'^' : 'triangles',
'D' : 'diamonds',
}
MARKER_TYPE_S2V = _invert_dict(MARKER_TYPE_V2S)
MARKER_SIZE_V2S = {
8: 'small',
12: 'medium',
16: 'large',
'diff': 'different'
}
MARKER_SIZE_S2V = _invert_dict(MARKER_SIZE_V2S)
COLOR_MAP_V2S = {
'Reds': 'transparent to solid red',
'Blues': 'transparent to solid blue',
'Greens': 'transparent to solid green',
'YlOrRd': 'transparent yellow to solid red',
'GnBu': 'transparent green to solid blue',
'BuPu': 'transparent blue to dark purple',
'spring': 'magenta to yellow',
'autumn': 'red to yellow',
'cool': 'light cyan to magenta',
'PRGn': 'purple to white to green',
'RdBu': 'red to white to blue',
'RdYlGn': 'red to yellow to green'
}
COLOR_MAP_S2V = _invert_dict(COLOR_MAP_V2S)
DENSITY_V2S = {
0.25: 'loose',
0.5: 'medium',
0.75: 'dense'
}
DENSITY_S2V = _invert_dict(DENSITY_V2S)
ARROW_SIZE_V2S = {
2.5: 'small',
4.5: 'large'
}
ARROW_SIZE_S2V = _invert_dict(ARROW_SIZE_V2S)
ARROW_STYLE_V2S = {
'->': 'curve',
'-|>': 'solid'
}
ARROW_STYLE_S2V = _invert_dict(ARROW_STYLE_V2S)
EXPLODE_V2S = {
0.03: 'small',
0.1: 'large'
}
EXPLODE_S2V = _invert_dict(EXPLODE_V2S)
PERCENTAGE_DISTANCE_FROM_CENTER_V2S = {
0.45: 'near',
0.6: 'medium',
0.75: 'far'
}
PERCENTAGE_DISTANCE_FROM_CENTER_S2V = _invert_dict(PERCENTAGE_DISTANCE_FROM_CENTER_V2S)
LABEL_DISTANCE_FROM_CENTER_V2S = {
1.1: 'near',
1.25: 'far'
}
LABEL_DISTANCE_FROM_CENTER_S2V = _invert_dict(LABEL_DISTANCE_FROM_CENTER_V2S)
RADIUS_V2S = {
0.8: 'small',
1: 'medium',
1.2: 'large'
}
RADIUS_S2V = _invert_dict(RADIUS_V2S)
ERROR_BAR_CAP_SIZE_V2S = {
4 : 'small',
7 : 'medium',
10 : 'large'
}
ERROR_BAR_CAP_SIZE_S2V = _invert_dict(ERROR_BAR_CAP_SIZE_V2S)
ERROR_BAR_CAP_THICKNESS_V2S = {
1 : 'thin',
3 : 'thick'
}
ERROR_BAR_CAP_THICKNESS_S2V = _invert_dict(ERROR_BAR_CAP_THICKNESS_V2S)
COLOR_BAR_LENGTH_V2S = {
0.8 : 'short',
1 : 'long'
}
COLOR_BAR_LENGTH_S2V = _invert_dict(COLOR_BAR_LENGTH_V2S)
COLOR_BAR_THICKNESS_V2S = {
0.1 : 'thick',
0.05 : 'medium',
0.033 : 'thin'
}
COLOR_BAR_THICKNESS_S2V = _invert_dict(COLOR_BAR_THICKNESS_V2S)
FONT_SIZE_V2S = {
8 : 'small',
10 : 'medium',
12 : 'large'
}
FONT_SIZE_S2V = _invert_dict(FONT_SIZE_V2S)
SLOTS_NEED_MAPPING = ['plot_type', 'marker_type', 'marker_size', 'color_map', \
'density', 'arrow_size', 'arrow_style', \
'explode', 'percentage_distance_from_center', 'label_distance_from_center', 'radius', \
'error_bar_cap_size', 'error_bar_cap_thickness', 'color_bar_length', 'color_bar_thickness', 'font_size']
# 53 slots
# Default dict, initial state
DEFAULT_DICT = {
'plot_type' : None,
# ------- Line -------
'line_color' : None,
'line_style' : None,
'line_width' : None,
'marker_type' : None,
'marker_size' : None,
'marker_edge_width' : None,
'marker_edge_color' : None,
'marker_face_color' : None,
'marker_interval' : None,
# ------- Histogram -------
'number_of_bins' : None,
'bar_relative_width' : None,
'bar_edge_width' : None,
'bar_edge_color' : None,
'bar_face_color' : None,
# ------- Scatter -------
## marker_type,
## marker_size,
## marker_edge_width,
## marker_edge_color,
## marker_face_color,
'color_map' : None,
# ------- Bar -------
'bar_orientation' : None,
'bar_width' : None, # {0.6, 0.8, 1}, already natural
'bar_height' : None, # {0.6, 0.8, 1}, already natural
## bar_edge_width,
## bar_edge_color,
## bar_face_color,
# ------- Matrix_display (imshow) -------
## color_map=None,
# ------- Contour -------
'contour_plot_type': None, # {'lined', 'filled'}
## color_map=None,
'number_of_levels': None, # {6, 10, 15}, natural
## line_style=None, # {'-', '--', '-.', ':'}
## line_width=0, # {1, 3, 5}
# ------- Streamline -------
'density': None, # {0.25, 0.5, 0.75}
## line_color=None, # {colors..., diff}
## color_map=None,
## line_width=None, # {1, 3, 5, diff}
'arrow_size': None, # {1, 3}
'arrow_style': None, # {lined('->'), solid('-|>')}
# ------- surface_3d -------
'surface_color': None, # {colors..., diff}
## color_map=None,
# ------- Pie -------
'explode': None, # {None, 0.03, 0.1}
'precision_digits': None, # {0, 1, 2, 3}
'percentage_distance_from_center': None, # {0.45, 0.6, 0.75}
'label_distance_from_center': None, # {1.1, 1.25}
'radius': None, # {0.75, 1, 1.25}
'section_edge_width': None, # {None, 1, 3}
'section_edge_color': None,
# ------- Errorbar -------
'show_error_bar' : None,
'error_bar_cap_size' : None, # {3, 7, 10}, can't be smaller than line_width, otherwise cap invisible
'error_bar_cap_thickness' : None, # {1, 3}
'error_bar_color' : None,
# ------- Colorbar -------
'color_bar_orientation' : None,
'color_bar_length' : None, # {0.8, 1}, ratio of length vs. plot height/width
'color_bar_thickness' : None, # {0.1, 0.05, 0.033}, ratio of width vs. length
# ------- Shared -------
# plot_title=None, # Active: all (plot_type.capitalize() + '\n\n\n')
# x_axis_label=None, # Fixed to 'X': line, hist, scatter, bar, contour, streamline, surface_3d
# y_axis_label=None, # Fixed to 'Y': line, hist, scatter, bar, contour, streamline, surface_3d
# z_axis_label=None, # Fixed to 'Z': surface_3d
'data_series_name' : None, # Active: line, hist, scatter (but not vary), bar
'font_size' : None, # {8, 10, 12}; active: all
'invert_x_axis' : None, # Active: line, hist, scatter, bar, contour, streamline, surface_3d
'invert_y_axis' : None, # Active: line, hist, scatter, bar, contour, streamline, surface_3d
'invert_z_axis' : None, # Active: surface_3d
## Grid lines: active: line, histogram, scatter, bar, contour, streamline
'grid_line_type' : None, # {None, 'horizontal', 'vertical', 'both'} -> Primary
'grid_line_color' : None, # {colors..., favor black & gray}
'grid_line_style' : None, # {'-', '--', '-.', ':'}
'grid_line_width' : None, # {0.5, 1}
## Axis position: active: line, histogram, scatter, bar, imshow, contour, streamline
'x_axis_position' : None,
'y_axis_position' : None,
## Scale: active: line, scatter, contour (both axis); bar (non-base axis); histogram, imshow, streamline, surface_3d (always linear)
'x_axis_scale' : None,
'y_axis_scale' : None,
'polarize' : None, # Active: line, hist, contour (can be True); scatter, bar, streamline (always False)
}
## This is (approximately) the same as Operator Panel order
SLOTS_NAT_ORDER = [
'plot_type',
# ------- Contour -------
'contour_plot_type', # {'lined', 'filled'}
## color_map=None,
'number_of_levels', # {6, 10, 15}, natural
## line_style=None, # {'-', '--', '-.', ':'}
## line_width=0, # {1, 3, 5}
# ------- Streamline -------
'density', # {0.25, 0.5, 0.75}
## line_color=None, # {colors..., diff}
## color_map=None,
## line_width=None, # {1, 3, 5, diff}
'arrow_size', # {1, 3}
'arrow_style', # {lined('->'), solid('-|>')}
# ------- 3D surface -------
'surface_color', # {colors..., diff}
## color_map=None,
# ------- Line -------
'line_style',
'line_width',
'line_color',
'marker_type',
'marker_size',
'marker_face_color',
'marker_edge_width',
'marker_edge_color',
'marker_interval',
# ------- Histogram -------
'number_of_bins',
'bar_relative_width',
'bar_face_color',
'bar_edge_width',
'bar_edge_color',
# ------- Bar -------
'bar_orientation',
'bar_width', # {0.6, 0.8, 1}, already natural
'bar_height', # {0.6, 0.8, 1}, already natural
## bar_edge_width,
## bar_edge_color,
## bar_face_color,
# ------- Scatter -------
## marker_type,
## marker_size,
## marker_edge_width,
## marker_edge_color,
## marker_face_color,
'color_map',
# ------- Matrix_display (imshow) -------
## color_map=None,
# ------- Pie -------
'explode', # {None, 0.03, 0.1}
'precision_digits', # {0, 1, 2, 3}
'percentage_distance_from_center', # {0.45, 0.6, 0.75}
'label_distance_from_center', # {1.1, 1.25}
'radius', # {0.75, 1, 1.25}
'section_edge_width', # {None, 1, 3}
'section_edge_color',
# ------- Errorbar -------
'show_error_bar',
'error_bar_cap_size', # {3, 7, 10}, can't be smaller than line_width, otherwise cap invisible
'error_bar_cap_thickness', # {1, 3}
'error_bar_color',
# ------- Colorbar -------
'color_bar_orientation',
'color_bar_length', # {0.8, 1}, ratio of length vs. plot height/width
'color_bar_thickness', # {0.1, 0.05, 0.033}, ratio of width vs. length
# ------- Shared -------
# plot_title=None, # Active: all (plot_type.capitalize() + '\n\n\n')
# x_axis_label=None, # Fixed to 'X': line, hist, scatter, bar, contour, streamline, surface_3d
# y_axis_label=None, # Fixed to 'Y': line, hist, scatter, bar, contour, streamline, surface_3d
# z_axis_label=None, # Fixed to 'Z': surface_3d
'polarize', # Active: line, hist, contour (can be True); scatter, bar, streamline (always False)
## Scale: active: line, scatter, contour (both axis); bar (non-base axis); histogram, imshow, streamline, surface_3d (always linear)
'x_axis_scale',
'y_axis_scale',
## Axis position: active: line, histogram, scatter, bar, imshow, contour, streamline
'x_axis_position',
'y_axis_position',
'data_series_name', # Active: line, hist, scatter (but not vary), bar
'font_size', # {8, 10, 12}; active: all
'invert_x_axis', # Active: line, hist, scatter, bar, contour, streamline, surface_3d
'invert_y_axis', # Active: line, hist, scatter, bar, contour, streamline, surface_3d
'invert_z_axis', # Active: surface_3d
## Grid lines: active: line, histogram, scatter, bar, contour, streamline
'grid_line_type', # {None, 'horizontal', 'vertical', 'both'} -> Primary
'grid_line_color', # {colors..., favor black & gray}
'grid_line_style', # {'-', '--', '-.', ':'}
'grid_line_width', # {0.5, 1}
]
### Auxiliary plotter/sampling functions
def plotter_kwargs_unnaturalize(**kwargs):
'''
Carry out plotter() functionality with natural-form values (keys are the same as plotter())
'''
call_params = {}
for k, v in kwargs.items():
_v = v
if v is None or v == '':
_v = None
elif k.endswith('color'):
_v = COLOR_S2V[v]
elif k.endswith('line_width') or k.endswith('edge_width'):
_v = WIDTH_S2V[v]
elif k.endswith('line_style'):
_v = LINE_STYLE_S2V[v]
elif k in SLOTS_NEED_MAPPING:
map_name = k.upper() + '_S2V'
map_dict = eval(map_name)
if v not in map_dict:
print(kwargs)
print(k, v)
_v = map_dict[v]
call_params[k] = _v
return call_params
def plotter_kwargs_type_uniformize(kwargs):
# Change all numpy types back to python types
plotter_kwargs = dict(kwargs)
for k in plotter_kwargs:
try:
plotter_kwargs[k] = plotter_kwargs[k].item()
except:
pass
return plotter_kwargs
def plotter_kwargs_validate_polarize_axis(kwargs, hard=False):
if kwargs is None:
return None
plotter_kwargs = dict(kwargs)
if plotter_kwargs['polarize']:
# Polar, disable incompatible slots
plotter_kwargs['show_error_bar'] = None
plotter_kwargs['x_axis_position'] = None
plotter_kwargs['y_axis_position'] = None
plotter_kwargs['x_axis_scale'] = None
plotter_kwargs['y_axis_scale'] = None
plotter_kwargs['invert_x_axis'] = None
plotter_kwargs['invert_y_axis'] = None
if plotter_kwargs['line_width'] == 'thick':
# For line: look weird, discard
return None
elif hard:
if (plotter_kwargs['plot_type'] not in {'pie chart'}) and (plotter_kwargs['invert_x_axis'] != True) and (plotter_kwargs['invert_y_axis'] != True):
# No inverted axis, discard
return None
if (plotter_kwargs['plot_type'] in {'line chart', 'scatter plot', 'bar plot', 'contour plot'}) and (plotter_kwargs['x_axis_scale'] != 'log') and (plotter_kwargs['y_axis_scale'] != 'log'):
# No log-scale, discard
return None
if (plotter_kwargs['plot_type'] not in {'pie chart', '3D surface'}) and (plotter_kwargs['x_axis_position'] != 'top') and (plotter_kwargs['y_axis_position'] != 'right'):
# No axis moving, discard
return None
return plotter_kwargs
def plotter_kwargs_validate_grid_line(kwargs, hard=False):
if kwargs is None:
return None
plotter_kwargs = dict(kwargs)
if plotter_kwargs['plot_type'] == 'contour plot' and plotter_kwargs['grid_line_color'] in plotter_kwargs['color_map']:
# Grid line color conflicts with cmap, change to gray (for contour, cmap is never None, so no need to check)
plotter_kwargs['grid_line_color'] = 'black'
if plotter_kwargs['grid_line_type'] is None:
plotter_kwargs['grid_line_width'] = None
plotter_kwargs['grid_line_style'] = None
plotter_kwargs['grid_line_color'] = None
return plotter_kwargs
# Sorted slots
# SLOTS = ['fontsize', 'hist_edgecolor', 'hist_edgewidth', 'hist_facecolor', 'hist_nbins', 'hist_rwidth', \
# 'invert_xaxis', 'invert_yaxis', 'label', 'line_color', 'line_marker', \
# 'line_markeredgecolor', 'line_markeredgewidth', 'line_markerfacecolor', 'line_markersize', 'line_markevery', \
# 'line_style', 'line_width', 'plot_type']
### Sampling
# Common kw use the public pool
# Common2 kw use the public pool2
# Special kw use a specialized pool
# (Above) these are used to make pools different for some slots between sample_one from sample_one_hard
# Use None for whatever slots not supported in the plot type or not activated.
# Only data_series_name is included in [type]_label_settings; others, like x_axis_label, y_axis_label, plot_title, are fixed.
LINE_COMMON_KWS = ['line_color', 'line_style', 'line_width', 'marker_type', 'marker_size', \
'marker_edge_width', 'marker_edge_color', 'marker_face_color', 'marker_interval', \
'show_error_bar', 'error_bar_cap_size', 'error_bar_cap_thickness', 'error_bar_color', \
'font_size', 'invert_x_axis', 'invert_y_axis', 'grid_line_type', 'grid_line_style', 'grid_line_width', 'grid_line_color', \
'x_axis_position', 'y_axis_position', 'x_axis_scale', 'y_axis_scale', 'polarize']
LINE_COMMON2_KWS = []
LINE_SPECIAL_KWS = []
HISTOGRAM_COMMON_KWS = ['number_of_bins', 'bar_relative_width', 'bar_edge_width', 'bar_edge_color', 'bar_face_color', \
'font_size', 'invert_x_axis', 'invert_y_axis', 'grid_line_type', 'grid_line_style', 'grid_line_width', 'grid_line_color', \
'x_axis_position', 'y_axis_position']
HISTOGRAM_COMMON2_KWS = []
HISTOGRAM_SPECIAL_KWS = []
SCATTER_COMMON_KWS = ['marker_edge_width', 'marker_edge_color', 'color_map', \
'color_bar_orientation', 'color_bar_length', 'color_bar_thickness', \
'font_size', 'invert_x_axis', 'invert_y_axis', 'grid_line_type', 'grid_line_style', 'grid_line_width', 'grid_line_color', \
'x_axis_position', 'y_axis_position', 'x_axis_scale', 'y_axis_scale', 'polarize']
SCATTER_COMMON2_KWS = ['marker_type', 'marker_size', 'marker_face_color']
SCATTER_SPECIAL_KWS = []
BAR_COMMON_KWS = ['bar_orientation', 'bar_width', 'bar_height', 'bar_edge_width', 'bar_edge_color', 'bar_face_color', \
'show_error_bar', 'error_bar_cap_size', 'error_bar_cap_thickness', 'error_bar_color', \
'font_size', 'invert_x_axis', 'invert_y_axis', 'grid_line_type', 'grid_line_style', 'grid_line_width', 'grid_line_color', \
'x_axis_position', 'y_axis_position', 'x_axis_scale', 'y_axis_scale']
BAR_COMMON2_KWS = []
BAR_SPECIAL_KWS = []
MATRIX_DISPLAY_COMMON_KWS = ['color_map', \
'color_bar_orientation', 'color_bar_length', 'color_bar_thickness', \
'font_size', 'invert_x_axis', 'invert_y_axis', 'x_axis_position', 'y_axis_position']
MATRIX_DISPLAY_COMMON2_KWS = []
MATRIX_DISPLAY_SPECIAL_KWS = []
CONTOUR_COMMON_KWS = ['contour_plot_type', 'number_of_levels', 'color_map', 'line_width', \
'color_bar_orientation', 'color_bar_length', 'color_bar_thickness', \
'font_size', 'invert_x_axis', 'invert_y_axis', 'grid_line_type', 'grid_line_style', 'grid_line_width', 'grid_line_color', \
'x_axis_position', 'y_axis_position', 'x_axis_scale', 'y_axis_scale', 'polarize']
CONTOUR_COMMON2_KWS = ['line_style']
CONTOUR_SPECIAL_KWS = []
STREAMLINE_COMMON_KWS = ['density', 'color_map', 'arrow_size', 'arrow_style', \
'color_bar_orientation', 'color_bar_length', 'color_bar_thickness', \
'font_size', 'invert_x_axis', 'invert_y_axis', 'grid_line_type', 'grid_line_style', 'grid_line_width', 'grid_line_color', \
'x_axis_position', 'y_axis_position']
STREAMLINE_COMMON2_KWS = ['line_color', 'line_width']
STREAMLINE_SPECIAL_KWS = []
SURFACE_3D_COMMON_KWS = ['surface_color', 'color_map', \
'color_bar_orientation', 'color_bar_length', 'color_bar_thickness', \
'font_size', 'invert_x_axis', 'invert_y_axis', 'invert_z_axis']
SURFACE_3D_COMMON2_KWS = []
SURFACE_3D_SPECIAL_KWS = []
PIE_COMMON_KWS = ['explode', 'precision_digits', 'percentage_distance_from_center', 'label_distance_from_center', \
'radius', 'section_edge_width', 'section_edge_color', \
'font_size']
PIE_COMMON2_KWS = []
PIE_SPECIAL_KWS = []
# With data_series_name: line, bar, hist, scatter
NORMAL_COLOR_POOL = ['red', 'orange', 'green', 'blue', 'magenta', 'gray', 'black']
## Always use natural values outside plotter()!
def Line_data_sampler(**kwargs):
if kwargs['polarize']:
data_series_name_pool = ['Position', 'Trajectory']
data_series_name = np.random.choice(data_series_name_pool)
label_setting = {'data_series_name': data_series_name}
x = np.linspace(0, 4*np.pi, 50)
y = np.linspace(0, 4*np.pi, 50) * (10 + np.random.uniform(-1, 1, 50))
data = {'x': x, 'y': y, 'c_type': PLOT_TYPE_S2V[kwargs['plot_type']]}
elif kwargs['x_axis_scale'] == 'log' or kwargs['y_axis_scale'] == 'log':
data_series_name_pool = ['Data Size', 'Power']
data_series_name = np.random.choice(data_series_name_pool)
# label_setting = {'plot_title': 'Line chart\n\n\n', 'x_axis_label': 'X', 'y_axis_label': 'Y', 'data_series_name': data_series_name}
label_setting = {'data_series_name': data_series_name}
x = 10 ** np.linspace(0, 5, 11) if kwargs['x_axis_scale'] == 'log' else np.linspace(0, 5, 11)
if kwargs['y_axis_scale'] == 'log':
y = 10 ** (np.linspace(0, 5, 11) + np.random.uniform(0, 2, 11)).clip(0, 6)
yerr = np.random.uniform(0.5, 0.75, 11) * y
else:
y = np.linspace(0, 5, 11) + np.random.uniform(0, 2, 11)
yerr = np.random.uniform(0.3, 0.6, 11)
data = {'x': x, 'y': y, 'z': yerr, 'c_type': PLOT_TYPE_S2V[kwargs['plot_type']]}
else:
data_series_name_pool = ['Data', 'Score', 'Energy', 'Stock Price', 'User Ratings']
data_series_name = np.random.choice(data_series_name_pool)
# label_setting = {'plot_title': 'Line chart\n\n\n', 'x_axis_label': 'X', 'y_axis_label': 'Y', 'data_series_name': data_series_name}
label_setting = {'data_series_name': data_series_name}
x = np.linspace(0, 10, 11)
y = np.random.uniform(155, 185, 11) + np.random.normal(0, 15, 11)
yerr = np.random.uniform(2, 4, 11)
data = {'x': x, 'y': y, 'z': yerr, 'c_type': PLOT_TYPE_S2V[kwargs['plot_type']]}