forked from rjrolph5/ERA5_calc_and_plotting_scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwindrose.py
736 lines (626 loc) · 27.6 KB
/
windrose.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# from __future__ import absolute_import, division, print_function
# from https://github.com/akrherz/windrose/blob/darylchanges/windrose/windrose.py
# Modified by Becca R.
from matplotlib.projections import register_projection
import locale
import matplotlib as mpl
import numpy as np
import random
from matplotlib.projections.polar import PolarAxes
from numpy.lib.twodim_base import histogram2d
import matplotlib.pyplot as plt
RESOLUTION = 100
ZBASE = -1000 # The starting zorder for all drawing, negative to have the grid on
VAR_DEFAULT = 'speed'
DIR_DEFAULT = 'direction'
FIGSIZE_DEFAULT = (8, 8)
DPI_DEFAULT = 80
class WindAxesFactory(object):
# Create based on class name:
@staticmethod
def create(typ, ax=None, *args, **kwargs):
typ = typ.lower()
d = {
'windroseaxes': WindroseAxes,
'windaxes': WindAxes
}
if typ in d.keys():
cls = d[typ]
if isinstance(ax, cls):
return ax
else:
ax = cls.from_ax(ax, *args, **kwargs)
return ax
else:
raise(NotImplementedError("typ=%r but it might be in %s" % (typ, d.keys())))
class WindroseAxes(PolarAxes):
"""
Create a windrose axes
"""
name = 'windrose'
def __init__(self, *args, **kwargs):
"""
See Axes base class for args and kwargs documentation
"""
# Uncomment to have the possibility to change the resolution directly
# when the instance is created
# self.RESOLUTION = kwargs.pop('resolution', 100)
self.rmax = kwargs.pop('rmax', None)
PolarAxes.__init__(self, *args, **kwargs)
self.set_aspect('equal', adjustable='box', anchor='C')
self.radii_angle = 67.5
self.cla()
@staticmethod
def from_ax(ax=None, fig=None, rmax=None, *args, **kwargs):
if ax is None:
if fig is None:
fig = plt.figure(figsize=FIGSIZE_DEFAULT, dpi=DPI_DEFAULT, facecolor='w', edgecolor='w')
rect = [0.1, 0.1, 0.8, 0.8]
ax = WindroseAxes(fig, rect, facecolor='w', rmax=rmax, *args, **kwargs)
fig.add_axes(ax)
return ax
else:
return ax
def cla(self):
"""
Clear the current axes
"""
PolarAxes.cla(self)
self.theta_angles = np.arange(0, 360, 45)
self.theta_labels = ['E', 'N-E', 'N', 'N-W', 'W', 'S-W', 'S', 'S-E']
self.set_thetagrids(angles=self.theta_angles, labels=self.theta_labels)
self._info = {
'dir': list(),
'bins': list(),
'table': list()
}
self.patches_list = list()
def _colors(self, cmap, n):
"""
Returns a list of n colors based on the colormap cmap
"""
return [cmap(i) for i in np.linspace(0.0, 1.0, n)]
def set_radii_angle(self, **kwargs):
"""
Set the radii labels angle
"""
kwargs.pop('labels', None)
angle = kwargs.pop('angle', None)
if angle is None:
angle = self.radii_angle
self.radii_angle = angle
N = 5
rmax = self.get_rmax()
radii = np.linspace(0, rmax, N + 1)
if rmax % N == 0:
fmt = "%d"
else:
fmt = "%.1f"
radii_labels = [fmt % r for r in radii]
# radii_labels[0] = "" # Removing label 0
self.set_rgrids(radii=radii[1:], labels=radii_labels[1:],
angle=self.radii_angle, **kwargs)
def _update(self):
if self.rmax is None:
# DEH edit to not use calm in the limits
self.set_rmax(rmax=np.max(np.sum(self._info['table'][1:,:], axis=0)))
else:
self.set_rmax(rmax=self.rmax)
self.set_radii_angle(angle=self.radii_angle)
def legend(self, loc='lower left', **kwargs):
"""
Sets the legend location and her properties.
The location codes are
'best' : 0,
'upper right' : 1,
'upper left' : 2,
'lower left' : 3,
'lower right' : 4,
'right' : 5,
'center left' : 6,
'center right' : 7,
'lower center' : 8,
'upper center' : 9,
'center' : 10,
If none of these are suitable, loc can be a 2-tuple giving x,y
in axes coords, ie,
loc = (0, 1) is left top
loc = (0.5, 0.5) is center, center
and so on. The following kwargs are supported:
isaxes=True # whether this is an axes legend
prop = FontProperties(size='smaller') # the font property
pad = 0.2 # the fractional whitespace inside the legend border
shadow # if True, draw a shadow behind legend
labelsep = 0.005 # the vertical space between the legend entries
handlelen = 0.05 # the length of the legend lines
handletextsep = 0.02 # the space between the legend line and legend text
borderaxespad = 0.02 # the border between the axes and legend edge
decimal_places = 1 # the decimal places of the formated legend
"""
def get_handles():
handles = list()
for p in self.patches_list:
if isinstance(p, mpl.patches.Polygon) or \
isinstance(p, mpl.patches.Rectangle):
color = p.get_facecolor()
elif isinstance(p, mpl.lines.Line2D):
color = p.get_color()
else:
raise AttributeError("Can't handle patches")
handles.append(mpl.patches.Rectangle((0, 0), 0.2, 0.2,
facecolor=color, edgecolor='black'))
return handles
def get_labels(decimal_places=1):
_decimal_places = str(decimal_places)
fmt = (
"[%." + _decimal_places + "f " +
": %0." + _decimal_places + "f"
)
labels = np.copy(self._info['bins'])
if locale.getlocale()[0] in ['fr_FR']:
fmt += '['
else:
fmt += ')'
labels = [fmt % (labels[i], labels[i + 1])
for i in range(len(labels) - 1)]
return labels
kwargs.pop('labels', None)
kwargs.pop('handles', None)
decimal_places = kwargs.pop('decimal_places', 1)
handles = get_handles()
labels = get_labels(decimal_places)
self.legend_ = mpl.legend.Legend(self, handles, labels, loc, **kwargs)
return self.legend_
def set_legend(self, **pyplot_arguments):
if 'borderaxespad' not in pyplot_arguments:
pyplot_arguments['borderaxespad'] = -0.10
l = self.legend(**pyplot_arguments)
plt.setp(l.get_texts(), fontsize=8)
def _init_plot(self, direction, var, **kwargs):
"""
Internal method used by all plotting commands
direction : 1D array - directions the wind blows from, North centred
var : 1D array - values of the variable to compute. Typically the wind
speeds
"""
# if weibull factors are entered overwrite direction and var
if 'weibull_factors' in kwargs or 'mean_values' in kwargs:
if 'weibull_factors' in kwargs and 'mean_values' in kwargs:
raise TypeError("cannot specify both weibull_factors and mean_values")
statistic_type = 'unset'
if 'weibull_factors' in kwargs:
statistic_type = 'weibull'
val = kwargs.pop('weibull_factors')
elif 'mean_values' in kwargs:
statistic_type = 'mean'
val = kwargs.pop('mean_values')
if val:
if 'frequency' not in kwargs:
raise TypeError("specify 'frequency' argument for statistical input")
windFrequencies = kwargs.pop('frequency')
if len(windFrequencies) != len(direction) or len(direction) != len(var):
if len(windFrequencies) != len(direction):
raise TypeError("len(frequency) != len(direction)")
elif len(direction) != len(var):
raise TypeError("len(frequency) != len(direction)")
windSpeeds = []
windDirections = []
for dbin in range(len(direction)):
for _ in range(int(windFrequencies[dbin] * 10000)):
if statistic_type == 'weibull':
windSpeeds.append(random.weibullvariate(var[dbin][0], var[dbin][1]))
elif statistic_type == 'mean':
windSpeeds.append(random.weibullvariate(var[dbin] * 2 / np.sqrt(np.pi), 2))
windDirections.append(direction[dbin])
var, direction = windSpeeds, windDirections
# self.cla()
kwargs.pop('zorder', None)
# Init of the bins array if not set
bins = kwargs.pop('bins', None)
if bins is None:
bins = np.linspace(np.min(var), np.max(var), 6)
if isinstance(bins, int):
bins = np.linspace(np.min(var), np.max(var), bins)
bins = np.asarray(bins)
nbins = len(bins)
# Number of sectors
nsector = kwargs.pop('nsector', None)
if nsector is None:
nsector = 16
# Sets the colors table based on the colormap or the "colors" argument
colors = kwargs.pop('colors', None)
cmap = kwargs.pop('cmap', None)
if colors is not None:
if isinstance(colors, str):
colors = [colors] * nbins
if isinstance(colors, (tuple, list)):
if len(colors) != nbins:
raise ValueError("colors and bins must have same length")
else:
if cmap is None:
cmap = mpl.cm.jet
colors = self._colors(cmap, nbins)
# Building the angles list
angles = np.arange(0, -2 * np.pi, -2 * np.pi / nsector) + np.pi / 2
normed = kwargs.pop('normed', False)
blowto = kwargs.pop('blowto', False)
# Set the global information dictionnary
self._info['dir'], self._info['bins'], self._info['table'] = histogram(direction, var, bins, nsector, normed, blowto)
return bins, nbins, nsector, colors, angles, kwargs
def contour(self, direction, var, **kwargs):
"""
Plot a windrose in linear mode. For each var bins, a line will be
draw on the axes, a segment between each sector (center to center).
Each line can be formated (color, width, ...) like with standard plot
pylab command.
Mandatory:
* direction : 1D array - directions the wind blows from, North centred
* var : 1D array - values of the variable to compute. Typically the wind
speeds
Optional:
* nsector: integer - number of sectors used to compute the windrose
table. If not set, nsectors=16, then each sector will be 360/16=22.5°,
and the resulting computed table will be aligned with the cardinals
points.
* bins : 1D array or integer- number of bins, or a sequence of
bins variable. If not set, bins=6, then
bins=linspace(min(var), max(var), 6)
* blowto : bool. If True, the windrose will be pi rotated,
to show where the wind blow to (usefull for pollutant rose).
* colors : string or tuple - one string color ('k' or 'black'), in this
case all bins will be plotted in this color; a tuple of matplotlib
color args (string, float, rgb, etc), different levels will be plotted
in different colors in the order specified.
* cmap : a cm Colormap instance from matplotlib.cm.
- if cmap == None and colors == None, a default Colormap is used.
others kwargs : see help(pylab.plot)
"""
bins, nbins, nsector, colors, angles, kwargs = self._init_plot(direction, var,
**kwargs)
# closing lines
angles = np.hstack((angles, angles[-1] - 2 * np.pi / nsector))
vals = np.hstack((self._info['table'],
np.reshape(self._info['table'][:, 0],
(self._info['table'].shape[0], 1))))
offset = 0
for i in range(nbins):
val = vals[i, :] + offset
offset += vals[i, :]
zorder = ZBASE + nbins - i
patch = self.plot(angles, val, color=colors[i], zorder=zorder,
**kwargs)
self.patches_list.extend(patch)
self._update()
def contourf(self, direction, var, **kwargs):
"""
Plot a windrose in filled mode. For each var bins, a line will be
draw on the axes, a segment between each sector (center to center).
Each line can be formated (color, width, ...) like with standard plot
pylab command.
Mandatory:
* direction : 1D array - directions the wind blows from, North centred
* var : 1D array - values of the variable to compute. Typically the wind
speeds
Optional:
* nsector: integer - number of sectors used to compute the windrose
table. If not set, nsectors=16, then each sector will be 360/16=22.5°,
and the resulting computed table will be aligned with the cardinals
points.
* bins : 1D array or integer- number of bins, or a sequence of
bins variable. If not set, bins=6, then
bins=linspace(min(var), max(var), 6)
* blowto : bool. If True, the windrose will be pi rotated,
to show where the wind blow to (usefull for pollutant rose).
* colors : string or tuple - one string color ('k' or 'black'), in this
case all bins will be plotted in this color; a tuple of matplotlib
color args (string, float, rgb, etc), different levels will be plotted
in different colors in the order specified.
* cmap : a cm Colormap instance from matplotlib.cm.
- if cmap == None and colors == None, a default Colormap is used.
others kwargs : see help(pylab.plot)
"""
bins, nbins, nsector, colors, angles, kwargs = self._init_plot(direction, var,
**kwargs)
kwargs.pop('facecolor', None)
kwargs.pop('edgecolor', None)
# closing lines
angles = np.hstack((angles, angles[-1] - 2 * np.pi / nsector))
vals = np.hstack((self._info['table'],
np.reshape(self._info['table'][:, 0],
(self._info['table'].shape[0], 1))))
offset = 0
for i in range(nbins):
val = vals[i, :] + offset
offset += vals[i, :]
zorder = ZBASE + nbins - i
patch = self.fill(np.append(angles, 0), np.append(val, 0),
facecolor=colors[i], edgecolor=colors[i],
zorder=zorder, **kwargs)
self.patches_list.extend(patch)
def bar(self, direction, var, **kwargs):
"""
Plot a windrose in bar mode. For each var bins and for each sector,
a colored bar will be draw on the axes.
Mandatory:
* direction : 1D array - directions the wind blows from, North centred
* var : 1D array - values of the variable to compute. Typically the wind
speeds
Optional:
* nsector: integer - number of sectors used to compute the windrose
table. If not set, nsectors=16, then each sector will be 360/16=22.5°,
and the resulting computed table will be aligned with the cardinals
points.
* bins : 1D array or integer- number of bins, or a sequence of
bins variable. If not set, bins=6 between min(var) and max(var).
* blowto : bool. If True, the windrose will be pi rotated,
to show where the wind blow to (usefull for pollutant rose).
* colors : string or tuple - one string color ('k' or 'black'), in this
case all bins will be plotted in this color; a tuple of matplotlib
color args (string, float, rgb, etc), different levels will be plotted
in different colors in the order specified.
* cmap : a cm Colormap instance from matplotlib.cm.
- if cmap == None and colors == None, a default Colormap is used.
edgecolor : string - The string color each edge bar will be plotted.
Default : no edgecolor
* opening : float - between 0.0 and 1.0, to control the space between
each sector (1.0 for no space)
"""
bins, nbins, nsector, colors, angles, kwargs = self._init_plot(direction, var,
**kwargs)
kwargs.pop('facecolor', None)
edgecolor = kwargs.pop('edgecolor', None)
if edgecolor is not None:
if not isinstance(edgecolor, str):
raise ValueError('edgecolor must be a string color')
opening = kwargs.pop('opening', None)
if opening is None:
opening = 0.8
dtheta = 2 * np.pi / nsector
opening = dtheta * opening
for j in range(nsector):
offset = 0
# DEH edit to keep first bin from plotting
for i in range(1, nbins):
# DEH edit again
if i > 1:
offset += self._info['table'][i - 1, j]
val = self._info['table'][i, j]
zorder = ZBASE + nbins - i
patch = mpl.patches.Rectangle(
(angles[j] - opening / 2, offset), opening, val,
facecolor=colors[i], edgecolor=edgecolor, zorder=zorder,
**kwargs)
self.add_patch(patch)
if j == 0:
self.patches_list.append(patch)
self._update()
def box(self, direction, var, **kwargs):
"""
Plot a windrose in proportional bar mode. For each var bins and for each
sector, a colored bar will be draw on the axes.
Mandatory:
* direction : 1D array - directions the wind blows from, North centred
* var : 1D array - values of the variable to compute. Typically the wind
speeds
Optional:
* nsector: integer - number of sectors used to compute the windrose
table. If not set, nsectors=16, then each sector will be 360/16=22.5°,
and the resulting computed table will be aligned with the cardinals
points.
* bins : 1D array or integer- number of bins, or a sequence of
bins variable. If not set, bins=6 between min(var) and max(var).
* blowto : bool. If True, the windrose will be pi rotated,
to show where the wind blow to (usefull for pollutant rose).
* colors : string or tuple - one string color ('k' or 'black'), in this
case all bins will be plotted in this color; a tuple of matplotlib
color args (string, float, rgb, etc), different levels will be plotted
in different colors in the order specified.
* cmap : a cm Colormap instance from matplotlib.cm.
- if cmap == None and colors == None, a default Colormap is used.
edgecolor : string - The string color each edge bar will be plotted.
Default : no edgecolor
"""
bins, nbins, nsector, colors, angles, kwargs = self._init_plot(direction, var,
**kwargs)
kwargs.pop('facecolor', None)
edgecolor = kwargs.pop('edgecolor', None)
if edgecolor is not None:
if not isinstance(edgecolor, str):
raise ValueError('edgecolor must be a string color')
opening = np.linspace(0.0, np.pi / 16, nbins)
for j in range(nsector):
offset = 0
for i in range(nbins):
if i > 0:
offset += self._info['table'][i - 1, j]
val = self._info['table'][i, j]
zorder = ZBASE + nbins - i
patch = mpl.patches.Rectangle(
(angles[j] - opening[i] / 2, offset), opening[i],
val, facecolor=colors[i], edgecolor=edgecolor,
zorder=zorder, **kwargs)
self.add_patch(patch)
if j == 0:
self.patches_list.append(patch)
self._update()
class WindAxes(mpl.axes.Subplot):
def __init__(self, *args, **kwargs):
"""
See Axes base class for args and kwargs documentation
"""
super(WindAxes, self).__init__(*args, **kwargs)
@staticmethod
def from_ax(ax=None, fig=None, *args, **kwargs):
if ax is None:
if fig is None:
fig = plt.figure(figsize=FIGSIZE_DEFAULT, dpi=DPI_DEFAULT)
ax = WindAxes(fig, 1, 1, 1, *args, **kwargs)
fig.add_axes(ax)
return ax
else:
return(ax)
def pdf(self, var, bins=None, Nx=100, bar_color='b', plot_color='g', Nbins=10, *args, **kwargs):
'''
Draw probability density function
and return Weibull distribution parameters
'''
import scipy.stats
if bins is None:
bins = np.linspace(0, np.max(var), Nbins)
hist, bins = np.histogram(var, bins=bins, normed=True)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
self.bar(center, hist, align='center', width=width, color=bar_color)
params = scipy.stats.exponweib.fit(var, floc=0, f0=1)
x = np.linspace(0, bins[-1], Nx)
self.plot(x, scipy.stats.exponweib.pdf(x, *params), color=plot_color)
return(self, params)
def histogram(direction, var, bins, nsector, normed=False, blowto=False):
"""
Returns an array where, for each sector of wind
(centred on the north), we have the number of time the wind comes with a
particular var (speed, polluant concentration, ...).
* direction : 1D array - directions the wind blows from, North centred
* var : 1D array - values of the variable to compute. Typically the wind
speeds
* bins : list - list of var category against we're going to compute the table
* nsector : integer - number of sectors
* normed : boolean - The resulting table is normed in percent or not.
* blowto : boolean - Normaly a windrose is computed with directions
as wind blows from. If true, the table will be reversed (usefull for
pollutantrose)
"""
if len(var) != len(direction):
raise(ValueError("var and direction must have same length"))
angle = 360. / nsector
dir_bins = np.arange(-angle / 2, 360. + angle, angle, dtype=np.float)
dir_edges = dir_bins.tolist()
dir_edges.pop(-1)
dir_edges[0] = dir_edges.pop(-1)
dir_bins[0] = 0.
var_bins = bins.tolist()
var_bins.append(np.inf)
if blowto:
direction = direction + 180.
direction[direction >= 360.] = direction[direction >= 360.] - 360
table = histogram2d(x=var, y=direction, bins=[var_bins, dir_bins],
normed=False)[0]
# add the last value to the first to have the table of North winds
table[:, 0] = table[:, 0] + table[:, -1]
# and remove the last col
table = table[:, :-1]
if normed:
table = table * 100 / table.sum()
return dir_edges, var_bins, table
def wrcontour(direction, var, ax=None, rmax=None, **kwargs):
ax = WindroseAxes.from_ax(ax, rmax=rmax)
ax.contour(direction, var, **kwargs)
ax.set_legend()
return ax
def wrcontourf(direction, var, ax=None, rmax=None, **kwargs):
ax = WindroseAxes.from_ax(ax, rmax=rmax)
ax.contourf(direction, var, **kwargs)
ax.set_legend()
return ax
def wrbox(direction, var, ax=None, rmax=None, **kwargs):
ax = WindroseAxes.from_ax(ax, rmax=rmax)
ax.box(direction, var, **kwargs)
ax.set_legend()
return ax
def wrbar(direction, var, ax=None, rmax=None, **kwargs):
ax = WindroseAxes.from_ax(ax, rmax=rmax)
ax.bar(direction, var, **kwargs)
ax.set_legend()
return ax
def wrpdf(var, bins=None, Nx=100, bar_color='b', plot_color='g', Nbins=10, ax=None, rmax=None, *args, **kwargs):
'''
Draw probability density function
and return Weitbull distribution parameters
'''
ax = WindAxes.from_ax(ax)
ax, params = ax.pdf(var, bins, Nx, bar_color, plot_color, *args, **kwargs)
return(ax, params)
def wrscatter(direction, var, ax=None, rmax=None, *args, **kwargs):
'''
Draw scatter plot
'''
ax = WindroseAxes.from_ax(ax, rmax=rmax)
ax.scatter(direction, var, *args, **kwargs)
return ax
# def clean(direction, var):
# '''
# Remove masked values in the two arrays, where if a direction data is masked,
# the var data will also be removed in the cleaning process (and vice-versa)
# '''
# dirmask = direction.mask==False
# varmask = direction.mask==False
# mask = dirmask*varmask
# return direction[mask], var[mask]
def clean_df(df, var=VAR_DEFAULT, direction=DIR_DEFAULT):
'''
Remove nan and var=0 values in the DataFrame
if a var (wind speed) is nan or equal to 0, this row is
removed from DataFrame
if a direction is nan, this row is also removed from DataFrame
'''
return(df[df[var].notnull() & df[var] != 0 & df[direction].notnull()])
def clean(direction, var, index=False):
'''
Remove nan and var=0 values in the two arrays
if a var (wind speed) is nan or equal to 0, this data is
removed from var array but also from dir array
if a direction is nan, data is also removed from both array
'''
dirmask = np.isfinite(direction)
varmask = (var != 0 & np.isfinite(var))
mask = dirmask * varmask
if index is None:
index = np.arange(mask.sum())
return direction[mask], var[mask], index
elif not index:
return direction[mask], var[mask]
else:
index = index[mask]
return direction[mask], var[mask], index
D_KIND_PLOT = {
'contour': wrcontour,
'contourf': wrcontourf,
'box': wrbox,
'bar': wrbar,
'pdf': wrpdf,
'scatter': wrscatter
}
def plot_windrose(direction_or_df, var=None, kind='contour', var_name=VAR_DEFAULT, direction_name=DIR_DEFAULT, by=None, rmax=None, **kwargs):
if var is None:
# Assuming direction_or_df is a DataFrame
df = direction_or_df
var = df[var_name].values
direction = df[direction_name].values
else:
direction = direction_or_df
return(plot_windrose_np(direction, var, kind=kind, by=by, rmax=rmax, **kwargs))
def plot_windrose_df(df, kind='contour', var_name=VAR_DEFAULT, direction_name=DIR_DEFAULT, by=None, rmax=None, **kwargs):
var = df[var_name].values
direction = df[direction_name].values
return(plot_windrose_np(direction, var, by=by, rmax=rmax, **kwargs))
def plot_windrose_np(direction, var, kind='contour', clean_flag=True, by=None, rmax=None, **kwargs):
if kind in D_KIND_PLOT.keys():
f_plot = D_KIND_PLOT[kind]
else:
raise(Exception("kind=%r but it must be in %r" % (kind, D_KIND_PLOT.keys())))
# if f_clean is not None:
# df = f_clean(df)
# var = df[var_name].values
# direction = df[direction_name].values
if clean_flag:
var, direction = clean(var, direction)
if by is None:
ax = f_plot(direction=direction, var=var, rmax=rmax, **kwargs)
if kind not in ['pdf']:
ax.set_legend()
return ax
else:
raise(NotImplementedError("'by' keyword not supported for now https://github.com/scls19fr/windrose/issues/10"))
register_projection(WindroseAxes)