forked from GrupoFWP/DAQ
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fwp_plot.py
781 lines (652 loc) · 22.3 KB
/
fwp_plot.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
# -*- coding: utf-8 -*-
"""
The 'fwp_plot' module contains tools for plotting.
Some of its most useful tools are:
animation_2D : function
Makes a series of 2D plots into an animation.
animation_3D : function
Makes a series of 3D plots into an animation.
add_style : function
Gives a specific style to figure.
@author: Vall
"""
from fwp_analysis import single_extreme
from matplotlib import rcParams, ticker, animation
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.cm import winter, summer, spring, autumn, cool, hot
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
#%%
def add_text(text, text_position='up', figure_id=None):
"""Prints some text on a matplotlib.pyplot figure.
Parameters
----------
text : str
Text to be printed.
text_position : tuple, str {'up', 'dowm'}
Position of the text to be printed.
figure_id=None : int
ID of the figure where the text will be printed.
If none is given, the current figure is taken as default.
Returns
-------
nothing
Yields
------
matplotlib.annotation
See Also
--------
plot_style
matplotlib.pyplot.gcf
"""
if figure_id is None:
plt.gcf()
else:
plt.figure(figure_id)
if text_position == 'up':
plt.annotate(text, (0.02,0.9), xycoords="axes fraction")
elif text_position == 'down':
plt.annotate(text, (0.02,0.05), xycoords="axes fraction")
else:
plt.annotate(text, text_position, xycords="axes fraction")
plt.show()
#%%
def add_labels_3D(title=None, xlabel=None, ylabel=None, zlabel=None,
figure_id=None, new_figure=False):
"""Labels a 3D graph's axis.
Parameters
----------
title=None : str, optional
Plot's title.
xlabel=None : str, optional
Plot's X label.
ylabel=None : str, optional
Plot's Y label.
zlabel=None : str, optional
Plot's Z label.
figure_id=None : int, optional
A matplotlib figure's ID. If none is specified, it uses the
current active figure.
new_figure=False : bool, optional
Indicates whether to make a new figure or not when
figure_id=None.
Returns
-------
nothing
Yields
------
axis labels
"""
if figure_id is not None:
fig = plt.figure(figure_id)
elif new_figure:
fig = plt.figure()
else:
fig = plt.gcf()
try:
ax = fig.axes
ax[0]
except IndexError:
ax = [plt.axes()]
if xlabel is not None:
for a in ax:
a.set_xlabel(xlabel)
if ylabel is not None:
for a in ax:
ax.set_ylabel(ylabel)
if zlabel is not None:
for a in ax:
ax.set_zlabel(zlabel)
#%%
def add_style(figure_id=None, new_figure=False, **kwargs):
"""Gives a specific style to figure.
This function...
...increases font size;
...increases linewidth;
...increases markersize;
...gives format to axis ticks if specified;
...stablishes new figure dimensions if specified;
...activates grid.
Parameters
----------
figure_id : int, optional
ID of the figure where the text will be printed.
If none is given, the current figure is taken as default.
new_figure=False : bool, optional
Indicates whether to make a new figure or not when
figure_id=None.
Other Parameters
----------------
xaxisformat : format-like str, optional.
Used to update x axis ticks format; i.e.: '%.2e'
yaxisformat : format-like str, optional.
Used to update y axis ticks format; i.e.: '%.2e'
dimensions: list with length 4, optional.
Used to update plot dimensions: [xmin, xmax, ymin, ymax]. Each
one should be a number expressed as a fraction of current
dimensions.
See Also
--------
matplotlib.pyplot.axis
matplotlib.pyplot.gcf
"""
if figure_id is not None:
fig = plt.figure(figure_id)
elif new_figure:
fig = plt.figure()
else:
fig = plt.gcf()
try:
ax = fig.axes
ax[0]
except IndexError:
ax = [plt.axes()]
kwargs_default = dict(
fontsize=12,
linewidth=3,
markersize=6,
dimensions=[1.15,1.05,1,1],
xaxisformat=None,
yaxisformat=None)
kwargs = {key:kwargs.get(key, value) for key, value in kwargs_default.items()}
# kwargs_list = ['fontsize', 'linewidth', 'markersize', 'dimensions']
# kwargs_val = [14, 3, 6, [1.15,1.05,1,1]]
# for key, val in zip(kwargs_list, kwargs_val):
# try:
# kwargs[key]
# except KeyError:
# kwargs[key] = val
rcParams.update({'font.size': kwargs['fontsize']})
rcParams.update({'lines.linewidth': kwargs['linewidth']})
rcParams.update({'lines.markersize': kwargs['markersize']})
for a in ax:
box = a.get_position()
a.set_position([kwargs['dimensions'][0]*box.x0,
kwargs['dimensions'][1]*box.y0,
kwargs['dimensions'][2]*box.width,
kwargs['dimensions'][3]*box.height])
# kwargs_list = ['xaxisformat', 'yaxisformat']
# for key in kwargs_list:
# try:
# kwargs[key]
# except KeyError:
# kwargs[key] = None
if kwargs['xaxisformat'] is not None:
for a in ax:
a.xaxis.set_major_formatter(ticker.FormatStrFormatter(
kwargs['xaxisformat']))
if kwargs['yaxisformat'] is not None:
for a in ax:
a.yaxis.set_major_formatter(ticker.FormatStrFormatter(
kwargs['yaxisformat']))
for a in ax:
a.grid()
plt.show()
#%% More than one 2D plot
def graphs_2D(X, Y, lcolor='blue'):
"""Plots several lines with a given color scale.
Parameters
----------
X : np.array
Data's X values. Can be a 1D n-array or a 2D (nxN) array, where
each column corresponds to a different data series.
Y : np.array
Data's Y values. Must be a 2D (nxN) array, where each column is
a series of data.
lcolor : str {'blue', 'green', 'red', 'violet', 'mixt'}, optional.
Plot lines' color scale.
Returns
-------
nothing
Yields
------
matplotlib.figure
Raises
------
"Y should be a 2D array" : TypeError
If Y doesn't have more than 1 column.
"X, Y should have the same number of columns" : IndexError
If X is not 1D and X, Y don't have the same number of columns.
"X, Y should have the same number of rows" : IndexError
If X, Y don't have the same number of rows.
"lcolor should be..." : TypeError
If leg isn't either a format string nor a list which length is
Y's number of columns.
"""
try:
Y_rows = len(Y[:,0])
Y_cols = len(Y[0,:])
except:
raise TypeError("Y should be a 2D array")
try:
X_rows = len(X[:,0])
X_cols = len(X[0,:])
except:
X_rows = len(X)
X_cols = 1
if X_cols != 1 and X_cols != Y_cols:
raise IndexError("X, Y should have the same number of columns")
if X_rows != Y_rows:
raise IndexError("X, Y should have the same number of rows")
if lcolor == 'blue':
lcolor = [[0, 0, (Y_cols-i)/Y_cols] for i in range(Y_cols)]
if lcolor == 'green':
lcolor = [[0, (Y_cols-i)/Y_cols, 0] for i in range(Y_cols)]
if lcolor == 'red':
lcolor = [[(Y_cols-i)/Y_cols, 0, 0] for i in range(Y_cols)]
if lcolor == 'violet':
lcolor = [[(Y_cols-i)/Y_cols, 0, (Y_cols-i)/Y_cols]
for i in range(Y_cols)]
if lcolor == 'mixt':
lcolor = [[(Y_cols-i)/Y_cols, 0, (i+1)/Y_cols]
for i in range(Y_cols)]
elif len(lcolor) != Y_cols:
message = "lcolor should be a {}-array like".format(Y_cols)
message = message + "or should be in {}".format(['blue',
'green',
'red',
'violet',
'mixt'])
raise TypeError(message)
plt.figure()
if X_cols == 1:
for i in range(Y_cols):
plt.plot(X, Y[:,i], color=lcolor[i])
else:
for i in range(Y_cols):
plt.plot(X[:,i], Y[:,i], color=lcolor[i])
plt.show()
#%%
def graph_3D(X, Y, Z, color_map='winter'):
"""Makes a 3D plot.
Parameters
----------
X : np.array
Data's X coordinates. Should be a 1D array of size X_len.
Y : np.array
Data's Y coordinates. Should be a 1D array of size Y_len.
Z : np.array
Data on a 2D array of size (Y_len, X_len).
color_map='winter' : str {'winter', 'summer', ...}
Color map specifier. Should be on ['spring', 'autumn', 'cool',
'hot', 'winter', 'summer']. If not, must be imported from
matplotlib.cm
Returns
-------
nothing
Yields
------
matplotlib.figure
Raises
------
"X should be array-like" : TypeError
If len(X) raises error.
"Y should be array-like" : TypeError
If len(X) raises error.
"X, Y should have the same legth" : IndexError
If X, Y don't have the same length.
"Z should be a 2D array" : TypeError
If Z is not a 2D array.
"color_map should be..." : TypeError
If color_map is not an allowed string or matplotlib colormap.
"""
try:
X_len = len(X)
except:
raise TypeError("X should be array-like")
try:
Y_len = len(Y)
except:
raise TypeError("Y should be array-like")
try:
Z[:,0]
except:
raise TypeError("Z should be a 2D array")
if X_len != Y_len:
raise IndexError("X, Y should have the same length")
key = ['winter', 'summer', 'autumn', 'spring', 'cool', 'hot']
if color_map not in key:
if not isinstance(color_map,
LinearSegmentedColormap):
raise TypeError("color_map should be a matplotlib colormap",
" or should be on {}".format(key))
X, Y = np.meshgrid(X, Y)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(X, Y, Z, cmap = color_map) #rstride=1, cstride=1
#ax.contourf(X, Y, Z, cmap=winter)#zdir='z', offset=-2, cmap=winter)
#%%
def graphs_3D(X, Y, Z, Z2, X2=None, Y2=None,
color_map=['winter','summer']):
"""Makes two 3D plots on different subplots.
Parameters
----------
X : np.array
Data's X coordinates. Should be a 1D array of size X_len.
Y : np.array
Data's Y coordinates. Should be a 1D array of size Y_len.
Z : np.array
Data on a 2D array of size (Y_len, X_len).
Z2 : np.array
2nd data on a 2D array.
X2 : np.array, optional
Data's 2nd X coordinates. Should be a 1D array.
Y2 : np.array, optional
Data's 2nd Y coordinates. Should be a 1D array.
color_map=['winter', 'summer'] : list, optional
Color map specifier. Each element should be on ['spring',
'autumn', 'cool', 'hot', 'winter', 'summer']. If not, must be
imported from matplotlib.cm
Returns
-------
nothing
Yields
------
matplotlib.figure
Raises
------
"X should be array-like" : TypeError
If len(X) raises error.
"Y should be array-like" : TypeError
If len(Y) raises error.
"Z should be a 2D array" : TypeError
If Z is not a 2D array.
"X2 should be array-like" : TypeError
If len(X2) raises error.
"Y2 should be array-like" : TypeError
If len(Y2) raises error.
"Z2 should be a 2D array" : TypeError
If Z is not a 2D array.
"color_map should be..." : TypeError
If color_map is not a size 2 list.
"Each color_map should be..." : TypeError
If not all color_map's elements are not an allowed string or
matplotlib colormap.
"""
try:
len(X)
except:
raise TypeError("X should be array-like")
try:
len(Y)
except:
raise TypeError("Y should be array-like")
try:
Z[:,0]
except:
raise TypeError("Z should be a 2D array")
try:
Z2[:,0]
except:
raise TypeError("Z2 should be a 2D array")
if X2 is not None:
try:
len(X2)
except:
raise TypeError("X2 should be array-like")
if Y2 is not None:
try:
len(Y2)
except:
raise TypeError("Y2 should be array-like")
key = ['winter', 'summer', 'autumn', 'spring', 'cool', 'hot']
try:
color_map[1]
except:
raise TypeError("color_map should be a list of length 2")
for cm in color_map:
if cm not in key:
if not isinstance(cm,
LinearSegmentedColormap):
raise TypeError("Each color_map should be a matplotlib",
"colormap or should be on ",
key)
X, Y = np.meshgrid(X, Y)
if X2 is not None:
if Y2 is not None:
X2, Y2 = np.meshgrid(X2, Y2)
else:
X2, Y2 = np.meshgrid(X2, Y)
elif Y2 is not None:
X2, Y2 = np.meshgrid(X, Y2)
else:
X2, Y2 = X, Y
fig = plt.figure(figsize=(13,6),tight_layout=True)
ax = fig.add_subplot(121, projection='3d')
ax.plot_surface(X, Y, Z, cmap = color_map[0])
ax2 = fig.add_subplot(122, projection='3d')
ax2.plot_surface(X2, Y2, Z2, cmap = color_map[1])
fig.show()
#%%
def animation_2D(X, Y, figure_id=None, new_figure=True,
frames_number=30, fps=5,
label_function=lambda i : '{:.0f}'.format(i)):
"""Makes a series of 2D plots into an animation.
Parameters
----------
X : np.array, list
Data's X values. Can be a 1D array of len X_len or a 2D array of
size (n, X_len), where each column corresponds to a different
data series. Can also be a list of 1D arrays.
Y : np.array, list
Data's X values. Should be a 2D array of size (n, Y_len), where
each column corresponds to a different data series. Can also be
a list of 1D arrays.
figure_id=None : int, optional
A matplotlib.pyplot.figure's ID. If specified, it plots on that
figure, which can be already formatted with axis labels, i.e.
new_figure=False : bool, optional
Indicates whether to make a new figure or not when
figure_id=None.
frames_number=30 : int, optional
Animation's total number of frames.
fps=30 : int, optional
Animation's number of frames per second.
label_function : function, optional.
Function that assigns frames' labels. Must take in one int
parameter and return one string.
Returns
-------
animation : matplotlib.animation object
Animation.
Raises
------
"Y should be a 2D array" : TypeError
If Y doesn't have more than 1 column.
"X, Y should have same number of columns" : IndexError
If X is not 1D and X, Y don't have the same number of columns.
"X, Y should have same number of rows" : IndexError
If X, Y don't have the same number of rows.
See Also
--------
matplotlib.animation
fwp_save.saveanimation
"""
# WARNINGS AND VARIABLES' TYPES
if isinstance(Y, np.ndarray):
try:
Y_rows = len(Y[:,0])
Y_cols = len(Y[0,:])
except:
raise TypeError("Y should be a 2D array")
call_Y_series = lambda i : Y[:,i]
frames_total = len(Y[0,:])
if not isinstance(X, np.ndarray):
X = np.array(X).T
try:
X_rows = len(X[:,0])
X_cols = len(X[0,:])
call_X_series = lambda i : X[:,i]
except:
X_rows = len(X)
X_cols = 1
call_X_series = lambda i : X
if X_cols != 1 and X_cols != Y_cols:
raise IndexError("X, Y should have same number of columns")
if X_rows != Y_rows:
raise IndexError("X, Y should have same number of rows")
else:
try:
Y[0][0]
call_Y_series = lambda i : Y[i]
frames_total = len(Y)
except:
raise TypeError("Y should be a 2D list")
X = list(X)
try:
X[0][0]
call_X_series = lambda i : X[i]
except:
call_X_series = lambda i : X
# ACTIVE CODE
if figure_id is not None:
fig = plt.figure(figure_id)
elif new_figure:
fig = plt.figure()
else:
fig = plt.gcf()
try:
ax = fig.axes
ax = ax[0]
except IndexError:
ax = [plt.axes()]
ax.set_xlim((single_extreme(X), single_extreme(X, 'max')))
ax.set_ylim((single_extreme(Y), single_extreme(Y, 'max')))
line, = ax.plot([], [])
label = ax.text(0.02, 0.90, '', transform=ax.transAxes)
index = lambda i : int(frames_total*i/frames_number)
def init():
line.set_data([], [])
label.set_text('')
return line, label
def animate(i):
i = index(i)
line.set_data(call_X_series(i), call_Y_series(i))
label.set_text(label_function(i))
return line, label
anim = animation.FuncAnimation(fig,
animate,
init_func=init,
frames=frames_number,
interval=1000/fps,
blit=True)
return anim;
#%%
def animation_3D(X, Y, Z, figure_id=None, new_figure=True,
color_map='winter', frames_number=30,
label_function=lambda i : '{:.0f}'.format(i)):
"""Makes a series of 3D plots into an animation.
Parameters
----------
X : np.array, list
Data's X values. Can be a 1D n-array of length X_len or a 2D
array of size (T, X_len), where each row corresponds to a
different data series. Can also be a 1D list or a 2D list.
Y : np.array, list
Data's X values. Can be a 1D n-array of length Y_len or a 2D
array of size (T, Y_len), where each row corresponds to a
different data series. Can also be a 1D list or a 2D list.
Z : np.array, list
Data. Should be a 3D array of size (T, Y_len, X_len). Can also
be a 3D list.
figure_id=None : int, optional
A matplotlib.pyplot.figure's ID. If specified, it plots on that
figure, which can be already formatted with axis labels, i.e.
new_figure=False : bool, optional
Indicates whether to make a new figure or not when
figure_id=None.
color_map='winter' : str, optional
Color map specifier. Each element should be on ['spring',
'autumn', 'cool', 'hot', 'winter', 'summer']. If not, must be
imported from matplotlib.cm
frames_number=30 : int, optional
Animation's number of frames.
label_function : function, optional.
Function that assigns frames' labels. Must take in one int
parameter and return one string.
Returns
-------
animation : matplotlib.animation object
Animation.
See Also
--------
matplotlib.animation
fwp_save.saveanimation
"""
if isinstance(Z, np.ndarray):
try:
Z_depth = len(Z[0,0,:])
Z_rows = len(Z[:,0,0])
Z_cols = len(Y[0,:,0])
except:
raise TypeError("Z should be a 3D array")
call_Z_series = lambda i : Z[:,:,i]
if not isinstance(X, np.ndarray):
X = np.array(X).T
try:
X_rows = len(X[:,0])
X_cols = len(X[0,:])
call_X_series = lambda i : X[:,i]
except:
X_rows = len(X)
X_cols = 1
call_X_series = lambda i : X
if not isinstance(Y, np.ndarray):
Y = np.array(Y).T
try:
Y_rows = len(Y[:,0])
Y_cols = len(Y[0,:])
call_Y_series = lambda i : Y[:,i]
except:
Y_rows = len(X)
Y_cols = 1
call_Y_series = lambda i : Y
if Z_rows != X_rows:
raise IndexError("Z, X should have same number of rows")
if Z_cols != Y_rows:
raise IndexError("Z should have as many columns as Y rows")
if Z_depth != X_cols:
raise IndexError("Z should have depth as X has columns")
if Z_depth != Y_cols:
raise IndexError("Z should have depth as Y has columns")
else:
try:
Z[0][0][0]
call_Z_series = lambda i : Z[i]
except:
raise TypeError("Z should be a 3D list")
X = list(X)
try:
X[0][0]
call_X_series = lambda i : X[i]
except:
call_X_series = lambda i : X
Y = list(Y)
try:
Y[0][0]
call_Y_series = lambda i : Y[i]
except:
call_Y_series = lambda i : Y
if figure_id is not None:
fig = plt.figure(figure_id)
elif new_figure:
fig = plt.figure()
else:
fig = plt.gcf()
#ax = axes(xlim=(x0,xf), ylim=(amin(Y),amax(Y)))
ax = fig.gca(projection='3d')
def update(i):
ax.clear()
x = call_X_series(i)
y = call_Y_series(i)
x, y = np.meshgrid(x, y)
ax.plot_surface(x, y, call_Z_series(i), rstride=1, cstride=1,
cmap=color_map, linewidth=0, antialiased=False)
ax.set_zlim(min(min(min(Z))), max(max(max(Z))))
ax.text(0, -2, 0.40, label_function(i), transform=ax.transAxes)
plt.show()
return
anim = animation.FuncAnimation(fig, update, frames=frames_number,
interval=210)
return anim;