Create month-long plot of Sea Surface Temperature (SST) using OPeNDAP service from CDIP THREDDS Server.
Enter CDIP Buoy Station Number and start/end dates for plot
stn = '029'
startdate = "01/01/2014" # MM/DD/YYYY
enddate = "01/31/2014"
Libraries are Python packages that contain a subset of specific functions
import matplotlib.pyplot as plt
import netCDF4
import numpy as np
import datetime
import time
import calendar
CDIP buoy data are available in two subsets:
Archived and Realtime NetCDF files must be called using separate URLs:
# Comment out the URL that you are not using
# CDIP Archived Dataset URL
data_url = 'http://thredds.cdip.ucsd.edu/thredds/dodsC/cdip/archive/' + stn + 'p1/' + stn + 'p1_historic.nc'
# CDIP Realtime Dataset URL
# data_url = 'http://thredds.cdip.ucsd.edu/thredds/dodsC/cdip/realtime/' + stn + 'p1_rt.nc'
nc = netCDF4.Dataset(data_url)
Assign variable names to the relevant variables from NetCDF file
ncTime = nc.variables['sstTime'][:]
timeall = [datetime.datetime.fromtimestamp(t) for t in ncTime] # Convert ncTime variable to datetime stamps
sst = nc.variables['sstSeaSurfaceTemperature'][:] # Make a numpy array of SST variable
# Create variables for Buoy Name and Month Name, to use in plot title
buoyname = nc.variables['metaStationName'][:]
buoytitle = " ".join(buoyname[:-40])
month_name = calendar.month_name[int(startdate[0:2])]
year_num = (startdate[6:10])
# Find nearest value in numpy array
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return array[idx]
NetCDF stores time variables as UNIX dates (values are in seconds since 01-01-1970 00:00:00). The below functions allow us to convert between human-format timestamps (e.g. 'MM/DD/YYYY') and UNIX timestamps.
# Convert to unix timestamp
def getUnixTimestamp(humanTime,dateFormat):
unixTimestamp = int(time.mktime(datetime.datetime.strptime(humanTime, dateFormat).timetuple()))
return unixTimestamp
Find the UNIX values that correspond to Start and End dates entered above
unixstart = getUnixTimestamp(startdate,"%m/%d/%Y")
neareststart = find_nearest(ncTime, unixstart) # Find the closest unix timestamp
nearIndex = numpy.where(ncTime==neareststart)[0][0] # Grab the index number of found date
unixend = getUnixTimestamp(enddate,"%m/%d/%Y")
future = find_nearest(ncTime, unixend) # Find the closest unix timestamp
futureIndex = numpy.where(ncTime==future)[0][0] # Grab the index number of found date
Create month-long plot of SST data
# Create figure and specify figure size
fig = plt.figure(figsize=(15,10))
psst = fig.add_subplot(111)
psst.plot(timeall[nearIndex:futureIndex],sst[nearIndex:futureIndex],'b')
# Set Titles
plt.suptitle(buoytitle, fontsize=30, y=0.99)
title(month_name + " " + year_num, fontsize=20, y=1)
# Set tick parameters
psst.tick_params(axis='y', which='major', labelsize=12, right='off')
psst.tick_params(axis='x', which='major', labelsize=12, top='off')
# Set x-axis tick interval to every 5 days
days = DayLocator(interval=5)
daysFmt = DateFormatter('%d')
plt.gca().xaxis.set_major_locator(days)
plt.gca().xaxis.set_major_formatter(daysFmt)
# Make a second y-axis, to show values in both Degrees C and Degrees F
psst2 = psst.twinx()
# Set y-axis limits for each plot
psst.set_ylim(5,25)
psst2.set_ylim((5*1.8+32),(25*1.8+32))
# Label each y-axis
psst.set_ylabel('SEA TEMPERATURE (Deg C)', fontsize=18)
psst2.set_ylabel('SEA TEMPERATURE (Deg F)', fontsize=18)
# Label x-axis
psst.set_xlabel('Day', fontsize=18)
# Plot dashed gridlines
psst.grid(b=True, which='major', color='b', linestyle='--')