Learning Objectives
By the end of this lab, you should be able to
Find and download sea surface temperature (SST) data from the NASA MUR dataset
Describe the structure of a netCDF file
Plot a time series of SST from data in a netCDF file
Plot a map of SST and SST differences from a netCDF file
Motivation¶
In the previous labs, we’ve used QGIS to visualize and analyze satellite imagery. Here, we will start to transition to using Python which will allow us assess data much for efficiently than in GIS.
In this notebook, we will analyze sea surface temperature in the California Current where upwelling of cold water is a prevalent feature of the system.
Part 1: Obtaining SST Data from the MUR Product¶
To begin, we’ll access data from the Multi-scale Ultra-high Resolution (MUR) Sea Surface Temperature (SST) product. This product is supported by the NASA MEaSUREs program. mMore information can be found at this project on the product page at JPL’s Physical Oceanography DAAC.
Here, we will use a convenient tool from the Environmental Research Division’s Data Access Program (ERRDAP) to gather SST data in a given location over a specific time frame. For the MUR product, we can access the data HERE.
Navigate to the Data Access Form page and select a subset of data according to the following specifications:
time: 2008-02-01T09:00:00Z to 2008-07-31T09:00:00Zlatitude: 34°N to 41°Nlongitude-126°E to -118°Eanalysed_sst(checked)
From the dropdown of output file types, choose the .nc option.
On ERRDAP, your query should look like the following screenshot:

Figure 1:Screenshot of a data request from ERRDAP for the MURv4.1 data around Monterey Bay during spring 2008.
When the file has downloaded, save it into your Lab 5/Data folder, renaming it at MUR_SST.nc. Then, to facilitate the codes below, enter the path to your data folder into the following coding block:
# enter a path to your data folder here
data_dir = '../data/labs/lab05'Understanding the structure of a netCDF file¶
The netCDF file structure - short for Network Common Data Format - is an organizational structure for gridded data used widely in oceanography and other Earth sciences. To explore this file, open the file with the Panoply and take a look at the contents.
You should see the following fields:
analysed_sst
longitude
latitude
time

Figure 2:MUR in Panoply
Of course, these match up with all of the fields selected from the ERRDAP portal. Here, we see that the .nc file contains the full collection of complementary fields.
By clicking each field in the file list, you can see lots of metadata about each field and, importantly, its size. For example, you can see that the analysed_sst field has a shape of (182, 701, 801) corresponding to the dimensions of time, latitude, and longitude. You can visualize this as a 3D grid composed of 2D maps stacked through time:

Figure 3:The structure of the SST data in the MUR file
Part 2: Reading netCDF data in Python¶
Loading Packages in Python¶
Before reading in our data for plotting, we’ll need to load in a few packages. While Python has some built-in functionality, the code for specific tasks such as reading and plotting data are contained in packages. Here, we will import some packages used in this notebook.
import os
import numpy as np
import matplotlib.pyplot as plt
import netCDF4 as nc4
from datetime import datetime, timezoneTypically, we will import packages at the start of a notebook but they are put here near the code for this initial example.
Reading netCDF files¶
In Python, the netCDF package provides the functionality to read in nc files. For example, we can read the file into a Dataset object and print out the names of the variables as follows:
# read in the SST nc file
ds = nc4.Dataset(os.path.join(data_dir,'MUR_SST.nc'))
# print out the variable names
print(ds.variables.keys())dict_keys(['time', 'latitude', 'longitude', 'analysed_sst'])
Here, we see that the variables are the same as those above. We can read in the data from the file as follows:
time = ds.variables['time'][:]
longitude = ds.variables['longitude'][:]
latitude = ds.variables['latitude'][:]
sst = ds.variables['analysed_sst'][:,:,:]In the fields above, we can see that they are read in with their shape in mind - the 1D fields are appended with the [:] field while the 3D fields are appended with [:,:,:].
After reading in the fields, we’ll be sure to close the file:
ds.close()Part 3: Plotting a Time Series¶
Now that we’ve got our data read in, we’re ready for some plotting. Since the goal of this exploration is to examine the effect of upwelling on SST, let’s have a look at a time series of temperature in the middle of Monterey Bay at 36.75°N, 122.03°W.
In order to make a time series at this location, we’ll need to find its location in the grid. Here, we’ll find the closest indices in the longitude and latitude grids that correspond to the Monterey Bay location. Let’s define this here:
# define the location of Monterey Bay
monterey_bay_lon = -122.03
monterey_bay_lat = 36.75
# get the indices of these locations in the longitude and latitude grid
lon_index = np.argmin(np.abs(longitude-monterey_bay_lon))
lat_index = np.argmin(np.abs(latitude-monterey_bay_lat))
# print the indices
print('Longitude Index:',lon_index)
print('Latitude Index:',lat_index)
# print the longitude and latitude at these locations as a check
print('Model Longitude:',longitude[lon_index])
print('Model Latitude:',latitude[lat_index])Longitude Index: 397
Latitude Index: 275
Model Longitude: -122.03
Model Latitude: 36.75
With these indices in hand, we can sample the big 3D grid along the respective dimensions. Above, we saw that latitude corresponded to the dimension with index 1 and longitude corresponded to the dimension with index 2, so we’ll enter these here:
sst_monterey_bay = sst[:, lat_index, lon_index]The : in dimension 0 indicates that we will take all values along this dimension i.e. all times.
With this data in hand, we can make a plot of the time series:
# make a figure object
fig = plt.figure(figsize=(8,4))
# plot the time series
plt.plot(time, sst_monterey_bay, color='red')
# label the axes
plt.ylabel('Temperature (°C)')
plt.xlabel('Seconds since 1970-01-01')
plt.grid(linestyle='--', linewidth=0.5)
plt.title(f'MURv4.1 SST at {latitude[lat_index]:.2f}°N, {-longitude[lon_index]:.2f}°W')
# show the plot
plt.show()
In the plot above, we see that the time was labeled as “Seconds since 1970-01-01” and this was labeled in the metadata in the nc file. This type of time, called Unix time, is convenient for storing time in a continuous format but it’s not very helpful for human interpretation. Luckily, there is a convenient function that can be used to convert each Unix time to a date. Let’s do that here:
dates = [] # make an empty list to hold some dates
# loop through each Unix time
for t in time:
# convert the Unix time to a date
date = datetime.fromtimestamp(t, tz=timezone.utc)
# put the date in the dates list
dates.append(date)With our dates in hand, we can recreate the plot above:
# recreate the figure using the new dates list
fig = plt.figure(figsize=(8,4))
plt.plot(dates, sst_monterey_bay, color='red')
plt.ylabel('Temperature (°C)')
plt.grid(linestyle='--', linewidth=0.5)
plt.title(f'MURv4.1 SST at {latitude[lat_index]:.2f}°N, {-longitude[lon_index]:.2f}°W')
plt.show()
With our converted dates, we can see that the dates from February through July 2008 are now used for the x-axis in our new plot, consistent with the query from ERRDAP.
Part 4: Plotting a Map¶
In addition to plotting a time series, we can also plot a map of our data by “slicing” our data differently.
Plotting a Map on a Given Day¶
Let’s take a look at the first timestep, plotting the grid along all rows and columns of the data array:
# make figure
plt.figure(figsize=(7,7))
# plot a map using the pcolormesh command
C = plt.pcolormesh(sst[0,:,:],cmap='turbo',vmin=8,vmax=15)
# label the axes and show the plot
plt.colorbar(C, label='Temperature (°C)')
plt.xlabel('Grid Columns')
plt.ylabel('Grid Rows')
plt.show()
Similar to the plot above, we can also plot our figure with references to the longitude and latitude coordinates provided with the file. Let’s check this out for another timestep in the file:
# choose a timestep to plot
timestep = 81
# get the plot above using the longitude and latitude for the horizontal dimensions
plt.figure(figsize=(7,7))
C = plt.pcolormesh(longitude, latitude, sst[timestep,:,:],cmap='turbo',vmin=8,vmax=15)
plt.colorbar(C, label='Temperature (°C)')
plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.show()
🤔 Try it for yourself¶
In the plot above, change the timesteps and investigate maps at different times of the upwelling season. Where do you find evidence of upwelling in these SST estimates?
Plotting a Statistical Summary¶
Another component of this data we might be interested in is some statistical summary over a given time period. Here, let’s compute the mean and visualize this along the California coast.
# compute the mean over all time
mean_sst = np.mean(sst, axis=0)
# generate the plot above for the mean temperature
plt.figure(figsize=(7,7))
C = plt.pcolormesh(longitude, latitude, mean_sst, cmap='turbo',vmin=8,vmax=15)
plt.colorbar(C, label='Temperature (°C)')
plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.show()
Estimating Temporal Differences in Space¶
With the temperature fields at our fingertips, we can compute many different components of our system. Here, we’ll choose a simple calculation - the temperature differences between winter and summer.
# compute the differences between the beginning and end of the time series
difference = sst[-1,:,:]-sst[0,:,:]
# compute the maximum difference to be used for plotting
max_difference = np.max(np.abs(difference))
# make a map of the differences
plt.figure(figsize=(7,7))
C = plt.pcolormesh(longitude, latitude, difference,
cmap='seismic', vmin=-max_difference, vmax=max_difference)
plt.colorbar(C, label='Temperature (°C)')
plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.show()
As we would probably expect, the SST is warmer in summer than in winter - but we can estimate the magnitude of this effect with our SST data.
Another computation we could consider is the anomaly of temperature relative to some given time period. For example, we could ask: how does the temperature in spring compare to the mean over the winter-summer period? Let’s compute this here:
# choose a spring timestep
timestep = 90
# compute the anomaly
anomaly = sst[timestep,:,:]-np.mean(sst,axis=0)
# estimate the maximum anomaly for plotting
max_anomaly = np.max(np.abs(anomaly))
# make a map of the anomalies
plt.figure(figsize=(7,7))
C = plt.pcolormesh(longitude, latitude, anomaly,
cmap='seismic', vmin=-max_anomaly, vmax=max_anomaly)
plt.colorbar(C, label='Temperature (°C)')
plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.show()
Here, we can see that the waters in the spring are anomalously cold along the CA coastline in spring.
🤔 Try it for yourself!¶
In the example above, we looked at upwelling in the California Current system during spring of 2008 - only a small part of the decades-long global MUR SST product. Consider another process in the ocean that you expect to have a significant SST signal - think ENSO events, marine heat waves, ice sheet melt, etc. Then, using the steps above, find some data from the MURv4.2 product and use it to examine your process of interest. Be sure to visualize a time series, a map, and compute some statistics for your region of interest.