/
visuals.py
820 lines (746 loc) · 33.3 KB
/
visuals.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
'''
Code for visualizations of 1+1 D and 2+1 D systems and analytics.
'''
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.ticker as plticker
from matplotlib import animation, rc
from matplotlib.colors import LinearSegmentedColormap
###################################################################################################
def diagram(field, ax=None, size=16, colorbar=False, y_min=0, y_max=None,
x_min=0, x_max=None, ticks=True, xtick_spacing=10, ytick_spacing=10,
tick_size=None, cmap=plt.cm.Greys, edgecolors='none', return_pcolor=False,
**pcolormesh_kwargs):
'''
Plots the given 2D field using matplotlib pcolormesh. Returns a matplotlib
Axes object.
Parameters
----------
field: ndarray (2-D)
2-D array of data to be plotted.
ax: matplotlib Axes object, optional (default=None)
An external Axes object that may be passed in to be further manipulated
after calling this plotting function.
size: int, optional (default=16)
Sets the size of the Figure object.
colorbar: bool, optional (default=False)
Set to True to include a colorbar in the plot, False to not include a colorbar.
y_min: int, optional (default=0)
Lower limit of the y-axis to be plotted.
y_max: int, optional (default=None)
Upper limit of the y-axis to be plotted. If None, is set to the size of the
y-axis for the input field.
x_min: int, optional (default=0)
Lower limit of the x-axis to be plotted.
x_max: int, optional (default=None)
Upper limit of the x-axis to be plotted. If None, is set to the size of the
x-axis for the input field.
ticks: bool, optional (default=None)
Determines whether to display the axis tick marks and corresponding labels or not.
xtick_spacing: int, optional (default=10)
Sets the interval for ticks on along the x-axis.
ytick_spacing: int, optional (default=10)
Sets the interval for ticks along the y-axis.
tick_size: int, optional (default=None)
Sets the size of the tick labels for the axes. If None, defaults to the value
of the 'size' parameter.
cmap: matplotlib colormap, optional (default=plt.cm.Greys)
Colormap used by pcolormesh for plotting the input field.
edgecolors: valid matplotlib color, optional (default='black')
Sets the color of the gird lines outlining the cells of the field.
If set to 'none' does not display any grid lines.
**pcolormesh_kwargs:
Additional keyword arguments for the matplotlib pcolormesh plotting function.
Returns
-------
ax: matplotlib Axes object
Axes object that has either been passed in or created, then updated with
this function.
'''
h,w = np.shape(field)
if y_max is None:
y_max = h
if x_max is None:
x_max = w
H = y_max - y_min
W = x_max - x_min
if ax is None:
fig, ax = plt.subplots(figsize = (size, (H/W)*size))
cropped_field = field[y_min:y_max, x_min:x_max]
im = ax.pcolormesh(cropped_field, cmap=cmap, edgecolors=edgecolors, **pcolormesh_kwargs)
ax.invert_yaxis()
if colorbar:
fig.colorbar(im)
# various code for tick control
if ticks:
ax.xaxis.set_major_locator(plticker.MultipleLocator(xtick_spacing))
ax.yaxis.set_major_locator(plticker.MultipleLocator(ytick_spacing))
if tick_size is None:
tick_size = size
x_labels = [str(int(label)+x_min+xtick_spacing) for label in ax.get_xticks().tolist()]
y_labels = [str(int(label)+y_min+ytick_spacing) for label in ax.get_yticks().tolist()]
x_ticks = [tick+0.5 for tick in ax.get_xticks()]
y_ticks = [tick +0.5 for tick in ax.get_yticks()]
if W % xtick_spacing == 0:
x_trim = 2
else:
x_trim = 1
if H % ytick_spacing == 0:
y_trim = 2
else:
y_trim = 1
ax.set_xticks(x_ticks[1:len(x_ticks)-x_trim], minor=True)
ax.set_yticks(y_ticks[1:len(y_ticks)-y_trim], minor=True)
ax.set_xticklabels(x_labels, fontsize=tick_size, minor=True)
ax.set_yticklabels(y_labels, fontsize=tick_size, minor=True)
ax.xaxis.set_major_formatter(plticker.NullFormatter())
ax.yaxis.set_major_formatter(plticker.NullFormatter())
ax.tick_params(
axis='both',
which='minor',
direction='out',
top=False,
right=False,
pad=8)
ax.tick_params(
axis='both',
which='major',
top=False,
bottom=False,
left=False,
right=False)
else:
ax.tick_params(axis='both',
which='both',
bottom=False,
top=False,
left=False,
right=False,
labelleft=False,
labelbottom=False)
if return_pcolor:
return im
else:
return ax
###################################################################################################
def spacetime_diagram(field, ax=None, size=16, title=None, title_size=None, axes_label_size=None,
axes=True, t_min=0, t_max=None, x_min=0, x_max=None, ttick_spacing=10,
**kwargs):
'''
Plots the given 1+1 D spacetime field using matplotlib pcolormesh.
Expects time on the vertical axis and space on the horizontal. Returns a matplotlib
Axes object.
Parameters
----------
field: ndarray (2-D)
2-D array of data to be plotted.
ax: matplotlib Axes object, optional (default=None)
An external Axes object that may be passed in to be further manipulated
after calling this plotting function.
size: int, optional (default=16)
Sets the size of the Figure object.
title: str, optional (default=None)
Title for the figure.
title_size: int, optional (default=None)
Sets the size for the figure title. If None, defaults to 2 times the 'size'
parameter.
axes_label_size: int, optional (default=None)
Sets the size for the labels on the x and y axes. If None, defaults to
1.8 times the 'size' parameter.
axes: bool, optional (default=True)
Determines whether to display the axes, including labels and ticks.
t_min: int, optional (default=0)
Lower limit of the time (vertical) axis to be plotted.
t_max: int, optional (default=None)
Upper limit of the time (vertical) axis to be plotted. If None, is set to the size of the
time axis for the input field.
x_min: int, optional (default=0)
Lower limit of the x-axis (horizontal) to be plotted.
x_max: int, optional (default=None)
Upper limit of the x-axis (horizontal) to be plotted. If None, is set to the size of the
x-axis for the input field.
ttick_spacing: int, optional (default=10)
Sets the interval for ticks along the time axis.
**kwargs:
Additional keyword arguments for the 'diagram' plotting function that is used
as the backend.
Returns
-------
ax: matplotlib Axes object
Axes object that has either been passed in or created, then updated with
this function.
'''
if ax is None:
h,w = np.shape(field)
if t_max is None:
t_max = h
if x_max is None:
x_max = w
H = t_max - t_min
W = x_max - x_min
fig, ax = plt.subplots(figsize = (size, (H/W)*size))
diagram(field, ax=ax, y_min=t_min, y_max=t_max, x_min=x_min, x_max=x_max,
ytick_spacing=ttick_spacing, **kwargs)
if not axes:
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
if title is not None:
if title_size is None:
title_size = 2*size
ax.set_title(title, {'fontsize':title_size})
if axes_label_size is None:
axes_label_size = 1.8*size
ax.set_ylabel('Time', {'fontsize':axes_label_size})
ax.set_xlabel('Space', {'fontsize':axes_label_size})
return ax
###################################################################################################
def state_overlay_diagram(data_field, state_field, ax=None, size=16, field_colors=plt.cm.Greys,
text_colors=None, text_single_color=None, state_labels=None,
text_size=None, x_min=0, x_max=None, y_min=0, y_max=None, **kwargs):
'''
Plots the given 2D data field with text of values from the state field overlayed
on top, using matplotlib pcolormesh. Returns a matplotlib Axes object.
Parameters
----------
data_field: array-like
2-D array of data to be plotted.
state_field: array-like
2-D array of state field values to be overlayed as text on top of the
data field plot. Must be same shape as data_field.
ax: matplotlib Axes object, optional (default=None)
An external Axes object that may be passed in to be further manipulated
after calling this plotting function.
size: int, optional (default=16)
Sets the size of the Figure object.
field_colors: matplotlib colormap, optional (default=plt.cm.Greys)
Colormap for the data_field values
text_colors: matplotlib colormap, optional (default=None)
Colormap for the overlaid state labels. If left as None, will color all
labels the same according to text_single_color (default=blue).
text_single_color: matplotlib color, optional (default=None)
If text_colors left as None, all labels will be colored uniformly as the
color specified here. If left as None, default is a shade of blue given
by plt.cm.rainbow(1/5). text_colors takes precedence, so that if both
text_colors and text_single_color are not None, colors will be assigned
according to the text_colors colormap.
state_labels: dict, optional (default=None)
Dictionary that maps the numerical state values in state_field to custom
labels given in the dictionary.
text_size: int, optional (default=None)
Size of the overlayed label text. If left as None, will be given as the
plot size (size parameter).
y_min: int, optional (default=0)
Lower limit of the y-axis to be plotted.
y_max: int, optional (default=None)
Upper limit of the y-axis to be plotted. If None, is set to the size of the
y-axis for the input field.
x_min: int, optional (default=0)
Lower limit of the x-axis to be plotted.
x_max: int, optional (default=None)
Upper limit of the x-axis to be plotted. If None, is set to the size of the
x-axis for the input field.
**kwargs:
Additional keyword arguments for the 'diagram' plotting function that is used
as the backend.
Returns
-------
ax: matplotlib Axes object
Axes object that has either been passed in or created, then updated with
this function.
'''
if data_field.shape != state_field.shape:
raise ValueError("data_field and state_field must be the same shape.")
h,w = np.shape(data_field)
if y_max is None:
y_max = h
if x_max is None:
x_max = w
H = y_max - y_min
W = x_max - x_min
y_ind = np.arange(y_min, y_max, 1)
x_ind = np.arange(x_min, x_max, 1)
x, y = np.meshgrid(x_ind, y_ind)
if ax is None:
fig, ax = plt.subplots(figsize = (size, (H/W)*size))
#diagram(data_field, ax=ax, cmap=field_colors, **kwargs)
diagram(data_field, ax=ax, cmap=field_colors, y_min=y_min, y_max=y_max,
x_min=x_min, x_max=x_max, **kwargs)
#add state label text
states = np.unique(state_field)
max_state = np.max(states)
if state_labels is None:
state_labels = dict(zip(states,states))
if text_colors is None:
if text_single_color is None:
text_single_color = plt.cm.rainbow(1/5)
text_colors = {state:text_single_color for state in states}
if text_size is None:
text_size = size
for x_val, y_val in zip(x.flatten(), y.flatten()):
c = state_field[y_val][x_val]
if c not in state_labels:
raise ValueError("Need a label for state {} in state_labels dict".format(c))
if type(text_colors) is dict:
if c not in text_colors:
raise ValueError("Need a color for state {} in text_colors dict".format(c))
else:
text_color = text_colors[c]
else:
text_color = text_colors(c/max_state)
ax.text(x_val+0.5-x_min, y_val+0.5-y_min, state_labels[c], va='center', ha='center',
color=text_color, size=text_size, weight='black')
return ax
###################################################################################################
def custom_colors(color_map):
'''
Creates custom color map from given dictionary.
Parameters
----------
color_map: dict
Keys are field array values and dict values are the corresponding colors
to be assigned to the field array values. Keys must be integers. Vals must
be valid matplotlib color scheme.
Returns
-------
color_map: LinearSegmentedColormap
Returns matplotlib LinearSegmentedColormap.from_list using the given
color_map dictionary.
'''
keys = np.array(color_map.keys())
min_key = np.min(keys)
normalization = np.max(keys - min_key)
normalized_keys = (keys-min_key)/normalization
normed_map = dict(zip(normalized_keys, color_map.values()))
colors = LinearSegmentedColormap.from_list('mycmap', sorted(normed_map.items()))
return colors
def old_custom_colors(values, colors):
'''
Creates custom color map from given list of values to the corresponding colors.
That is, values[i] is mapped to color colors[i]/
Parameters
----------
values: list
List of the numerical values to be given colors.
colors: list
List of colors to be assigned to the given values.
Returns
-------
color_map: LinearSegmentedColormap
Returns matplotlib LinearSegmentedColormap.from_list using the input values
and colors
'''
min_val = np.min(values)
normalization = np.max(values - min_val)
normalized_vals = (values-min_val)/normalization
color_map = LinearSegmentedColormap.from_list('mycmap', sorted(zip(normalized_vals, colors)))
return color_map
###################################################################################################
def state_overlay_animate(data_fields, state_fields, ax=None, size=16, field_colors=plt.cm.Greys,
text_colors=None, text_single_color=None, state_labels=None,
text_size=None, edgecolors='black', axes_label_size=None,
y_min=0, y_max=None, x_min=0, x_max=None, colorbar=False,
title=None, title_size=None, axes=True, ticks=True,
ytick_spacing=10, xtick_spacing=10, tick_size=None, **anim_kwargs):
'''
Animates matplotlib pcolormesh plot of the given 2-D data fields with text of values
from state fields overlayed on top. Returns a matplotlib animation object.
Must be same number of state and data fields, and all fields (both data and
state) must be same shape.
Parameters
----------
data_field: array-like
2-D array of data to be plotted.
state_field: array-like
2-D array of state field values to be overlayed as text on top of the
data field plot. Must be same shape as data_fields.
size: int, optional (default=16)
Sets the size of the Figure object.
field_colors: matplotlib colormap, optional (default=plt.cm.Greys)
Colormap for the data_field values
text_colors: matplotlib colormap, optional (default=None)
Colormap for the overlaid state labels. If left as None, will color all
labels the same according to text_single_color (default=blue).
text_single_color: matplotlib color, optional (default=None)
If text_colors left as None, all labels will be colored uniformly as the
color specified here. If left as None, default is a shade of blue given
by plt.cm.rainbow(1/5). text_colors takes precedence, so that if both
text_colors and text_single_color are not None, colors will be assigned
according to the text_colors colormap.
state_labels: dict, optional (default=None)
Dictionary that maps the numerical state values in state_field to custom
labels given in the dictionary.
text_size: int, optional (default=None)
Size of the overlayed label text. If left as None, will be given as the
plot size (size parameter).
edgecolors: matplotlib color, optional (default='black')
Grid line colors for the diagram. Set to 'none' for no grid lines.
axes_label_size: int, optional (default=None)
Size of the axes labels "Time" and "Space". If left as None will be given
as 1.8*size.
y_min: int, optional (default=0)
Lower limit of the y-axis to be plotted.
y_max: int, optional (default=None)
Upper limit of the y-axis to be plotted. If None, is set to the size of the
y-axis for the input field.
x_min: int, optional (default=0)
Lower limit of the x-axis to be plotted.
x_max: int, optional (default=None)
Upper limit of the x-axis to be plotted. If None, is set to the size of the
x-axis for the input field.
colorbar: Bool, optional (default=False)
Option to display the colorbar.
title: str, optional (default=None)
Title for the animated Figure.
title_size: int, optional (default=None)
Sets the size for the figure title. If None, defaults to 2 times the 'size'
parameter.
axes: bool, optional (default=True)
Determines whether to show the axes, with ticks and labels or not.
ticks: bool, optional (default=True)
Determines whether to show the axes ticks or not. Does not affect axes labels.
xtick_spacing: int, optional (default=10)
Sets the interval for ticks on along the x-axis.
ytick_spacing: int, optional (default=10)
Sets the interval for ticks along the y-axis.
tick_size: int, optional (default=None)
Sets the size of the tick labels for the axes. If None, defaults to the value
of the 'size' parameter.
**anim_kwargs:
Additional keyword arguments for the matplotlib animation.FuncAnimation()
function.
Returns
-------
ax: matplotlib Axes object
Axes object that has either been passed in or created, then updated with
this function.
'''
if np.shape(data_fields) != np.shape(state_fields):
raise ValueError("data_fields and state_fields must be same shape.")
t,h,w = np.shape(data_fields)
if y_max is None:
y_max = h
if x_max is None:
x_max = w
H = y_max - y_min
W = x_max - x_min
if ax is None:
fig, ax = plt.subplots(figsize = (size, (H/W)*size))
cropped_data = data_fields[:, y_min:y_max, x_min:x_max]
cropped_states = state_fields[:, y_min:y_max, x_min:x_max]
im = ax.pcolormesh(cropped_data[0], cmap=cmap, edgecolors=edgecolors)
ax.invert_yaxis()
if not axes:
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
if colorbar:
ax.colorbar()
if title is not None:
if title_size is None:
title_size = 2*size
ax.set_title(title, {'fontsize':title_size})
if axes_label_size is None:
axes_label_size = 1.8*size
ax.set_ylabel('Y', {'fontsize':axes_label_size})
ax.set_xlabel('X', {'fontsize':axes_label_size})
# various code for tick control
if ticks:
ax.xaxis.set_major_locator(plticker.MultipleLocator(xtick_spacing))
ax.yaxis.set_major_locator(plticker.MultipleLocator(ytick_spacing))
if tick_size is None:
tick_size = size
x_labels = [str(int(label)+x_min+xtick_spacing) for label in ax.get_xticks().tolist()]
y_labels = [str(int(label)+y_min+ytick_spacing) for label in ax.get_yticks().tolist()]
x_ticks = [tick+0.5 for tick in ax.get_xticks()]
y_ticks = [tick +0.5 for tick in ax.get_yticks()]
if W % xtick_spacing == 0:
x_trim = 2
else:
x_trim = 1
if H % ytick_spacing == 0:
y_trim = 2
else:
y_trim = 1
ax.set_xticks(x_ticks[1:len(x_ticks)-x_trim], minor=True)
ax.set_yticks(y_ticks[1:len(y_ticks)-y_trim], minor=True)
ax.set_xticklabels(x_labels, fontsize=tick_size, minor=True)
ax.set_yticklabels(y_labels, fontsize=tick_size, minor=True)
ax.xaxis.set_major_formatter(plticker.NullFormatter())
ax.yaxis.set_major_formatter(plticker.NullFormatter())
ax.tick_params(
axis='both',
which='minor',
direction='out',
top=False,
right=False,
pad=8)
ax.tick_params(
axis='both',
which='major',
top=False,
bottom=False,
left=False,
right=False)
else:
ax.tick_params(axis='both',
which='both',
bottom=False,
top=False,
left=False,
right=False,
labelleft=False,
labelbottom=False)
# set "global" text items to be used in all overlays
states = np.unique(state_fields)
max_state = np.max(states)
if state_labels is None:
state_labels = dict(zip(states,states))
if text_colors is None:
if text_single_color is None:
text_single_color = plt.cm.rainbow(1/5)
text_colors = {state:text_single_color for state in states}
if text_size is None:
text_size = size
state_field = cropped_states[0]
# each text instance needs to be assigned a viariable so it can be updated
# during the animation
labels = []
for x_val, y_val in zip(x.flatten(), y.flatten()):
c = state_field[y_val][x_val]
if c not in state_labels:
raise ValueError("Need a label for state {} in state_labels dict".format(c))
if type(text_colors) is dict:
if c not in text_colors:
raise ValueError("Need a color for state {} in text_colors dict".format(c))
else:
text_color = text_colors[c]
else:
text_color = text_colors(c/max_state)
labels.append(ax.text(x_val+0.5, y_val+0.5, state_labels[c], va='center', ha='center',
color=text_color, size=text_size, weight='black')
)
plt.close() # prevents initial figure from being displayed in jupyter notebook
# update function needed for animation
def animate(i):
im.set_array(cropped_data[i].flatten())
state_field = cropped_states[i]
for x_val, y_val, label in zip(x.flatten(), y.flatten(), labels):
c = state_field[y_val][x_val]
if c not in state_labels:
raise ValueError("Need a label for state {} in state_labels dict".format(c))
text_color = text_colors(c/max_state)
label.set_text(state_labels[c])
label.set_color(text_colors(c/max_state))
frames = t
# put it all together and call the matplotlib animation function
anim = animation.FuncAnimation(fig, animate, frames=frames, **anim_kwargs)
return anim
###################################################################################################
# 2+1 D STUFF
###################################################################################################
def config_diagram(field, ax=None, size=16, title=None, title_size=None, axes_label_size=None,
axes=True, y_min=0, y_max=None, x_min=0, x_max=None, **kwargs):
'''
Plots the given 2 D spatial field using matplotlib pcolormesh.
Returns a matplotlib Axes object.
Parameters
----------
field: ndarray (2-D)
2-D array of data to be plotted.
ax: matplotlib Axes object, optional (default=None)
An external Axes object that may be passed in to be further manipulated
after calling this plotting function.
size: int, optional (default=16)
Sets the size of the Figure object.
title: str, optional (default=None)
Title for the figure.
title_size: int, optional (default=None)
Sets the size for the figure title. If None, defaults to 2 times the 'size'
parameter.
axes_label_size: int, optional (default=None)
Sets the size for the labels on the x and y axes. If None, defaults to
1.8 times the 'size' parameter.
axes: bool, optional (default=True)
Determines whether to display the axes, including labels and ticks.
y_min: int, optional (default=0)
Lower limit of the y-axis to be plotted.
y_max: int, optional (default=None)
Upper limit of the y-axis to be plotted. If None, is set to the size of the
time axis for the input field.
x_min: int, optional (default=0)
Lower limit of the x-axis to be plotted.
x_max: int, optional (default=None)
Upper limit of the x-axis to be plotted. If None, is set to the size of the
x-axis for the input field.
**kwargs:
Additional keyword arguments for the 'diagram' plotting function that is used
as the backend.
Returns
-------
ax: matplotlib Axes object
Axes object that has either been passed in or created, then updated with
this function.
'''
h,w = np.shape(field)
if y_max is None:
y_max = h
if x_max is None:
x_max = w
H = y_max - y_min
W = x_max - x_min
if ax is None:
fig, ax = plt.subplots(figsize = (size, (H/W)*size))
diagram(field, ax=ax, y_min=y_min, y_max=y_max, x_min=x_min, x_max=x_max,
**kwargs)
if not axes:
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
if title is not None:
if title_size is None:
title_size = 2*size
ax.set_title(title, {'fontsize':title_size})
if axes_label_size is None:
axes_label_size = 1.8*size
ax.set_ylabel('Y', {'fontsize':axes_label_size})
ax.set_xlabel('X', {'fontsize':axes_label_size})
return ax
###################################################################################################
def spacetime_animate(data_fields, ax=None, size=20, colorbar=False, axes_label_size=None,
y_min=0, y_max=None, x_min=0, x_max=None, title=None,
title_size=None, axes=True, ticks=True, xtick_spacing=10,
ytick_spacing=10, tick_size=None, cmap=plt.cm.rainbow,
edgecolors='none', anim_kwargs={}, **pcolor_kwargs):
'''
Plots the given 2D field using matplotlib pcolormesh. Returns a matplotlib
Axes object.
Parameters
----------
field: ndarray (2-D)
2-D array of data to be plotted.
ax: matplotlib Axes object, optional (default=None)
An external Axes object that may be passed in to be further manipulated
after calling this plotting function.
size: int, optional (default=16)
Sets the size of the Figure object.
colorbar: bool, optional (default=False)
Set to True to include a colorbar in the plot, False to not include a colorbar.
y_min: int, optional (default=0)
Lower limit of the y-axis to be plotted.
y_max: int, optional (default=None)
Upper limit of the y-axis to be plotted. If None, is set to the size of the
y-axis for the input field.
x_min: int, optional (default=0)
Lower limit of the x-axis to be plotted.
x_max: int, optional (default=None)
Upper limit of the x-axis to be plotted. If None, is set to the size of the
x-axis for the input field.
title: str, optional (default=None)
Title for the figure.
title_size: int, optional (default=None)
Sets the size for the figure title. If None, defaults to 2 times the 'size'
parameter.
axes_label_size: int, optional (default=None)
Sets the size for the labels on the x and y axes. If None, defaults to
1.8 times the 'size' parameter.
axes: bool, optional (default=True)
Determines whether to display the axes, including labels and ticks.
ticks: bool, optional (default=None)
Determines whether to display the axis tick marks and corresponding labels or not.
xtick_spacing: int, optional (default=10)
Sets the interval for ticks on along the x-axis.
ytick_spacing: int, optional (default=10)
Sets the interval for ticks along the y-axis.
tick_size: int, optional (default=None)
Sets the size of the tick labels for the axes. If None, defaults to the value
of the 'size' parameter.
cmap: matplotlib colormap, optional (default=plt.cm.Greys)
Colormap used by pcolormesh for plotting the input field.
edgecolors: valid matplotlib color, optional (default='black')
Sets the color of the gird lines outlining the cells of the field.
If set to 'none' does not display any grid lines.
**anim_kwargs:
Additional keyword arguments for the matplotlib animation.FuncAnimation()
function.
Returns
-------
ax: matplotlib Axes object
Axes object that has either been passed in or created, then updated with
this function.
'''
t,h,w = np.shape(data_fields)
if y_max is None:
y_max = h
if x_max is None:
x_max = w
H = y_max - y_min
W = x_max - x_min
if ax is None:
fig, ax = plt.subplots(figsize = (size, (H/W)*size))
cropped_fields = data_fields[:, y_min:y_max, x_min:x_max]
im = ax.pcolormesh(cropped_fields[0], cmap=cmap, edgecolors=edgecolors, **pcolor_kwargs)
ax.invert_yaxis()
if not axes:
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
if colorbar:
ax.colorbar()
if title is not None:
if title_size is None:
title_size = 2*size
ax.set_title(title, {'fontsize':title_size})
if axes_label_size is None:
axes_label_size = 1.8*size
ax.set_ylabel('Y', {'fontsize':axes_label_size})
ax.set_xlabel('X', {'fontsize':axes_label_size})
# various code for tick control
if ticks:
ax.xaxis.set_major_locator(plticker.MultipleLocator(xtick_spacing))
ax.yaxis.set_major_locator(plticker.MultipleLocator(ytick_spacing))
if tick_size is None:
tick_size = size
x_labels = [str(int(label)+x_min+xtick_spacing) for label in ax.get_xticks().tolist()]
y_labels = [str(int(label)+y_min+ytick_spacing) for label in ax.get_yticks().tolist()]
x_ticks = [tick+0.5 for tick in ax.get_xticks()]
y_ticks = [tick +0.5 for tick in ax.get_yticks()]
if W % xtick_spacing == 0:
x_trim = 2
else:
x_trim = 1
if H % ytick_spacing == 0:
y_trim = 2
else:
y_trim = 1
ax.set_xticks(x_ticks[1:len(x_ticks)-x_trim], minor=True)
ax.set_yticks(y_ticks[1:len(y_ticks)-y_trim], minor=True)
ax.set_xticklabels(x_labels, fontsize=tick_size, minor=True)
ax.set_yticklabels(y_labels, fontsize=tick_size, minor=True)
ax.xaxis.set_major_formatter(plticker.NullFormatter())
ax.yaxis.set_major_formatter(plticker.NullFormatter())
ax.tick_params(
axis='both',
which='minor',
direction='out',
top=False,
right=False,
pad=8)
ax.tick_params(
axis='both',
which='major',
top=False,
bottom=False,
left=False,
right=False)
else:
ax.tick_params(axis='both',
which='both',
bottom=False,
top=False,
left=False,
right=False,
labelleft=False,
labelbottom=False)
plt.close() # prevents initial figure from being displayed in jupyter notebook
def animate(i):
im.set_array(cropped_fields[i].flatten())
frames = t
anim = animation.FuncAnimation(fig, animate, frames=frames, **anim_kwargs)
return anim