We will work together, running each cell in this Notebook step by step. Start by downloading the notebook (“Code” button above).
The data comes from Climate Reanalyzer, and the notebook downloads the most recent version every time you run it, so your graphs will include days that are not on this page. If the download doesn’t work (no internet, or the site is down), the notebook falls back to local copies of the data. Download these 2 csv files and put them in the same folder as the notebook:
import numpy as npimport matplotlib.pyplot as pltimport matplotlib as mplimport pandas as pdfrom pandas.plotting import register_matplotlib_convertersregister_matplotlib_converters() # datetime converter for a matplotlibimport seaborn as snssns.set_theme(style="ticks", font_scale=1.5)from statsmodels.tsa.seasonal import seasonal_decomposeimport matplotlib.dates as mdatesfrom matplotlib.dates import DateFormatterfrom datetime import datetime as dtimport timefrom statsmodels.tsa.stattools import adfuller# %matplotlib widget
download and plot data
import urllib.requestimport jsondef download_sst(region):"""download daily SST from Climate Reanalyzer, return a dataframe with an 'sst' column""" url =f"https://climatereanalyzer.org/clim/sst_daily/json_2clim/oisst2.1_{region}_sst_day.json"with urllib.request.urlopen(url, timeout=30) as response: data = json.load(response)# data is a list with one entry per year, each holding 366 daily values starting on Jan 1 pieces = []for entry in data:ifnot entry['name'].isdigit(): # skip "Preliminary", "1982-2010" climatology, etc.continue year =int(entry['name']) dates = pd.date_range(f"{year}-01-01", f"{year}-12-31", freq="D") # 365 or 366 days pieces.append(pd.Series(entry['data'][:len(dates)], index=dates, dtype=float)) sst = pd.concat(pieces).dropna() # days not measured (yet) are emptyreturn sst.rename_axis('date').to_frame('sst')try: df_world = download_sst("world2") df_north = download_sst("natlan")print("downloaded data up to", df_world.index[-1].date())exceptExceptionas error:print("download failed, reading local csv files instead:", error) df_world = pd.read_csv("sst_world.csv", index_col='date', parse_dates=True) df_north = pd.read_csv("sst_north.csv", index_col='date', parse_dates=True)fig, ax = plt.subplots(2, 1, figsize=(8,5), sharex=True)fig.subplots_adjust(hspace=0.1) # increase vertical space between panelsax[0].plot(df_world['sst'], color="black")ax[1].plot(df_north['sst'], color="black")fig.text(0.02, 0.5, 'sea surface temperature (°C)', va='center', rotation='vertical')ax[1].set(yticks=[20, 25])ax[0].text(0.5, 0.97, r"world average", transform=ax[0].transAxes, horizontalalignment='center', verticalalignment='top',)ax[1].text(0.5, 0.97, r"north atlantic", transform=ax[1].transAxes, horizontalalignment='center', verticalalignment='top',)pass
downloaded data up to 2026-11-07
36.2 trend
Take a rolling average of the data, using a 365-day window. Do it twice, one using '365D' and another using 365. What’s the difference?
If all you need is the average by years, then the most common way of writing the command would be in one single line:
df_world.groupby('year')['sst'].mean()
Let’s use groupby to plot world SST for all years, see how handy this method is. Also note that groupby return an object that can be iterated upon, as we do below.
fig, ax = plt.subplots()for year, data in gb_year_world: ax.plot(data['doy'], data['sst'], color="black")ax.set(xlabel="DOY", ylabel="SST");
With a few more lines of code we can make this look pretty.
Show the code
fig, ax = plt.subplots(2, 1, figsize=(8, 5), sharex=True)fig.subplots_adjust(hspace=0.1)# define the segment of the colormap to usestart, end =0.3, 0.8base_cmap = plt.cm.hot_rnew_colors = base_cmap(np.linspace(start, end, 256))new_cmap = mpl.colors.LinearSegmentedColormap.from_list("trunc({n},{a:.2f},{b:.2f})".format(n=base_cmap.name, a=start, b=end), new_colors)# defining the years for plottingyears = [year for year, _ in gb_year_world] + [year for year, _ in gb_year_north]min_year, max_year =min(years), max(years)# create a new normalization that matches the years to the new colormapnorm = mpl.colors.Normalize(vmin=min_year, vmax=max_year)# plotting the data with year-specific colors from the new colormapfor year, data in gb_year_world: ax[0].plot(data.index.day_of_year, data['sst'], color=new_cmap(norm(year)))for year, data in gb_year_north: ax[1].plot(data.index.day_of_year, data['sst'], color=new_cmap(norm(year)))# colorbar setupsm = mpl.cm.ScalarMappable(cmap=new_cmap, norm=norm)sm.set_array([])cbar = fig.colorbar(sm, ax=ax.ravel().tolist(), orientation='vertical', fraction=0.046, pad=0.04)ticks_years = [1981, 1991, 2001, 2011, max_year] # Specify years for colorbar tickscbar.set_ticks(ticks_years)cbar.set_ticklabels(ticks_years)# adding shared ylabel and xlabelfig.text(0.02, 0.5, 'SST temperature (°C)', va='center', rotation='vertical')ax[1].set_xlabel("day of year")ax[0].text(0.97, 0.97, r"world average", transform=ax[0].transAxes, horizontalalignment='right', verticalalignment='top',)ax[1].text(0.97, 0.97, r"north atlantic", transform=ax[1].transAxes, horizontalalignment='right', verticalalignment='top',);
Now let’s do the same for the detrended SST:
Show the code
fig, ax = plt.subplots(2, 1, figsize=(8, 5), sharex=True)fig.subplots_adjust(hspace=0.1)# define the segment of the colormap to usestart, end =0.3, 0.8base_cmap = plt.cm.hot_rnew_colors = base_cmap(np.linspace(start, end, 256))new_cmap = mpl.colors.LinearSegmentedColormap.from_list("trunc({n},{a:.2f},{b:.2f})".format(n=base_cmap.name, a=start, b=end), new_colors)# defining the years for plottingyears = [year for year, _ in gb_year_world] + [year for year, _ in gb_year_north]min_year, max_year =min(years), max(years)# create a new normalization that matches the years to the new colormapnorm = mpl.colors.Normalize(vmin=min_year, vmax=max_year)# plotting the data with year-specific colors from the new colormapfor year, data in gb_year_world: ax[0].plot(data.index.day_of_year, data['detrended'], color=new_cmap(norm(year)))for year, data in gb_year_north: ax[1].plot(data.index.day_of_year, data['detrended'], color=new_cmap(norm(year)))# colorbar setupsm = mpl.cm.ScalarMappable(cmap=new_cmap, norm=norm)sm.set_array([])cbar = fig.colorbar(sm, ax=ax.ravel().tolist(), orientation='vertical', fraction=0.046, pad=0.04)ticks_years = [1981, 1991, 2001, 2011, max_year] # Specify years for colorbar tickscbar.set_ticks(ticks_years)cbar.set_ticklabels(ticks_years)# adding shared ylabel and xlabelfig.text(0.02, 0.5, 'detrended SST temperature (°C)', va='center', rotation='vertical')ax[0].set(yticks=[-0.4,0,0.4])ax[1].set_xlabel("day of year")ax[0].text(0.97, 0.97, r"world average", transform=ax[0].transAxes, horizontalalignment='right', verticalalignment='top',)ax[1].text(0.97, 0.97, r"north atlantic", transform=ax[1].transAxes, horizontalalignment='right', verticalalignment='top',);
In order to determine what is the seasonal component, we need to calculate the average of the detrended data across all years. Again, groupby comes to rescue in a most elegant way:
Leap years introduce a small mismatch here: from March onwards, the same calendar date has a day of year one larger in leap years (March 1 is day 61 instead of 60), and day 366 exists only in leap years, so its average comes from just a handful of years; this is negligible for a slowly varying quantity like SST, but worth handling for data with sharp events tied to the calendar.
Let’s incorporate the averages in the same graphs we saw above:
Show the code
fig, ax = plt.subplots(2, 1, figsize=(8, 5), sharex=True)fig.subplots_adjust(hspace=0.1)# define the segment of the colormap to usestart, end =0.3, 0.8base_cmap = plt.cm.hot_rnew_colors = base_cmap(np.linspace(start, end, 256))new_cmap = mpl.colors.LinearSegmentedColormap.from_list("trunc({n},{a:.2f},{b:.2f})".format(n=base_cmap.name, a=start, b=end), new_colors)# defining the years for plottingyears = [year for year, _ in gb_year_world] + [year for year, _ in gb_year_north]min_year, max_year =min(years), max(years)# create a new normalization that matches the years to the new colormapnorm = mpl.colors.Normalize(vmin=min_year, vmax=max_year)# plotting the data with year-specific colors from the new colormapfor year, data in gb_year_world: ax[0].plot(data.index.day_of_year, data['detrended'], color=new_cmap(norm(year)))for year, data in gb_year_north: ax[1].plot(data.index.day_of_year, data['detrended'], color=new_cmap(norm(year)))ax[0].plot(avg_world, color='dodgerblue', lw=2, ls='--')ax[1].plot(avg_north, color='dodgerblue', lw=2, ls='--', label="mean across years")ax[1].legend(loc="upper left", frameon=False)# colorbar setupsm = mpl.cm.ScalarMappable(cmap=new_cmap, norm=norm)sm.set_array([])cbar = fig.colorbar(sm, ax=ax.ravel().tolist(), orientation='vertical', fraction=0.046, pad=0.04)ticks_years = [1981, 1991, 2001, 2011, max_year] # Specify years for colorbar tickscbar.set_ticks(ticks_years)cbar.set_ticklabels(ticks_years)# adding shared ylabel and xlabelfig.text(0.02, 0.5, 'detrended SST temperature (°C)', va='center', rotation='vertical')ax[0].set(yticks=[-0.4,0,0.4])ax[1].set_xlabel("day of year")ax[0].text(0.97, 0.97, r"world average", transform=ax[0].transAxes, horizontalalignment='right', verticalalignment='top',)ax[1].text(0.97, 0.97, r"north atlantic", transform=ax[1].transAxes, horizontalalignment='right', verticalalignment='top',);
How do we know we have properly decomposed our signal into trend, seasonal and residual? The residual should be stationary. Let’s check using the ADF test:
Show the code
alpha =0.05# significance levelfor name, df in [("World-average", df_world), ("North-Atlantic", df_north)]: result = adfuller(df['resid'].dropna()) p_value = result[1]print(f"{name} residual")print(f"ADF test p-value: {p_value:.2e}")if p_value < alpha:print(f"p < {alpha}: reject the null hypothesis, the residual is stationary\n")else:print(f"p >= {alpha}: cannot reject the null hypothesis, the residual may be non-stationary\n")
World-average residual
ADF test p-value: 4.57e-26
p < 0.05: reject the null hypothesis, the residual is stationary
North-Atlantic residual
ADF test p-value: 8.10e-24
p < 0.05: reject the null hypothesis, the residual is stationary
Both residuals are stationary according to ADF. But be careful about what this means. The ADF test looks for one specific kind of non-stationarity: a unit root, the kind of wandering behavior of a random walk. A regular annual cycle is not a unit root, so the ADF test also says “stationary” for a series that still has the whole seasonal cycle in it, and even for the raw data:
So the ADF test cannot tell us whether we managed to remove the seasonal component. Here is a check that can. If the annual cycle is still in the data, then today is similar to the same day one year ago, and the autocorrelation at a lag of one year is high. If we removed the annual cycle, the autocorrelation at that lag should be close to zero.
Our data is daily and has no gaps, so a lag of one year is a lag of 365 data points (leap years shift this by a quarter of a day, which doesn’t matter here). With hourly data, one year would be a lag of 8760 points; with monthly data, a lag of 12.
autocorrelation at a lag of one year
lag =365# one year, because the data is dailyac_table = {}for name, df in [("world average", df_world), ("north atlantic", df_north)]: ac_table[name] = {column: df[column].autocorr(lag)for column in ["detrended", "resid"]}pd.DataFrame(ac_table).round(2).rename_axis(f"autocorrelation at lag {lag}")
world average
north atlantic
autocorrelation at lag 365
detrended
0.87
1.00
resid
0.04
0.12
The detrended series, which still contains the annual cycle, is strongly correlated with itself one year later. In the residual, this correlation almost disappears: the seasonal component took the annual cycle with it.
36.6 seasonal decomposition
It is customary to plot each component in its own panel: