my_filename = ('snc_NAM-44_CCCma-CanESM2_rcp85_r1i1p1_' 'CCCma-CanRCM4_r2_day_20410101-20451231.nc') # for this demo, we will see where it will be a white christmas in 2041. my_year, my_month, my_day = (2041, 12, 25) # calculations based on the above values: # to increase compatibility with Python 3.x: from __future__ import print_function import re # extracts variable name from beginning of filename: my_variable = my_filename[:my_filename.find('_')] print("my_variable = {}".format(my_variable)) first_year = int(re.search(('([12][90][0-9]{2})[01][0-9]' '[0-3][0-9]\-[12][90][0-9]{2}[01][0-9][0-3][0-9]\.nc'), my_filename).group(1)) print("first year in .nc file = {}".format(first_year)) month_lengths = (0,31,28,31,30,31,30,31,31,30,31,30) month_cumulative = [] counter = 0 for length in month_lengths: counter += length month_cumulative.append(counter) print("month_cumulative = {}".format(month_cumulative)) days_elapsed = (365 * (my_year - first_year) + month_cumulative[my_month - 1] + my_day) print(("{} days elapsed between Jan. 1, {} and specified date" "of {}-{}-{}").format(days_elapsed, first_year, my_year, my_month, my_day)) print("(leap days are not counted)") import netCDF4 # netCDF4 is not part of standard Python, # you may have to download and install it import numpy as np ncfile = netCDF4.Dataset(my_filename, 'r') # note that you'll have to download the file yourself # Let's have a look at this file. print("Attributes:") print(ncfile.ncattrs()) print("\nVariables:") print(ncfile.variables) nc_lons = np.array(ncfile.variables['lon']) nc_lats = np.array(ncfile.variables['lat']) nc_vars = np.array(ncfile.variables[my_variable]) print("Shape of nc_lons: {}".format(nc_lons.shape)) print("Shape of nc_lons: {}".format(nc_lats.shape)) print("Shape of nc_vars before specifying day: {}".\ format(nc_vars.shape)) nc_vars = nc_vars[days_elapsed] print("Shape of nc_vars after specifying day: {}".\ format(nc_vars.shape)) print("Starting day of file: {}".format(\ ncfile.variables['time'][0])) from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt %matplotlib inline fig = plt.figure(figsize=(8,8)) ax = fig.add_axes([0.1,0.1,0.8,0.8]) m = Basemap(width=6000000,height=4000000, resolution='l',projection='stere',\ lon_0=-93,lat_0=41, area_thresh=1000) m.drawlsmask(land_color='#00441b',ocean_color='#8be5e5', lakes=True) m.drawcoastlines() m.drawstates() m.drawcountries() parallels = np.arange(0., 90, 10.) m.drawparallels(parallels,labels=[1,0,0,0],fontsize=10) meridians = np.arange(180.,360.,10.) m.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10) x, y = m(nc_lons, nc_lats) clevs = range(1,101) cs = m.contourf(x,y,nc_vars,clevs,cmap=plt.cm.Greens_r) cbar = m.colorbar(cs,location='bottom',pad="5%") cbar.set_label('% snow cover') plt.title('Snow cover projected on Dec. 25, 2041') plt.show()