Plot Time Series of CAMS Data
Contents
Plot Time Series of CAMS Data¶
This tutorial demonstrates how to plot time series of data from the Copernicus Atmosphere Monitoring Service (CAMS). The example focusses on CO2, and we will visualise the “Keeling Curve” of global average increases in CO2 from the last decades.
Run the tutorial via free cloud platforms: |
---|
Install and import packages¶
!pip install cdsapi
Requirement already satisfied: cdsapi in c:\users\cxcs\anaconda3\lib\site-packages (0.5.1)
Requirement already satisfied: tqdm in c:\users\cxcs\anaconda3\lib\site-packages (from cdsapi) (4.62.3)
Requirement already satisfied: requests>=2.5.0 in c:\users\cxcs\anaconda3\lib\site-packages (from cdsapi) (2.26.0)
Requirement already satisfied: charset-normalizer~=2.0.0 in c:\users\cxcs\anaconda3\lib\site-packages (from requests>=2.5.0->cdsapi) (2.0.4)
Requirement already satisfied: idna<4,>=2.5 in c:\users\cxcs\anaconda3\lib\site-packages (from requests>=2.5.0->cdsapi) (3.2)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\cxcs\anaconda3\lib\site-packages (from requests>=2.5.0->cdsapi) (2021.10.8)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\users\cxcs\anaconda3\lib\site-packages (from requests>=2.5.0->cdsapi) (1.26.7)
Requirement already satisfied: colorama in c:\users\cxcs\anaconda3\lib\site-packages (from tqdm->cdsapi) (0.4.4)
# CDS API
import cdsapi
# Libraries for reading and working with multidimensional arrays
import numpy as np
import xarray as xr
# Library for plotting and visualising data
%matplotlib inline
import matplotlib.pyplot as plt
# Disable warnings for data download via API
import urllib3
urllib3.disable_warnings()
Data access and preprocessing¶
Download CAMS global reanalysis data¶
Copy your API key into the code cell below, replacing #######
with your key. (Remember, to access data from the ADS, you will need first to register/login https://ads.atmosphere.copernicus.eu and obtain an API key from https://ads.atmosphere.copernicus.eu/api-how-to.)
URL = 'https://ads.atmosphere.copernicus.eu/api/v2'
# Replace the hashtags with your key:
KEY = '##########################################'
Here we specify a data directory into which we will download our data and all output files that we will generate:
DATADIR = './'
For this tutorial, we will use CAMS global greenhouse gas reanalysis (EGG4) data, monthly averaged fields version. The code below shows the subset characteristics that we will extract from this dataset as an API request.
Note
Before running this code, ensure that you have accepted the terms and conditions. This is something you only need to do once for each CAMS dataset. You will find the option to do this by selecting the dataset in the ADS, then scrolling to the end of the Download data tab.
c = cdsapi.Client(url=URL, key=KEY)
c.retrieve(
'cams-global-ghg-reanalysis-egg4-monthly',
{
'variable': 'co2_column_mean_molar_fraction',
'year': [
'2003', '2004', '2005',
'2006', '2007', '2008',
'2009', '2010', '2011',
'2012', '2013', '2014',
'2015', '2016', '2017',
'2018', '2019', '2020',
],
'month': [
'01', '02', '03',
'04', '05', '06',
'07', '08', '09',
'10', '11', '12',
],
'product_type': 'monthly_mean',
'format': 'netcdf',
},
f'{DATADIR}/CO2_2003-2020.nc')
2022-07-30 16:13:36,334 INFO Welcome to the CDS
2022-07-30 16:13:36,344 INFO Sending request to https://ads.atmosphere.copernicus.eu/api/v2/resources/cams-global-reanalysis-eac4-monthly
2022-07-30 16:13:36,441 INFO Request is queued
2022-07-30 16:17:54,959 INFO Request is completed
2022-07-30 16:17:54,969 INFO Downloading https://download-0005-ads-clone.copernicus-climate.eu/cache-compute-0005/cache/data1/adaptor.mars.internal-1659194176.4934468-21743-12-595d03f1-83d2-4740-ba73-9430b38e6f93.nc to ./DATA/CO_NHemis_Aug2003-2021.nc (52.6M)
2022-07-30 16:18:03,412 INFO Download rate 6.2M/s
Result(content_length=55179884,content_type=application/x-netcdf,location=https://download-0005-ads-clone.copernicus-climate.eu/cache-compute-0005/cache/data1/adaptor.mars.internal-1659194176.4934468-21743-12-595d03f1-83d2-4740-ba73-9430b38e6f93.nc)
Read and inspect data¶
Read the data into an Xarray dataset:
fn = f'{DATADIR}/CO2_2003-2020.nc'
ds = xr.open_dataset(fn)
ds
<xarray.Dataset> Dimensions: (longitude: 480, latitude: 241, time: 216) Coordinates: * longitude (longitude) float32 0.0 0.75 1.5 2.25 ... 357.0 357.8 358.5 359.2 * latitude (latitude) float32 90.0 89.25 88.5 87.75 ... -88.5 -89.25 -90.0 * time (time) datetime64[ns] 2003-01-01 2003-02-01 ... 2020-12-01 Data variables: tcco2 (time, latitude, longitude) float32 ... Attributes: Conventions: CF-1.6 history: 2022-08-15 14:54:50 GMT by grib_to_netcdf-2.25.1: /opt/ecmw...
Spatial aggregation¶
We would like to visualise this data not in maps, but as a one dimensional time series of global average values. To do this, we will first need to aggregate the data spatially to create a single global average at each time step.
In order to aggregate over the latitudinal dimension, we need to take into account the variation in area as a function of latitude. We will do this using the cosine of the latitude as a proxy:
weights = np.cos(np.deg2rad(ds.latitude))
weights.name = "weights"
ds_weighted = ds.weighted(weights)
Now we can average over both the longitude and latitude dimensions:
# Average (mean) over the latitudinal axis
co_ds = ds_weighted.mean(dim=["latitude", "longitude"])
Create xarray Data Array from Dataset object¶
Here we create an Xarray Data Array object containing the CO2 variable.
co = co_ds['tcco2']
Plot time series of global CO¶
Now we can plot the time series of globally averaged CO2 data over time.
Simple plot using xarray¶
The easiest way to plot data in an Xarray Data Array object is to use Xarray’s own plotting functionality.
co.plot()
[<matplotlib.lines.Line2D at 0x1eb60b4a3a0>]
In this plot of monthly averaged CO2 we can see the seasonal variation and yearly increase in global CO2 over the last decades.
Customised plot using matplotlib¶
In this example we use the Matplotlib library to create the same plot as above, with a few customisations
fig, ax = plt.subplots(1, 1, figsize = (9, 6)) # Set size and dimensions of figure
ax.set_title('CO2 global time series', fontsize=12) # Set figure title
ax.set_ylabel('CO2 column-mean molar fraction (ppm)') # Set Y axis title
ax.set_xlabel('Year') # Set X axis title
ax.grid(linewidth=1, color='gray', alpha=0.5, linestyle='--') # Include gridlines
ax.plot(co.time, co) # Plot the data
fig.savefig(f'{DATADIR}/CAMS_CO2_reanalysis.png') # Save the figure