Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
new
  • Loading branch information
mkbenneh committed Jun 16, 2024
1 parent f89d0d4 commit 70977e6
Show file tree
Hide file tree
Showing 40 changed files with 671,154 additions and 0 deletions.
23 changes: 23 additions & 0 deletions GMet_location_avgSI.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@

Navrongo -1.10 10.90 0.973
Wa -2.50 10.05 0.833
Tamale -0.85 9.43 0.838
Yendi -0.02 9.45 0.821
Bole -2.48 9.03 0.749
Kete_Krachi -0.17 7.80 0.818
Kumasi -1.60 6.72 0.600
Sefwi_Bekwai -2.33 6.20 0.572
Abetifi -0.75 6.67 0.609
Ho 0.48 6.67 0.595
Akatsi 0.80 6.12 0.765
Akuse 0.12 6.10 0.631
Koforidua -0.25 6.08 0.562
Akim_Oda -0.98 5.93 0.559
Ada 0.63 5.78 0.900
Tema 0.00 5.62 0.862
Accra -0.17 5.60 0.810
Saltpond -1.07 5.20 0.820
Takoradi -1.77 4.88 0.781
Axim -2.23 4.87 0.751
Damongo -1.826 9.091 0.990
Zuarungu -0.810 10.800 0.916
149 changes: 149 additions & 0 deletions Ghana Map plot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 27 17:32:37 2023
@author: micha
"""

###### Import required libraries #########
import cartopy.crs as ccrs
import cartopy.feature as cf
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
import pandas as pd
from pathlib import Path as Path
import seaborn as sns
import matplotlib
from matplotlib import pyplot as plt, dates
import numpy as np
import numpy as np
from matplotlib import gridspec
import os
import glob
import dataframe_image as dfi
import itertools
import matplotlib.patheffects as pe
import matplotlib.dates as mdates
# from matplotlib.dates import DateFormatter
from matplotlib.dates import YearLocator, DateFormatter
from matplotlib.ticker import (
MultipleLocator, FormatStrFormatter, AutoMinorLocator)

import warnings
warnings.filterwarnings('ignore')

################## Reading data for Stations ###############
dat = pd.read_fwf('C:/Users/micha/OneDrive/Desktop/Rainfall Analysis Publication/GMet_location_avgSI.txt',
names=['Station', 'Longitude', 'Latitude', 'St'])

##### Functoin to Draw a zebra border around maps ############

crs = ccrs.PlateCarree()


def add_zebra_frame(ax, lw=4, crs="pcarree", zorder=None):

ax.spines["geo"].set_visible(False)
left, right, bot, top = ax.get_extent()

# Alternate black and white line segments
bws = itertools.cycle(["k", "white"])

xticks = sorted([left, *ax.get_xticks(), right])
xticks = np.unique(np.array(xticks))
yticks = sorted([bot, *ax.get_yticks(), top])
yticks = np.unique(np.array(yticks))
for ticks, which in zip([xticks, yticks], ["lon", "lat"]):
for idx, (start, end) in enumerate(zip(ticks, ticks[1:])):
bw = next(bws)
if which == "lon":
xs = [[start, end], [start, end]]
ys = [[bot, bot], [top, top]]
else:
xs = [[left, left], [right, right]]
ys = [[start, end], [start, end]]

# For first and lastlines, used the "projecting" effect
capstyle = "butt" if idx not in (
0, len(ticks) - 2) else "projecting"
for (xx, yy) in zip(xs, ys):
ax.plot(
xx,
yy,
color=bw,
linewidth=lw,
clip_on=False,
transform=crs,
zorder=zorder,
solid_capstyle=capstyle,
# Add a black border to accentuate white segments
path_effects=[
pe.Stroke(linewidth=lw + 1, foreground="black"),
pe.Normal(),
],
)


##################### Plot for study Area ###########################
plt.figure(figsize=(10, 9)) # Specifying the size of the figure
# Specifying the type of geopatial plot
ax = plt.axes(projection=ccrs.PlateCarree())
ax.add_feature(cf.COASTLINE, alpha=0.8)
ax.add_feature(cf.BORDERS)
# ax.add_feature(cf.LAND)
ax.set_extent([-3.2, 0.8, 11.2, 7.7]) # setting the map boundaries
# ax.stock_img()
ax.add_feature(cf.STATES, alpha=0.1) # adding territorial boundaries

ax.plot(dat.Longitude,
dat.Latitude,
'ro', # plotting the longitudes and latitudes of the station
ms=7,
color='k') # ,
# for longitude, latitude, name in zip(dat.Longitude, dat.Latitude, dat.Station):
# if name in ['Damongo', 'Kete_Krachi', 'Wa', 'Bole', 'Tamale', 'Yendi']:
# ax.plot(dat.Longitude,
# dat.Latitude,
# 'ro', ##### plotting the longitudes and latitudes of the station
# ms=7,
# color = 'k')
# transform=ccrs.Geodetic(),label='Synoptic stations')

s_stations = np.asarray(dat.Station)

for longitude, latitude, name in zip(dat.Longitude, dat.Latitude, dat.Station):
if name in ['Damongo', 'Kete_Krachi', 'Wa', 'Bole', 'Tamale', 'Yendi']:
ax.text(longitude + .05, latitude + .15,
name,
va='center',
ha='center', transform=ccrs.Geodetic(), fontweight='bold', fontsize='15')
if name in ['Navrongo']:
ax.text(longitude - 0.4, latitude,
name,
va='center',
ha='center', transform=ccrs.Geodetic(), fontweight='bold', fontsize='15')
if name in ['Zuarungu']:
ax.text(longitude, latitude-0.1,
name,
va='center',
ha='center', transform=ccrs.Geodetic(), fontweight='bold', fontsize='15')
# else:
# ax.text(longitude + .05, latitude + .12,
# else:
# ax.text(longitude + .05, latitude + .12,
# name,
# va='center',
# ha='center', transform=ccrs.Geodetic(), fontweight='bold',fontsize = '10')


ax.set_xticks([-3, -2.5, -2.0, -1.5, -1.0, -0.5, 0, 0.5],
crs=ccrs.PlateCarree())
ax.set_yticks([11, 10.5, 10, 9.5, 9.0, 8.5, 8], crs=ccrs.PlateCarree())
lon_formatter = LongitudeFormatter(zero_direction_label=True)
lat_formatter = LatitudeFormatter()
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)
add_zebra_frame(ax, lw=4, crs=crs)
# plt.title('')

# #plt.savefig('Synoptic Stations.pdf',bbox_inches = 'tight')
# plt.savefig('Graphs/graphs/Study_Area.JPEG',bbox_inches = 'tight')
115 changes: 115 additions & 0 deletions analyis.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"import xarray as xr\n",
"import pandas as pd\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import cartopy as cp\n",
"import cartopy.crs as ccrs\n",
"import cartopy.feature as cf\n",
"from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter\n",
"from pathlib import Path\n",
"import warnings\n",
"warnings.filterwarnings('ignore')\n",
"from mpl_toolkits.basemap import Basemap"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"data = xr.open_dataset(\"./data/Ghana_chirps_dRR_1991_2020.nc\")\n",
"data = data.sel(latitude = slice(4,12), longitude = slice(-3,1.5)).precip\n",
"data = data.resample(time = 'y').sum('time')"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"location = pd.read_fwf(\"GMet_location_avgSI.txt\", names = ['Station','longitude','latitude','g'])\n",
"path_to_file=Path('data/')"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"import netCDF4 as nc\n",
"import numpy as np\n",
"import os\n",
"\n",
"# Function to read NetCDF file and save station data into individual text files\n",
"def separate_stations_to_txt(nc_file, output_dir):\n",
" # Open the NetCDF file\n",
" ds = nc.Dataset(\"./data/Ghana_chirps_dRR_1991_2020.nc\")\n",
" \n",
" # Assuming the structure of the dataset\n",
" # Dimensions: time, station\n",
" # Variables: time, station, rainfall\n",
" \n",
" # Extract the dimensions and variables\n",
" times = ds.variables['time'][:] # or appropriate time variable\n",
" stations = ds.variables['station'][:] # or appropriate station variable\n",
" rainfall = ds.variables['rainfall'][:] # or appropriate rainfall variable\n",
" \n",
" # Ensure output directory exists\n",
" if not os.path.exists(\"data\"):\n",
" os.makedirs(\"data\")\n",
" \n",
" # Loop through each station and save the data\n",
" for i, station in enumerate(stations):\n",
" # Create a filename for each station\n",
" station_id = str(station)\n",
" filename = os.path.join(\"data\", f'station_{station_id}.txt')\n",
" \n",
" # Open a text file for the station\n",
" with open(filename, 'w') as f:\n",
" f.write('Time\\tRainfall\\n')\n",
" for j, time in enumerate(times):\n",
" f.write(f'{time}\\t{rainfall[j, i]}\\n')\n",
" \n",
" # Close the dataset\n",
" ds.close()\n",
"\n",
"# Example usage\n",
"#nc_file = 'path/to/ghana_rainfall_data.nc'\n",
"#output_dir = 'output_directory'\n",
"#separate_stations_to_txt(nc_file, output_dir)\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Loading

0 comments on commit 70977e6

Please sign in to comment.