1
- import os
2
- import math
3
1
import numpy as np
4
2
import pandas as pd
5
3
import seaborn as sns
4
+ import scipy .stats as st
6
5
import matplotlib .pyplot as plt
7
- import scipy . stats as stats
6
+
8
7
from matplotlib .dates import MonthLocator , DateFormatter
9
- import calendar
10
- from math import floor ,ceil
11
- from ..stats .general import *
12
- from ..tables .general import *
8
+ import matplotlib .ticker as mticker
9
+ import matplotlib .patches as mpatches
10
+ from cycler import cycler
11
+
12
+ from .. import stats
13
+ from .. import tables
13
14
14
15
15
16
def plot_scatter_diagram (data : pd .DataFrame , var1 : str , step_var1 : float , var2 : str , step_var2 : float , output_file ):
@@ -21,7 +22,7 @@ def plot_scatter_diagram(data: pd.DataFrame, var1: str, step_var1: float, var2:
21
22
outputfile: name of output file with extrensition e.g., png, eps or pdf
22
23
"""
23
24
24
- sd = calculate_scatter (data , var1 , step_var1 , var2 , step_var2 )
25
+ sd = tables . calculate_scatter (data , var1 , step_var1 , var2 , step_var2 )
25
26
26
27
# Convert to percentage
27
28
tbl = sd .values
@@ -67,31 +68,24 @@ def plot_scatter_diagram(data: pd.DataFrame, var1: str, step_var1: float, var2:
67
68
68
69
def plot_pdf_all (data , var , bins = 70 , output_file = 'pdf_all.png' ): #pdf_all(data, bins=70)
69
70
70
- import matplotlib .pyplot as plt
71
- from scipy .stats import expon
72
- from scipy .stats import genextreme
73
- from scipy .stats import gumbel_r
74
- from scipy .stats import lognorm
75
- from scipy .stats import weibull_min
76
-
77
71
data = data [var ].values
78
72
79
73
x = np .linspace (min (data ),max (data ),100 )
80
74
81
- param = weibull_min .fit (data ) # shape, loc, scale
82
- pdf_weibull = weibull_min .pdf (x , param [0 ], loc = param [1 ], scale = param [2 ])
75
+ param = st . weibull_min .fit (data ) # shape, loc, scale
76
+ pdf_weibull = st . weibull_min .pdf (x , param [0 ], loc = param [1 ], scale = param [2 ])
83
77
84
- param = expon .fit (data ) # loc, scale
85
- pdf_expon = expon .pdf (x , loc = param [0 ], scale = param [1 ])
78
+ # param = expon.fit(data) # loc, scale
79
+ # pdf_expon = expon.pdf(x, loc=param[0], scale=param[1])
86
80
87
- param = genextreme .fit (data ) # shape, loc, scale
88
- pdf_gev = genextreme .pdf (x , param [0 ], loc = param [1 ], scale = param [2 ])
81
+ param = st . genextreme .fit (data ) # shape, loc, scale
82
+ pdf_gev = st . genextreme .pdf (x , param [0 ], loc = param [1 ], scale = param [2 ])
89
83
90
- param = gumbel_r .fit (data ) # loc, scale
91
- pdf_gumbel = gumbel_r .pdf (x , loc = param [0 ], scale = param [1 ])
84
+ param = st . gumbel_r .fit (data ) # loc, scale
85
+ pdf_gumbel = st . gumbel_r .pdf (x , loc = param [0 ], scale = param [1 ])
92
86
93
- param = lognorm .fit (data ) # shape, loc, scale
94
- pdf_lognorm = lognorm .pdf (x , param [0 ], loc = param [1 ], scale = param [2 ])
87
+ param = st . lognorm .fit (data ) # shape, loc, scale
88
+ pdf_lognorm = st . lognorm .pdf (x , param [0 ], loc = param [1 ], scale = param [2 ])
95
89
96
90
fig , ax = plt .subplots (1 , 1 )
97
91
#ax.plot(x, pdf_expon, label='pdf-expon')
@@ -127,7 +121,7 @@ def strconv(name:str):
127
121
return mapping [name ]
128
122
else : return name
129
123
130
- if type (percentiles )== str : return strconv (percentiles )
124
+ if type (percentiles ) is str : return strconv (percentiles )
131
125
else : return [strconv (p ) for p in percentiles ]
132
126
133
127
def plot_monthly_stats (data : pd .DataFrame ,
@@ -285,7 +279,7 @@ def plot_directional_stats(data: pd.DataFrame, var: str, step_var: float, var_di
285
279
plot_directional_stats(data, 'hs', 0.1, 'Pdir', title='Directional Wave Statistics', output_file='directional_hs_stats.png')
286
280
"""
287
281
fig , ax = plt .subplots ()
288
- cumulative_percentage = table_directional_non_exceedance (data ,var ,step_var ,var_dir )
282
+ cumulative_percentage = tables . table_directional_non_exceedance (data ,var ,step_var ,var_dir )
289
283
for i in show :
290
284
cumulative_percentage .loc [i ][:- 1 ].plot (marker = 'o' )
291
285
#cumulative_percentage.loc['Maximum'][:-1].plot(marker = 'o')
@@ -300,7 +294,7 @@ def plot_directional_stats(data: pd.DataFrame, var: str, step_var: float, var_di
300
294
return fig
301
295
302
296
def plot_monthly_weather_window (data : pd .DataFrame , var : str ,threshold = 5 , window_size = 12 ,add_table = True , output_file : str = 'monthly_weather_window_plot.png' ):
303
- results_df = calculate_monthly_weather_window (data = data , var = var , threshold = threshold , window_size = window_size )
297
+ results_df = stats . calculate_monthly_weather_window (data = data , var = var , threshold = threshold , window_size = window_size )
304
298
# Plot the results
305
299
fig , ax = plt .subplots (figsize = (12 , 6 ))
306
300
results_df .T .plot (marker = 'o' )
@@ -335,39 +329,40 @@ def plot_monthly_weather_window(data: pd.DataFrame, var: str,threshold=5, window
335
329
336
330
return fig , table
337
331
338
-
339
- def plot_monthly_max_mean_min (df ,var = 'T2m' ,out_file = 'plot_monthly_max_min_min.png' ):
340
- out = sort_by_month (df )
341
- df2 = pd .DataFrame ()
342
- months = calendar .month_name [1 :] # eliminate the first insane one
343
- df2 ['month' ]= [x [:3 ] for x in months ] # get the three first letters
344
- df2 ['Min' ]= [np .min (out [m ][var ]) for m in out ]
345
- df2 ['Mean' ]= [np .mean (out [m ][var ]) for m in out ]
346
- df2 ['Max' ]= [np .max (out [m ][var ]) for m in out ]
332
+ # This function doesn't work, because sort_by_month is not defined.
333
+ # Therefore it's commented out. Maybe plot_monthly_stats above is a replacement.
334
+
335
+ # def plot_monthly_max_mean_min(df,var='T2m',out_file='plot_monthly_max_min_min.png'):
336
+ # out = sort_by_month(df)
337
+ # df2 = pd.DataFrame()
338
+ # months = calendar.month_name[1:] # eliminate the first insane one
339
+ # df2['month']=[x[:3] for x in months] # get the three first letters
340
+ # df2['Min']=[np.min(out[m][var]) for m in out]
341
+ # df2['Mean']=[np.mean(out[m][var]) for m in out]
342
+ # df2['Max']=[np.max(out[m][var]) for m in out]
347
343
348
- plt .plot (df2 ['month' ],df2 ['Min' ])
349
- plt .plot (df2 ['month' ],df2 ['Mean' ])
350
- plt .plot (df2 ['month' ],df2 ['Max' ])
351
- plt .ylabel ('Temperature [℃]' )
352
- plt .grid ()
353
- plt .savefig (out_file ,dpi = 100 ,facecolor = 'white' ,bbox_inches = 'tight' )
344
+ # plt.plot(df2['month'],df2['Min'])
345
+ # plt.plot(df2['month'],df2['Mean'])
346
+ # plt.plot(df2['month'],df2['Max'])
347
+ # plt.ylabel('Temperature [℃]')
348
+ # plt.grid()
349
+ # plt.savefig(out_file,dpi=100,facecolor='white',bbox_inches='tight')
354
350
355
- return df2
351
+ # return df2
356
352
357
353
358
354
def plot_profile_stats (data ,var = ['W10' ,'W50' ,'W80' ,'W100' ,'W150' ], z = [10 , 50 , 80 , 100 , 150 ],reverse_yaxis = False , output_file = 'stats_profile.png' ):
359
- import matplotlib .ticker as ticker
360
- df = table_profile_stats (data = data , var = var , z = z , output_file = None )
355
+ df = tables .table_profile_stats (data = data , var = var , z = z , output_file = None )
361
356
df = df .drop (['Std.dev' , 'Max Speed Event' ],axis = 1 )
362
357
fig , ax = plt .subplots ()
363
358
plt .yticks (z ) # Set yticks to be the values in z
364
- ax .yaxis .set_major_locator (ticker .MultipleLocator (int (max (z )/ 4 ))) # Set major y-ticks at intervals of 10
359
+ ax .yaxis .set_major_locator (mticker .MultipleLocator (int (max (z )/ 4 ))) # Set major y-ticks at intervals of 10
365
360
366
361
for column in df .columns [1 :]:
367
362
plt .plot (df [column ][1 :],z ,marker = '.' , label = column )
368
363
plt .ylabel ('z[m]' )
369
364
plt .xlabel ('[m/s]' )
370
- if reverse_yaxis == True :
365
+ if reverse_yaxis :
371
366
plt .gca ().invert_yaxis ()
372
367
plt .legend ()
373
368
plt .grid (True )
@@ -387,15 +382,12 @@ def plot_profile_monthly_stats(
387
382
reverse_yaxis = True ,
388
383
output_file = 'table_profile_monthly_stats.png' ,
389
384
include_year = True ):
390
- import matplotlib .pyplot as plt
391
- import matplotlib .ticker as ticker
392
- from cycler import cycler
393
385
394
386
# Custom color cycle
395
387
custom_cycler = cycler (color = ['b' , 'g' , 'r' , 'c' , 'm' , 'y' , 'k' ])
396
388
397
389
# Get the data
398
- df = table_profile_monthly_stats (data = data , var = var , z = z , method = method , output_file = None , rounding = None )
390
+ df = tables . table_profile_monthly_stats (data = data , var = var , z = z , method = method , output_file = None , rounding = None )
399
391
# Create a plot
400
392
fig , ax = plt .subplots ()
401
393
# Set the custom color cycle
@@ -404,7 +396,7 @@ def plot_profile_monthly_stats(
404
396
plt .yticks (z )
405
397
406
398
# Set major y-ticks at intervals of max(z)/4
407
- ax .yaxis .set_major_locator (ticker .MultipleLocator (int (max (z )/ 4 )))
399
+ ax .yaxis .set_major_locator (mticker .MultipleLocator (int (max (z )/ 4 )))
408
400
409
401
# Only plot specified variables.
410
402
if months == []:
@@ -434,7 +426,7 @@ def plot_profile_monthly_stats(
434
426
435
427
436
428
def plot_tidal_levels (data , var = 'tide' ,start_time = None , end_time = None ,output_file = 'tidal_levels.png' ):
437
- df = table_tidal_levels (data = data , var = var , output_file = None )
429
+ df = tables . table_tidal_levels (data = data , var = var , output_file = None )
438
430
if start_time and end_time is None :
439
431
data = data [var ]
440
432
else :
@@ -469,13 +461,13 @@ def plot_nb_hours_below_threshold(df,var='hs',thr_arr=(np.arange(0.05,20.05,0.05
469
461
# 2) var: a string
470
462
# 3) thr_arr: list of thresholds (should be a lot for smooth curve)
471
463
# 4) String with filename without extension
472
- nbhr_arr = nb_hours_below_threshold (df ,var ,thr_arr )
464
+ nbhr_arr = stats . nb_hours_below_threshold (df ,var ,thr_arr )
473
465
years = df .index .year .to_numpy ()
474
466
years_unique = np .unique (years )
475
467
yr1 = int (years_unique [0 ])
476
468
yr2 = int (years_unique [- 1 ])
477
469
del df ,years ,years_unique
478
- from matplotlib . patches import Patch
470
+
479
471
fig , ax = plt .subplots (figsize = (10 , 8 ))
480
472
ax .fill_between (thr_arr ,np .min (nbhr_arr ,axis = 1 ),np .max (nbhr_arr ,axis = 1 ),color = 'lightgray' )
481
473
ax .plot (thr_arr ,np .mean (nbhr_arr ,axis = 1 ),linewidth = 2 ,color = 'k' )
@@ -486,7 +478,7 @@ def plot_nb_hours_below_threshold(df,var='hs',thr_arr=(np.arange(0.05,20.05,0.05
486
478
ax .set_ylabel ('Number of hours' ,fontsize = 20 )
487
479
ax .tick_params (axis = 'both' , which = 'major' , labelsize = 18 )
488
480
ax .set_title ('Mean number of hours per year with ' + var + ' < threshold\n ' + str (yr1 )+ '-' + str (yr2 ),fontsize = 20 )
489
- legend_elements = [Patch (facecolor = 'lightgray' , edgecolor = None , label = 'Min-Max range' )]
481
+ legend_elements = [mpatches . Patch (facecolor = 'lightgray' , edgecolor = None , label = 'Min-Max range' )]
490
482
ax .legend (handles = legend_elements , loc = 'lower right' , prop = {'size' : 20 })
491
483
plt .savefig (output_file , dpi = 150 , bbox_inches = 'tight' )
492
484
plt .close ()
0 commit comments