Uncomment the blocks of code with the installation lines (!pip install
, etc.). Remember the shortcut to uncomment/comment multiple lines is Command-/
on Macs or Control-/
on Windows.
Then run this cell to install the packages, import libraries, and give Colab access to Google Drive.
When prompted, click the link to give Colab access to Google Drive, copy the code, and paste back into here.
# # This code installs the netCDF4 module
# # Run this code once per session, then comment it out
# !pip install netcdf4
# # This code allows Cartopy to work with Google Colab
# # Run this code once per session, then comment it out
# !grep '^deb ' /etc/apt/sources.list | \
# sed 's/^deb /deb-src /g' | \
# tee /etc/apt/sources.list.d/deb-src.list
# !apt-get -qq update
# !apt-get -qq build-dep python3-cartopy
# !pip uninstall -y shapely
# !pip install shapely --no-binary shapely
# !pip install cartopy
# Import NumPy, xarray, Matplotlib, Cartopy (and related imports)
import numpy as np
import pandas as pd
import xarray as xr
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
# Give Colab access to Google Drive
from google.colab import drive
drive.mount('/content/drive')
Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
Next, update the filepath below. To find the correct filepath, you can click on the left sidebar (folder icon), navigate to the Class #13 data folder, click the "..." on the file, and select "Copy path."
Add back slashes (\
) in front of quotation marks in the filepath, as necessary.
# Filepath for Arctic sea ice concentration netCDF file
filepath = '/content/drive/MyDrive/OCEAN 215 - Autumn \'20/OCEAN 215 - Autumn \'20 - Course documents/Zoom class slides and notebooks/2020-11-17 - class #13 - data/nsidc_sea_ice_cdr_north.nc'
Run the code cell to load and display the netCDF file using xarray
.
Notice that there are three dimensions: lat (50-90°N), lon (-180°E to 180°E), and time (1978 to 2020). The data are monthly in time.
# Load netCDF file using xarray
data = xr.open_dataset(filepath)
# Display netCDF file
display(data)
array(['1978-11-01T00:00:00.000000000', '1978-12-01T00:00:00.000000000', '1979-01-01T00:00:00.000000000', ..., '2020-08-01T00:00:00.000000000', '2020-09-01T00:00:00.000000000', '2020-10-01T00:00:00.000000000'], dtype='datetime64[ns]')
array([-180. , -179.5, -179. , ..., 178.5, 179. , 179.5])
array([50. , 50.25, 50.5 , 50.75, 51. , 51.25, 51.5 , 51.75, 52. , 52.25, 52.5 , 52.75, 53. , 53.25, 53.5 , 53.75, 54. , 54.25, 54.5 , 54.75, 55. , 55.25, 55.5 , 55.75, 56. , 56.25, 56.5 , 56.75, 57. , 57.25, 57.5 , 57.75, 58. , 58.25, 58.5 , 58.75, 59. , 59.25, 59.5 , 59.75, 60. , 60.25, 60.5 , 60.75, 61. , 61.25, 61.5 , 61.75, 62. , 62.25, 62.5 , 62.75, 63. , 63.25, 63.5 , 63.75, 64. , 64.25, 64.5 , 64.75, 65. , 65.25, 65.5 , 65.75, 66. , 66.25, 66.5 , 66.75, 67. , 67.25, 67.5 , 67.75, 68. , 68.25, 68.5 , 68.75, 69. , 69.25, 69.5 , 69.75, 70. , 70.25, 70.5 , 70.75, 71. , 71.25, 71.5 , 71.75, 72. , 72.25, 72.5 , 72.75, 73. , 73.25, 73.5 , 73.75, 74. , 74.25, 74.5 , 74.75, 75. , 75.25, 75.5 , 75.75, 76. , 76.25, 76.5 , 76.75, 77. , 77.25, 77.5 , 77.75, 78. , 78.25, 78.5 , 78.75, 79. , 79.25, 79.5 , 79.75, 80. , 80.25, 80.5 , 80.75, 81. , 81.25, 81.5 , 81.75, 82. , 82.25, 82.5 , 82.75, 83. , 83.25, 83.5 , 83.75, 84. , 84.25, 84.5 , 84.75, 85. , 85.25, 85.5 , 85.75, 86. , 86.25, 86.5 , 86.75, 87. , 87.25, 87.5 , 87.75, 88. , 88.25, 88.5 , 88.75, 89. , 89.25, 89.5 , 89.75])
array([11, 12, 1, ..., 8, 9, 10])
[57945600 values with dtype=float64]
First, assign roles:
Timekeeper: keep things moving
Coder: share your screen and write the code based on input from everyone else
Reporter: before the end of the session, ask the Coder to paste their code into the chat, then copy and paste it into this Google Document
# 1. Write one line of code to select the Chukchi Sea region from your "data" variable.
# Save this as a new variable called "chukchi".
chukchi = data.sel(lat=slice(70,75),lon=slice(-180,-140))
# 2. Write one line of code to calculate the mean of "chukchi" over the latitude and longitude dimensions.
# Save this as a new variable called "chukchi_time_series"
chukchi_time_series = chukchi.mean(dim=['lat','lon'])
# 3. Set up a figure with a width of 12 and height of 6.
plt.figure(figsize=(12,6))
# 4. Plot "chukchi_time_series" (time vs. sea ice concentration) using a black line.
# Make sure sea ice concentration has units of 0% to 100%, not 0.0 to 1.0.
plt.plot(chukchi_time_series['time'], 100 * chukchi_time_series['sea_ice_conc'],c='k')
# 5. Label your axes, add a title, and add a grid.
plt.xlabel('Time')
plt.ylabel('Sea ice concentration (%)')
plt.title('Chukchi Sea sea ice concentration')
plt.grid()
# 6. If you have time, answer the following questions:
# a. What long-term trend do you see?
# b. In 1980, was there sea ice in the Chukchi Sea year-round? How do you know?
# c. In 2019, was there sea ice in the Chukchi Sea year-round? How do you know?
# d. In 2019, was there a time of the year where the entire Chukchi Sea was covered by sea ice?
/usr/local/lib/python3.6/dist-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice return np.nanmean(a, axis=axis, dtype=dtype)
First, assign roles:
Timekeeper: keep things moving
Coder: share your screen and write the code based on input from everyone else
Reporter: before the end of the session, ask the Coder to paste their code into the chat, then copy and paste it into this Google Document
# 1. Write one line of code to select the Chukchi Sea region from your "data" variable.
# Save this as a new variable called "chukchi".
chukchi = data.sel(lat=slice(70,75),lon=slice(-180,-140))
# 2. Write two lines of code to select the sea ice concentration data from "chukchi"
# from September 1980 and September 2019.
#
# Save these as new variables called "chukchi_1980" and "chukchi_2019".
chukchi_1980 = chukchi['sea_ice_conc'].sel(time='1980-09')
chukchi_2019 = chukchi['sea_ice_conc'].sel(time='2019-09')
# or: chukchi_2019 = chukchi.sel(time=slice(datetime(2019,9,1),datetime(2019,9,30)))
# 3. Those two variables are 2-D and in xarray format. Write two lines of code
# to convert those two variables into flattened (1-D) NumPy arrays.
chukchi_1980 = chukchi_1980.values.flatten()
chukchi_2019 = chukchi_2019.values.flatten()
# 4. To speed things up, I've set up a figure with two subplots (1 row, 2 columns).
fig, (ax0,ax1) = plt.subplots(nrows=1,ncols=2,figsize=(16,5))
# 5. On the left subplot, create a histogram of the September 1980 sea ice data.
# Make sure sea ice concentration has units of 0% to 100%, not 0.0 to 1.0.
# Set the color to 'navy' and the transparency to 80%.
ax0.hist(100*chukchi_1980,color='navy')
# 6. On the right subplot, create a histogram of the September 2019 sea ice data.
# Make sure sea ice concentration has units of 0% to 100%, not 0.0 to 1.0.
# Set the color to 'firebrick' and the transparency to 80%.
ax1.hist(100*chukchi_2019,color='firebrick')
# 7. Add a grid to both subplot axes. Add axis labels.
ax0.grid()
ax1.grid()
ax0.set_xlabel('Sea ice concentration (%)')
ax1.set_xlabel('Sea ice concentration (%)')
ax0.set_ylabel('Grid cell count')
# 8. If you have time, answer the following questions:
# a. In 1980, were there areas of the Chukchi Sea with full sea ice cover?
# b. In 2019, were there areas of the Chukchi Sea with full sea ice cover?
# c. What other differences do you see between September 1980 and September 2019?
/usr/local/lib/python3.6/dist-packages/numpy/lib/histograms.py:839: RuntimeWarning: invalid value encountered in greater_equal keep = (tmp_a >= first_edge) /usr/local/lib/python3.6/dist-packages/numpy/lib/histograms.py:840: RuntimeWarning: invalid value encountered in less_equal keep &= (tmp_a <= last_edge)
Text(0, 0.5, 'Grid cell count')
First, assign roles:
Timekeeper: keep things moving
Coder: share your screen and write the code based on input from everyone else
Reporter: before the end of the session, ask the Coder to paste their code into the chat, then copy and paste it into this Google Document
# 1. Write one lines of code to select the sea ice concentration data from September 1980.
# Save this as a new variable called "sic_1980".
sic_1980 = data['sea_ice_conc'].sel(time='1980-09')
# 2. This variable will still be 3-D, but the time dimension has just a single time.
# To get rid of the unneeded time dimension and make the data truly 2-D,
# use this code to "squeeze" out the time dimension.
sic_1980 = sic_1980.squeeze()
# 3. Use this code to set up a blank figure and set the axes to use Cartopy's Arctic map projection,
# AKA a "northern polar stereographic" projection with a central longitude of 0°.
fig = plt.figure(figsize=(9,9))
ax = plt.axes(projection=ccrs.NorthPolarStereo(central_longitude=0))
# 4. Set the map extent to -180°E to 180°E in longitude, 65-90°N in latitude.
ax.set_extent([-180, 180, 65, 90], crs=ccrs.PlateCarree())
# 5. Plot the sea ice data (your variable "sic_1980") using pcolormesh().
# - Recall that pcolormesh() takes the X values, Y values, and Z values as arguments.
# - Don't forget to specify the 'transform' argument.
# - Make sure sea ice concentration has units of 0% to 100%, not 0.0 to 1.0.
# - Specify the colormap as 'Blues'.
pcm = ax.pcolormesh(sic_1980['lon'],sic_1980['lat'],100*sic_1980.values,
transform=ccrs.PlateCarree(),cmap='Blues')
# 6. Add a colorbar.
# Then label the colorbar "Sea ice concentration (%)".
cbar = plt.colorbar(pcm,ax=ax,shrink=0.8)
cbar.set_label('Sea ice concentration (%)')
# 7. Try to add some formatting to the map. If you get stuck on any of these, just move on a different part.
# - Add coastlines with a resolution of 110 m and line width of 0.5 to the map.
# - Add gridlines to the map with a transparency of 50%.
# - Add the land feature to the map with the color 'papayawhip'.
cs = ax.coastlines(resolution='110m',linewidth=0.5)
gl = ax.gridlines(crs=ccrs.PlateCarree(),draw_labels=True,alpha=0.5)
ax.add_feature(cfeature.LAND, color='papayawhip')
<cartopy.mpl.feature_artist.FeatureArtist at 0x7f6f8449b080>
First, assign roles:
Timekeeper: keep things moving
Coder: share your screen and write the code based on input from everyone else
Reporter: before the end of the session, ask the Coder to paste their code into the chat, then copy and paste it into this Google Document
# 1. Write one lines of code to select the sea ice concentration data from September 2019.
# Save this as a new variable called "sic_2019".
sic_2019 = data['sea_ice_conc'].sel(time='2019-09')
# 2. This variable will still be 3-D, but the time dimension has just a single time.
# To get rid of the unneeded time dimension and make the data truly 2-D,
# use this code to "squeeze" out the time dimension.
sic_2019 = sic_2019.squeeze()
# 3. Use this code to set up a blank figure and set the axes to use Cartopy's Arctic map projection,
# AKA a "northern polar stereographic" projection with a central longitude of 0°.
fig = plt.figure(figsize=(9,9))
ax = plt.axes(projection=ccrs.NorthPolarStereo(central_longitude=0))
# 4. Set the map extent to -180°E to 180°E in longitude, 65-90°N in latitude.
ax.set_extent([-180, 180, 65, 90], crs=ccrs.PlateCarree())
# 5. Plot the sea ice data (your variable "sic_2019") using pcolormesh().
# - Recall that pcolormesh() takes the X values, Y values, and Z values as arguments.
# - Don't forget to specify the 'transform' argument.
# - Make sure sea ice concentration has units of 0% to 100%, not 0.0 to 1.0.
# - Specify the colormap as 'Blues'.
pcm = ax.pcolormesh(sic_2019['lon'],sic_2019['lat'],100*sic_2019.values,
transform=ccrs.PlateCarree(),cmap='Blues')
# 6. Add a colorbar.
# Then label the colorbar "Sea ice concentration (%)".
cbar = plt.colorbar(pcm,ax=ax,shrink=0.8)
cbar.set_label('Sea ice concentration (%)')
# 7. Try to add some formatting to the map. If you get stuck on any of these, just move on a different part.
# - Add coastlines with a resolution of 110 m and line width of 0.5 to the map.
# - Add gridlines to the map with a transparency of 50%.
# - Add the land feature to the map with the color 'papayawhip'.
cs = ax.coastlines(resolution='110m',linewidth=0.5)
gl = ax.gridlines(crs=ccrs.PlateCarree(),draw_labels=True,alpha=0.5)
ax.add_feature(cfeature.LAND, color='papayawhip')
<cartopy.mpl.feature_artist.FeatureArtist at 0x7f6f843e2eb8>