We are going to download NCEP reanalysis netCDF file for 2 m air temperature, get the data from it, convert them to $^\circ$C and plot with Basemap. More details in Russian can be found at http://koldunov.net/?p=714
import numpy
First we download the file with system comman wget (in order to run system command you have to put ! in front of it)
!wget ftp://ftp.cdc.noaa.gov/Datasets/ncep.reanalysis.dailyavgs/surface/air.sig995.2012.nc
--2012-12-13 15:05:38-- ftp://ftp.cdc.noaa.gov/Datasets/ncep.reanalysis.dailyavgs/surface/air.sig995.2012.nc => `air.sig995.2012.nc' Resolving ftp.cdc.noaa.gov... 140.172.38.117 Connecting to ftp.cdc.noaa.gov|140.172.38.117|:21... connected. Logging in as anonymous ... Logged in! ==> SYST ... done. ==> PWD ... done. ==> TYPE I ... done. ==> CWD /Datasets/ncep.reanalysis.dailyavgs/surface ... done. ==> SIZE air.sig995.2012.nc ... 7258672 ==> PASV ... done. ==> RETR air.sig995.2012.nc ... done. Length: 7258672 (6.9M) 100%[======================================>] 7,258,672 1.08M/s in 6.2s 2012-12-13 15:05:46 (1.13 MB/s) - `air.sig995.2012.nc' saved [7258672]
We will use netcdf module from scipy in order handle netCDF files
from scipy.io import netcdf
f = netcdf.netcdf_file('air.sig995.2012.nc', 'r')
We can look at some of the netCDF file properties (use TAB)
f.dimensions
{'lat': 73, 'lon': 144, 'time': None}
List variables
f.variables
{'air': <scipy.io.netcdf.netcdf_variable at 0x7fcedca36690>, 'lat': <scipy.io.netcdf.netcdf_variable at 0x7fcedca364d0>, 'lon': <scipy.io.netcdf.netcdf_variable at 0x7fcedca36550>, 'time': <scipy.io.netcdf.netcdf_variable at 0x7fcedca36610>}
Let's get air variable from the file
air = f.variables['air']
Look at some of it;s properties, like scale_factor and offset, that we need to get temperature in Kelvins
air.scale_factor
0.0099999998
air.add_offset
512.81
Now convert air temperature and prepare lat lon data for the plot.
airData = air[:]
airDataCels = ((airData*air.scale_factor)+air.add_offset)-273.15
lat = f.variables['lat'][:]
lon = f.variables['lon'][:]
lons, lats = numpy.meshgrid(lon,lat)
Show graphics in the notebook and import Basemap.
%pylab inline
from mpl_toolkits.basemap import Basemap
Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline]. For more information, type 'help(pylab)'.
Create map and prepare coordinates.
m = Basemap(llcrnrlon=0,llcrnrlat=40,urcrnrlon=190,urcrnrlat=85,projection='mill', resolution='l')
x, y = m(lons, lats)
Create plot
fig = plt.figure(figsize=(10,10))
dayNumber = 120
m.drawcoastlines(linewidth=1)
m.drawcountries(linewidth=0.5)
m.drawmapboundary
cs = m.contourf(x,y,airDataCels[dayNumber,:,:],20)
colorbar(orientation='horizontal')
<matplotlib.colorbar.Colorbar instance at 0x3bea518>