I have some NetCDF files from which I need to plot some variables. I use the following little code in order to plot the data I need:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
%matplotlib inline
import xarray as xr
os.chdir
fname = "/home/data.nc"
ds = xr.open_dataset(fname)
ds['Evap_obs'].plot()
plt.show()
Which work just fine and produce the following figure:
My problem now is that this plot is not really readable. Therefore I wish to smooth the data beforehand. For that I have this small function:
def mov_avg(x,window,min_count=None,axis=-1):
import bottleneck as bn
yy=np.ma.filled(np.ma.fix_invalid(x),np.nan)
yyF=np.ma.masked_all(yy.shape)
xtmp=bn.move_mean(yy,window,min_count=min_count,axis=axis)
wd1=(window-1)/2
ndim = len(yy.shape)
#print xtmp.shape,ndim,axis,window,wd1
if ndim ==1 :
#print wd1,-wd1,wd-1
yyF[wd1:-wd1]=np.ma.fix_invalid(xtmp[window-1:])
elif ndim == 2:
if axis==-1 or axis==1:
yyF[:,wd1:-wd1]=np.ma.fix_invalid(xtmp[:,window-1:])
elif axis==0:
yyF[wd1:-wd1,:]=np.ma.fix_invalid(xtmp[window-1:,:])
return yyF
Then when I wish to run this function on my data in order to smooth it as follow (using a window of 7 time steps to smooth):
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
%matplotlib inline
import xarray as xr
os.chdir
fname = "/home/data.nc"
ds = xr.open_dataset(fname)
obs = ds['Evap_obs']
obs = mov_avg(obs,7)
obs.plot()
It does not work and I got the following ValueError:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-18-6a8a2dd438c6> in <module>()
7 #dsloc = ds.sel(lon=230.5,lat=55.0,method='nearest')
8 obs = ds['Evap_obs']
----> 9 obs = mov_avg(obs,7)
10 obs.plot()
11 #ds['Evap_obs'].plot()
<ipython-input-11-c01b37a40c9a> in mov_avg(x, window, min_count, axis)
4 yy=np.ma.filled(np.ma.fix_invalid(x),np.nan)
5 yyF=np.ma.masked_all(yy.shape)
----> 6 xtmp=bn.move_mean(yy,window,min_count=min_count,axis=axis)
7 wd1=(window-1)/2
8 ndim = len(yy.shape)
ValueError: Moving window (=7) must between 1 and 1, inclusive
Does anyone knows how to smooth my data please?
Xarray includes a rolling method for these sorts of operations.
ds['Evap_obs'].rolling(time=7).mean().plot()
The xarray documentation includes a handful examples using this method: http://xarray.pydata.org/en/stable/computation.html#rolling-window-operations