import pandas as pd
import os
import datetime
import matplotlib.pyplot as plt
import re
from windrose import WindroseAxes
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import mpl_toolkits.axisartist
import cartopy.crs as ccrs
import cartopy.io.img_tiles as cimgt
ROUTE = './Datos dirección y velocidad del viento/Datos dirección y dirección del viento/'
df = pd.read_excel(
f'{ROUTE}Colina.xlsx',
names=['Date','Velocity (m/s)', 'Direction (degrees)'],
skiprows=range(0,6)).iloc[:-11]
def coordinates_to_decimal_degreses(coordinates_array):
lat_n_lon = []
for cor in coordinates_array:
cor_splitted = re.split('°|\'|"', cor)
cor_in_degrees = int(cor_splitted[0]) + (int(cor_splitted[1]) / 60) + (int(float(cor_splitted[2])) / 3600)
lat_n_lon.append(cor_in_degrees)
return lat_n_lon
folder = os.listdir(ROUTE)
dfs = [f'df_{file}'.strip('.xlsx') for file in folder]
for file in folder:
df = pd.read_excel(
f'{ROUTE}{file}',
names=['Date','Velocity (m/s)','Direction (degrees)'],
skiprows=range(0,6)).iloc[:-11]
lat_station = pd.read_excel( f'{ROUTE}{file}', names=['lat','lon','col'], skiprows=range(0,1)).iloc[0,0]
lon_station = pd.read_excel( f'{ROUTE}{file}', names=['lat','lon','col'], skiprows=range(0,1)).iloc[0,1]
dd_coordinate = coordinates_to_decimal_degreses([lat_station,lon_station])
dfs[folder.index(file)] = [dfs[folder.index(file)], df, dd_coordinate]
dfs[0][1].head()
dfs[0][1].describe()
dfs_dates = [date.replace(" 24:00", "") for date in dfs[0][1]["Date"]]
reference_dates = pd.date_range('01-01-2022', periods=334)
reference_dates_formatted = [datetime.datetime.strftime(ref_date, '%d-%m-%Y') for ref_date in reference_dates]
dates_missing_in_dataset = [date for date in reference_dates_formatted if date not in dfs_dates]
dates_missing_in_dataset
for df in dfs:
print(f'In station {df[0]} the days missing velocity record are: \n {df[1]["Date"][df[1]["Velocity (m/s)"] == "----"]} \n Number of days: {df[1]["Date"][df[1]["Velocity (m/s)"] == "----"].count()} \n')
for df in dfs:
print(f'{df[0]}: { round(df[1]["Velocity (m/s)"][ (df[1]["Velocity (m/s)"] != "----")][ (df[1]["Direction (degrees)"] != "----")].mean(),2) }' )
data = {
'station':[df[0] for df in dfs],
'avg_velocity': [ round(df[1]["Velocity (m/s)"][df[1]["Velocity (m/s)"] != "----"][ (df[1]["Direction (degrees)"] != "----")].mean(),2) for df in dfs]
}
ds = pd.DataFrame(data)
ds.plot(x='station', y='avg_velocity', kind='barh', figsize=(20,10), xlabel='avg_velocity (m/s)')
plt.show()
ws = dfs[7][1]["Velocity (m/s)"][dfs[7][1]["Velocity (m/s)"] != '----'][dfs[7][1]["Direction (degrees)"] != "----"]
wd = dfs[7][1]["Direction (degrees)"][dfs[7][1]["Velocity (m/s)"] != '----'][dfs[7][1]["Direction (degrees)"] != "----"]
wd
ax = WindroseAxes.from_ax()
ax.bar(wd, ws, normed=False, opening=0.8, edgecolor='white')
ax.set_legend()
ax.set_title('Title', fontsize=16)
def generate_plot_set(dfs_subarray):
fig = plt.figure(figsize=(20,20))
for df in dfs_subarray:
ws = df[1]["Velocity (m/s)"][df[1]["Velocity (m/s)"] != '----'][ df[1]["Direction (degrees)"] != "----"]
wd = df[1]["Direction (degrees)"][df[1]["Velocity (m/s)"] != '----'][ df[1]["Direction (degrees)"] != "----"]
position = str(24)+str(dfs_subarray.index(df)+1)
title = df[0]
ax = fig.add_subplot( int(position), projection="windrose")
ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='white')
ax.set_title(title)
ax.legend(bbox_to_anchor=(0.5, -0.3), title="Wind velocity (m/s)")
plt.show()
generate_plot_set(dfs[:8])
generate_plot_set(dfs[8:])
min_lat, max_lat, min_lon, max_lon = (4.5,4.785,-74,-74.25)
proj = ccrs.PlateCarree()
fig = plt.figure(figsize=(58,20))
main_ax = fig.add_subplot(1,1,1, projection=proj)
main_ax.set_extent([min_lon, max_lon, min_lat, max_lat], crs=proj)
main_ax.gridlines(draw_labels=True)
main_ax.coastlines()
request = cimgt.OSM()
main_ax.add_image(request,12)
main_ax.set_title("Bogota's wind behavior 2022")
coordinates_array = [df[2] for df in dfs]
def generate_plot_on_map(lon, lat, wd, ws, title):
wrax = inset_axes(
main_ax,
width=1,
height=1,
loc='center',
bbox_to_anchor=(lon,lat),
bbox_transform=main_ax.transData,
axes_class=WindroseAxes,
)
wrax.bar(wd,ws)
wrax.tick_params(labelleft=False, labelbottom=False)
wrax.set_title(title)
for df in dfs:
ws = df[1]["Velocity (m/s)"][df[1]["Velocity (m/s)"] != '----'][ df[1]["Direction (degrees)"] != "----"]
wd = df[1]["Direction (degrees)"][df[1]["Velocity (m/s)"] != '----'][ df[1]["Direction (degrees)"] != "----"]
lat = float(df[2][0])
lon = float(df[2][1]) * -1
title = df[0]
generate_plot_on_map(lon,lat,wd,ws, title)