Extract a specific time step from a netcdf file or opendap dataset using netCDF4 and plot without spatial coordinates.
Import requirements, taking care to put the "%matplotlib inline" before "import matplotlib" to avoid problems on jupyterhub servers
In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import netCDF4
import datetime as dt
Create a dictionary to hold short titles in keys, OPeNDAP Data URLS in values
In [2]:
models = {'GFS CONUS 80km':'http://thredds.ucar.edu/thredds/dodsC/grib/NCEP/GFS/CONUS_80km/Best',
'NAM CONUS 20km':'http://thredds.ucar.edu/thredds/dodsC/grib/NCEP/NAM/CONUS_20km/noaaport/Best'}
Pick a model
In [3]:
name = 'NAM CONUS 20km'
url = models[name]
In [4]:
nc = netCDF4.Dataset(url)
ncv = nc.variables
ncv.keys()
Out[4]:
In [5]:
# take a look at the "metadata" for the variable "u"
var_name = 'Temperature_height_above_ground'
var = ncv[var_name]
print var
In [6]:
var.shape
Out[6]:
In [7]:
# Desired time for snapshot
# ....right now (or some number of hours from now) ...
start = dt.datetime.utcnow() + dt.timedelta(hours=+2)
# ... or specific time (UTC)
#start = dt.datetime(2014,9,9,0,0,0) + dt.timedelta(hours=-1)
Identify the time coordinate from the "coordinates" attribute
In [8]:
var.coordinates
Out[8]:
We want time, not reftimes. Extract the index closest to the specified time
In [9]:
time_var = ncv['time']
itime = netCDF4.date2index(start,time_var,select='nearest')
Access data at specified time step and level
In [10]:
lev = 0
t = var[itime,lev,:,:]
t.shape
Out[10]:
Make a nice time stamp string
In [11]:
tm = netCDF4.num2date(time_var[itime],time_var.units)
daystr = tm.strftime('%Y-%b-%d %H:%M UTC')
Make a pcolormesh plot of the data
In [12]:
fig=plt.figure(figsize=(18,10))
plt.pcolormesh(t)
cbar = plt.colorbar()
plt.title('%s:%s, %s, Level %d' % (name, daystr, var_name, lev));