-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_profile_hovmoller.py
More file actions
743 lines (513 loc) · 21.6 KB
/
plot_profile_hovmoller.py
File metadata and controls
743 lines (513 loc) · 21.6 KB
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
# -*- coding: utf-8 -*-
# author (unless omitted): Ronaldo Mitsuo Sato
# email: ronaldo.sato@gmail.com
# created: 30/09/2025
# python version: 3
'''Programa para plotar perfil de corrente interanual médio e
diagrama Hovmöller.
'''
import sys
import re
import xarray as xr
import numpy as np
import pandas as pd
from scipy.stats import circmean
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.cm import ScalarMappable
# import matplotlib.colors as mcolors
from matplotlib.colors import ListedColormap, Normalize
# from matplotlib.colors import LinearSegmentedColormap
import json
def uv2spddir(u, v):
"""
Cálculo da velocidade e direção, respectivamente 'spd' e 'drc',
a partir das componentes de velocidade (u e v).
Parâmetros
----------
u: array_like
Componente zonal de velocidade
v: array_like
Componente meriodional de velocidade
Retorno
-------
spd: array_like
Intensidade
drc: array_like
Direção
Exemplo (arrumar isto aqui)
-------
>>> spd, drc = uv2spddir(u, v)
>>> spd
>>> dir
"""
spd = np.sqrt(u**2 + v**2)
drc = np.rad2deg(np.arctan2(u, v)) % 360
return spd, drc
def hovmoller_test():
condition = (df['dir'] < 225) & (df['dir'] > 45)
df.loc[condition, 'spd'] = (-1) * df.loc[condition, 'spd']
# xtime = df['spd'].unstack(level='depth').index.to_numpy(dtype=float)
# ydepth = df['spd'].unstack(level='time').index.to_numpy()
# xtime = xtime - xtime[0]
# xx, yy = np.meshgrid(xtime, ydepth)
fig, ax = plt.subplots(figsize=(16, 12))
# vmin = np.round(-(df['spd'].max()-(1*df['spd'].std())), decimals=1)
vmin = df['spd'].min()
vmax = np.round(df['spd'].max()-(1*df['spd'].std()), decimals=1)
levels = np.arange(0., df['spd'].max(), .5)
ticks = (-levels[:0:-1]).tolist() + levels.tolist()
cmap = plt.get_cmap('jet', 256)
cmap = ListedColormap(cmap(np.linspace(.15, .95, 256)))
norm = Normalize(vmin=vmin, vmax=vmax, clip=False)
contourf = ax.contourf( #pcolor( #imshow(
df['spd'].unstack(level='time').values,
vmin=vmin,
vmax=vmax,
levels=100,
cmap=cmap,
norm=norm,
extend='both')
if False:
csplus = ax.contour(
df['spd'].unstack(level='time').values,
levels=levels, colors='k', linewidths=.2, zorder=3)
ax.clabel(
csplus, levels,
fmt='', inline=True, inline_spacing=15, fontsize=10)
csminus = ax.contour(
df['spd'].unstack(level='time').values,
levels=-levels[::-1], colors='w', linewidths=.2, zorder=3)
ax.clabel(
csminus, -levels[::-1],
fmt='', inline=True, inline_spacing=15, fontsize=10)
ax.invert_yaxis()
# cbar = fig.colorbar(
# contourf, fraction=.2, shrink=.75, extend='both')
# ticks=(-levels[:0:-1]).tolist() + levels.tolist())
cbar = fig.colorbar(
ScalarMappable(norm=contourf.norm, cmap=contourf.cmap),
ax=ax, ticks=ticks, fraction=.015, shrink=.75, extend='both')
fig.savefig(f'{path2save}/teste_hovmoller.png', format='png')
return None
def plot_hovmoller(variable, clabel=False):
x = df[variable].unstack(level='depth') \
.index.get_level_values('time').astype(int)
y = df[variable].unstack(level='time') \
.index.get_level_values('depth')
xx, yy = np.meshgrid(x, y)
# df['timestamp'] = df.index.get_level_values('time').astype(int)
# _df = df.reset_index().set_index(['timestamp', 'depth'])
fig, ax = plt.subplots(figsize=(18, 12))
if variable == 'spd':
# vmin = np.round(-(df['spd'].max()-(1*df['spd'].std())), decimals=1)
vmin = df['spd'].min()
vmax = np.round(df['spd'].max()-(1*df['spd'].std()), decimals=1)
levels = np.arange(0., df['spd'].max(), .5)
ticks = (-levels[:0:-1]).tolist() + levels.tolist()
cmap = plt.get_cmap('jet', 256)
cmap = ListedColormap(cmap(np.linspace(.15, .95, 256)))
norm = Normalize(vmin=vmin, vmax=vmax, clip=False)
contourf = ax.contourf( #pcolor( #imshow(
# x, y,
xx, yy,
df[variable].unstack(level='time').values,
vmin=vmin,
vmax=vmax,
levels=100,
cmap=cmap,
norm=norm,
extend='both')
cbar_title = 'Intensidade de Corrente [m/s]'
elif variable == 'dir':
vmin, vmax = 0., 360.
levels = np.arange(0., vmax+1, 45.)
ticks = levels.tolist()
if False:
cmap = plt.get_cmap('RdYlBu_r', 128) # Spectral_r
_colors = np.vstack((cmap(np.linspace(.0, .5, 128)),
cmap(np.linspace(.0, .5, 128))[::-1]))
_colors = np.roll(_colors, int(cmap.N*(-.25)), axis=0) #.75
cmap = ListedColormap(_colors, name='RdYlBu_cutted')
if True:
cmap = plt.get_cmap('RdBu_r', 128)
_colors = np.vstack((cmap(np.linspace(.1, .5, 128)),
cmap(np.linspace(.1, .5, 128))[::-1]))
_colors = np.roll(_colors, int(cmap.N*(-.25)), axis=0)
cmap = ListedColormap(_colors, name='RdBu_cutted')
# cmap = plt.get_cmap('bwr', 128)
# _colors = np.vstack((cmap(np.linspace(.1, .5, 128)),
# cmap(np.linspace(.1, .5, 128))[::-1]))
# _colors = np.roll(_colors, int(cmap.N*(-.25)), axis=0)
# cmap = ListedColormap(_colors, name='bwr_cutted')
# cmap = plt.get_cmap('jet', 256)
# _colors = cmap(np.linspace(.15, .95, 256))
# _colors = np.roll(_colors, int(cmap.N*(-.25)), axis=0)
# cmap = ListedColormap(_colors, name='jet_rolled')
norm = Normalize(vmin=vmin, vmax=vmax, clip=False)
contourf = ax.contourf( #pcolor( #imshow(
# x, y,
xx, yy,
# _df[variable].unstack(level='timestamp').values,
# df[variable].index.get_level_values('time'),
# df[variable].index.get_level_values('depth'),
df[variable].unstack(level='time').values,
vmin=vmin,
vmax=vmax,
levels=100,
cmap=cmap,
norm=norm,
extend='both')
cbar_title = 'Direção de Corrente [°]'
if clabel:
cs_plus = ax.contour(
df[variable].unstack(level='time').values,
levels=levels, colors='k', linewidths=.2, zorder=3)
ax.clabel(
cs_plus, levels,
fmt='', inline=True, inline_spacing=15, fontsize=10)
cs_minus = ax.contour(
df[variable].unstack(level='time').values,
levels=-levels[::-1], colors='w', linewidths=.2, zorder=3)
ax.clabel(
cs_minus, -levels[::-1],
fmt='', inline=True, inline_spacing=15, fontsize=10)
ax.invert_yaxis()
# ax.set_ylim(ax.get_ylim()[::-1])
# ax.yaxis.set_inverted(True)
ax.set_ylabel('Profundidade [m]', fontsize=22)
ax.tick_params(axis='y', which='major', labelsize=16)
try:
ax.set_title(
f'{dataset}\nPonto de grade próximo à {point_name.capitalize()}\n'
'Diagrama Hovmöller',
fontsize=22, pad=18)
except NameError:
ax.set_title(
f'{dataset}\nPonto de grade próximo à'
f' lat={round(ds["lat"].item(), ndigits=4)},'
f' lon={round(ds["lon"].item(), ndigits=4)}\n'
'Diagrama Hovmöller',
fontsize=22, pad=18)
cbar = fig.colorbar(
ScalarMappable(norm=contourf.norm, cmap=contourf.cmap),
ax=ax, ticks=ticks, fraction=.015, shrink=.75, extend='both', pad=.02)
cbar.ax.tick_params(labelsize=18, pad=10)
cbar.set_label(cbar_title, rotation=270, fontsize=22, labelpad=30)
month_labels = df[variable].index.get_level_values('time') \
.unique().strftime('%m/%Y').unique().to_list()
major_labels = [
label
for label in month_labels
if pd.to_datetime(label, format='%m/%Y').month == 1]
major_ticks = pd.to_numeric(
pd.to_datetime(major_labels, format='%m/%Y')).tolist()
_minor_labels = [
label
for label in month_labels
if pd.to_datetime(label, format='%m/%Y').month in [3, 6, 9, 12]]
minor_ticks = pd.to_numeric(
pd.to_datetime(_minor_labels, format='%m/%Y')).tolist()
minor_labels = [
dt.strftime('%m')
for dt in pd.to_datetime(month_labels, format='%m/%Y')
if dt.month in [3, 6, 9, 12]]
# _middle_labels = [
# label
# for label in month_labels
# if pd.to_datetime(label, format='%m/%Y').month in [3, 6, 9, 12]]
# major_ticks += pd.to_numeric(
# pd.to_datetime(_middle_labels, format='%m/%Y')).tolist()
# major_labels += [
# pd.to_datetime(label, format='%m/%Y').strftime('%m')
# for label in _middle_labels]
# _ = ax.set_xticks(
# major_ticks+minor_ticks, major_labels+minor_labels,
# rotation=60, fontsize=10, ha='right')
ax.set_xticks(
major_ticks, major_labels, minor=False,
rotation=90, fontsize=16, ha='center')
ax.set_xticks(
minor_ticks, minor_labels, minor=True,
rotation=90, fontsize=14, ha='center')
# for ticklabel in ax.xaxis.get_ticklabels():
# if re.match('\d+/\d+', ticklabel.get_text()):
# month = pd.to_datetime(ticklabel.get_text(), format='%m/%Y').month
# if (month % d == 0 for d in [3, 9, 11]):
# ticklabel.set_fontsize(15)
# Controlar dessa forma está dando OverflowError
# ax.xaxis.set_major_locator(mdates.MonthLocator(interval=3))
# ax.xaxis.set_minor_locator(mdates.MonthLocator(interval=1))
# ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%Y'))
_ = ax.tick_params(
axis='x', which='major', direction='out', bottom=True, top=True,
labelbottom=True, labeltop=False, width=2, length=8, pad=20)
_ = ax.tick_params(
axis='x', which='minor', direction='out', bottom=True, top=True,
labelbottom=True, labeltop=False, width=1, length=5)
# ax.grid(which='major', color='grey', linestyle='--', linewidth=0.8)
fig.subplots_adjust(left=.08, right=.92, top=.89, bottom=.13)
fig.savefig(
f'{path2save}/hovmoller_{variable}_'
f'{df.index.get_level_values("time")[0].strftime(r"%b%Y")}'
f'-{df.index.get_level_values("time")[-1].strftime(r"%b%Y")}.png',
format='png')
return fig, ax
def hovmoller_subplots(variable, depths=[], clabel=False):
fig, ax = plt.subplots(
figsize=(18, 12), nrows=len(depths), sharex=True)
_depth = np.array(depths).flatten()
_depth = _depth[0], _depth[-1]
contourf = []
for i, depth in enumerate(depths):
x = df.loc[(slice(None), slice(*depth)), variable] \
.unstack(level='depth') \
.index.get_level_values('time').astype(int)
y = df.loc[(slice(None), slice(*depth)), variable] \
.unstack(level='time') \
.index.get_level_values('depth')
xx, yy = np.meshgrid(x, y)
if variable == 'spd':
vmin = np.round(
df.loc[(slice(None), slice(*_depth)), variable].min(),
decimals=1)
vmax = np.round(
df.loc[(slice(None), slice(*_depth)), variable].max()
-(1*df.loc[(slice(None), slice(*_depth)), variable].std()),
decimals=1)
levels = np.arange(0., df[variable].max(), .5)
ticks = (-levels[:0:-1]).tolist() + levels.tolist()
cmap = plt.get_cmap('jet', 256)
cmap = ListedColormap(cmap(np.linspace(.15, .95, 256)))
norm = Normalize(vmin=vmin, vmax=vmax, clip=False)
try:
contourf += [
ax[i].contourf(
xx, yy,
df.loc[(slice(None), slice(*depth)), variable] \
.unstack(level='time').values,
vmin=vmin,
vmax=vmax,
levels=100,
cmap=cmap,
norm=norm,
extend='both')]
except TypeError:
contourf += [
ax.contourf(
xx, yy,
df.loc[(slice(None), slice(*depth)), variable] \
.unstack(level='time').values,
vmin=vmin,
vmax=vmax,
levels=100,
cmap=cmap,
norm=norm,
extend='both')]
cbar_title = 'Intensidade de Corrente [m/s]'
elif variable == 'dir':
vmin, vmax = 0., 360.
levels = np.arange(0., vmax+1, 45.)
ticks = levels.tolist()
cmap = plt.get_cmap('RdBu_r', 128)
_colors = np.vstack((cmap(np.linspace(.1, .5, 128)),
cmap(np.linspace(.1, .5, 128))[::-1]))
_colors = np.roll(_colors, int(cmap.N*(-.25)), axis=0)
cmap = ListedColormap(_colors, name='RdBu_cutted')
norm = Normalize(vmin=vmin, vmax=vmax, clip=False)
try:
contourf += [
ax[i].contourf(
xx, yy,
df.loc[(slice(None), slice(*depth)), variable] \
.unstack(level='time').values,
vmin=vmin,
vmax=vmax,
levels=100,
cmap=cmap,
norm=norm,
extend='both')]
except TypeError:
contourf += [
ax.contourf(
xx, yy,
df.loc[(slice(None), slice(*depth)), variable] \
.unstack(level='time').values,
vmin=vmin,
vmax=vmax,
levels=100,
cmap=cmap,
norm=norm,
extend='both')]
cbar_title = 'Direção de Corrente [°]'
try:
ax[i].invert_yaxis()
ax[i].set_ylabel('Profundidade [m]', fontsize=22)
ax[i].tick_params(axis='y', which='major', labelsize=16)
except TypeError:
ax.invert_yaxis()
ax.set_ylabel('Profundidade [m]', fontsize=22)
ax.tick_params(axis='y', which='major', labelsize=16)
# Título
try:
ax[0].set_title(
f'{dataset}\n'
f'Ponto de grade próximo à {point_name.capitalize()}\n'
'Diagrama Hovmöller',
fontsize=22, pad=18)
except NameError:
ax[0].set_title(
f'{dataset}\nPonto de grade próximo à'
f' lat={round(ds["lat"].item(), ndigits=4)},'
f' lon={round(ds["lon"].item(), ndigits=4)}\n'
'Diagrama Hovmöller',
fontsize=22, pad=18)
except TypeError:
ax.set_title(
f'{dataset}\n'
f'Ponto de grade próximo à {point_name.capitalize()}\n'
'Diagrama Hovmöller',
fontsize=22, pad=18)
cbar = fig.colorbar(
ScalarMappable(norm=contourf[0].norm, cmap=contourf[0].cmap),
ax=ax, ticks=ticks, fraction=.015, shrink=.75,
extend='both')
cbar.ax.tick_params(labelsize=18, pad=10)
cbar.set_label(cbar_title, rotation=270, fontsize=22, labelpad=30)
month_labels = df[variable].index.get_level_values('time') \
.unique().strftime('%m/%Y').unique().to_list()
major_labels = [
label
for label in month_labels
if pd.to_datetime(label, format='%m/%Y').month == 1]
major_ticks = pd.to_numeric(
pd.to_datetime(major_labels, format='%m/%Y')).tolist()
_minor_labels = [
label
for label in month_labels
if pd.to_datetime(label, format='%m/%Y').month in [3, 6, 9, 12]]
minor_ticks = pd.to_numeric(
pd.to_datetime(_minor_labels, format='%m/%Y')).tolist()
minor_labels = [
dt.strftime('%m')
for dt in pd.to_datetime(month_labels, format='%m/%Y')
if dt.month in [3, 6, 9, 12]]
try:
ax[-1].set_xticks(
major_ticks, major_labels, minor=False,
rotation=90, fontsize=16, ha='center')
ax[-1].set_xticks(
minor_ticks, minor_labels, minor=True,
rotation=90, fontsize=14, ha='center')
except TypeError:
ax.set_xticks(
major_ticks, major_labels, minor=False,
rotation=90, fontsize=16, ha='center')
ax.set_xticks(
minor_ticks, minor_labels, minor=True,
rotation=90, fontsize=14, ha='center')
try:
for _ax in ax:
if _ax == ax[-1]:
labelbottom = True
else:
labelbottom = False
_ = _ax.tick_params(
axis='x', which='major', direction='out',
bottom=True, top=True, labelbottom=labelbottom, labeltop=False,
width=2, length=8, pad=20)
_ = _ax.tick_params(
axis='x', which='minor', direction='out',
bottom=True, top=True, labelbottom=labelbottom, labeltop=False,
width=1, length=5)
except TypeError:
_ = ax.tick_params(
axis='x', which='major', direction='out',
bottom=True, top=True, labelbottom=True, labeltop=False,
width=2, length=8, pad=20)
_ = ax.tick_params(
axis='x', which='minor', direction='out',
bottom=True, top=True, labelbottom=True, labeltop=False,
width=1, length=5)
# ax.grid(which='major', color='grey', linestyle='--', linewidth=0.8)
fig.subplots_adjust(left=.08, right=.87, top=.89, bottom=.13, hspace=.08)
if clabel:
cs_plus = ax.contour(
df[variable].unstack(level='time').values,
levels=levels, colors='k', linewidths=.2, zorder=3)
ax.clabel(
cs_plus, levels,
fmt='', inline=True, inline_spacing=15, fontsize=10)
cs_minus = ax.contour(
df[variable].unstack(level='time').values,
levels=-levels[::-1], colors='w', linewidths=.2, zorder=3)
ax.clabel(
cs_minus, -levels[::-1],
fmt='', inline=True, inline_spacing=15, fontsize=10)
fig.savefig(
f'{path2save}/hovmoller_{variable}_{_depth[0]}-{_depth[-1]}m'
f'{df.index.get_level_values("time")[0].strftime(r"%b%Y")}'
f'-{df.index.get_level_values("time")[-1].strftime(r"%b%Y")}_.png',
format='png')
return fig, ax
def plot_profile():
interannual_mean = df[['spd', 'dir']].groupby(
pd.Grouper(level='depth')).mean()
interannual_mean['dir'] *= np.nan
interannual_mean['dir'] = df['dir'].groupby(
pd.Grouper(level='depth')).apply(
lambda x: circmean(x, high=360.))
# Daily Maximum
# media_mensal =
# for depth in ds.depth.values:
# media_mensal = df.xs(depth, level='depth').groupby(
# pd.Grouper(freq='1M')).mean()
fig, ax = plt.subplots()
ax.plot(interannual_mean['spd'], -(interannual_mean.index.values))
# Move left y-axis to centre
# ax.spines['left'].set_position('center')
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
ax.set_xlim(0, interannual_mean['spd'].max())
ax.set_ylim(-interannual_mean.index.values.max(), 100)
ax.tick_params(
axis='x', which='major',
bottom=False, labelbottom=False,
top=True, labeltop=True)
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_color('none')
ax.grid(True, color='k', linestyle=':', linewidth=.3)
ax.set_ylabel('Profundidade [m]', fontsize=12, labelpad=30, rotation=270)
ax.yaxis.set_label_position('right')
ax.set_xlabel('Intensidade [m/s]', fontsize=12, labelpad=10)
ax.xaxis.set_label_position('top')
# ax.text(
# ax.get_xlim()[0],
# ax.get_ylim()[0],
# f'{ds.time[0].dt.strftime("%d/%m/%Y %Hh").item()}',
# bbox=dict(boxstyle='round', facecolor='w', pad=.3),
# fontsize=10, fontweight='roman')
fig.savefig(f'{path_local}/perfil.png', format='png')
return None
if __name__ == '__main__':
# Mapeamento Contêiner
path_local = '/rotinas'
path_data = '/base'
path2save = '/figuras'
sys.path.insert(0, f'{path_local}/utils')
from values import *
with open(
'/'.join([path_local, 'input_profile.json'])) as f:
daux = json.load(f)
dataset = daux['dataset'] # nome da base de dados
path_dataset = daux['data_path'] # path dos dados
start = daux['start'] # data inicial
end = daux['end'] # data final
year = daux['year'] # ano específico
ds = xr.open_mfdataset(f'{path_data}/{path_dataset}/*.nc', autoclose=True)
ds['spd'], ds['dir'] = uv2spddir(ds['uvel'], ds['vvel'])
df = ds[['spd', 'dir']].to_dataframe()
df.drop(['lat', 'lon'], axis=1, inplace=True)
if any(df['spd'].isna()):
df.drop(df[df['spd'].isna()].index, inplace=True)
fig, ax = plt.subplots()