Last active
June 14, 2021 09:37
-
-
Save nmathewa/3ff7130e1c8e19b31b8644fda20219f6 to your computer and use it in GitHub Desktop.
scipy spatial regridding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from scipy.interpolate import griddata | |
import matplotlib.pyplot as plt | |
import numpy as np | |
import xarray as xr | |
file = "your_ncfile.nc" | |
dset = xr.open_dataset(file) | |
start_lat,end_lat = 10,15 # setting an start and end lon/lat points | |
start_lon,end_lon = 65,75 | |
""" Creating data arrays""" | |
n_dset = dset.sel(lat = slice(start_lat,end_lat),lon = slice(start_lon,end_lon)) #subsetting the netcdf using xarrray.sel | |
y = n_dset.lat.values # latitude values (1D array) change variable name according to what in dataset | |
x = n_dset.lon.values # latitude values (1D array) | |
vals = n_dset.rh2.values[0,0,:,:] # ndarray(here Iam taking lat/lon so indexed to 2D array) | |
xm,ym = np.meshgrid(x,y) # Creating complete set of lon (x), lat (y) points | |
xf = xm.flatten() # creating 1 D array of all lon points | |
yf = ym.flatten() # creating 1D array of all lat points | |
valsf = vals.flatten() # corresponding 1 D array of values | |
""" Creating an new lat lon grid on 0.1 degree resolution""" | |
xx = np.arange(start_lon+1,end_lon,0.2) # Creating new lon list | |
yy = np.arange(start_lat+1,end_lat,0.2) # creating new lat list | |
""" (x,y) are the initial (lon,lat) points then the new lat and lon points are reshaped accoridng to the axis""" | |
n_vals = griddata((xf,yf),valsf,(xx[None,:],yy[:,None]),method="linear") | |
"""simply visualising using plt.contourf""" | |
plt.contourf(x,y,vals) | |
#plt.contourf(xx,yy,n_vals) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment