You can run this notebook in a live session Binder or view it on Github.

Table of Contents

  • 1  Compare weighted and unweighted mean temperature

      • 1.0.1  Data

      • 1.0.2  Creating weights

      • 1.0.3  Weighted mean

      • 1.0.4  Plot: comparison with unweighted mean

Compare weighted and unweighted mean temperature

Author: Mathias Hauser

We use the air_temperature example dataset to calculate the area-weighted temperature over its domain. This dataset has a regular latitude/ longitude grid, thus the grid cell area decreases towards the pole. For this grid we can use the cosine of the latitude as proxy for the grid cell area.

[1]:
%matplotlib inline

import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import numpy as np

import xarray as xr

Data

Load the data, convert to celsius, and resample to daily values

[2]:
ds = xr.tutorial.load_dataset("air_temperature")

# to celsius
air = ds.air - 273.15

# resample from 6-hourly to daily values
air = air.resample(time="D").mean()

air
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
File /build/python-xarray-x7F8vs/python-xarray-2022.10.0/xarray/tutorial.py:131, in open_dataset(name, cache, cache_dir, engine, **kws)
    130 try:
--> 131     import pooch
    132 except ImportError as e:

ModuleNotFoundError: No module named 'pooch'

The above exception was the direct cause of the following exception:

ImportError                               Traceback (most recent call last)
Cell In [2], line 1
----> 1 ds = xr.tutorial.load_dataset("air_temperature")
      3 # to celsius
      4 air = ds.air - 273.15

File /build/python-xarray-x7F8vs/python-xarray-2022.10.0/xarray/tutorial.py:270, in load_dataset(*args, **kwargs)
    233 def load_dataset(*args, **kwargs) -> Dataset:
    234     """
    235     Open, load into memory, and close a dataset from the online repository
    236     (requires internet).
   (...)
    268     load_dataset
    269     """
--> 270     with open_dataset(*args, **kwargs) as ds:
    271         return ds.load()

File /build/python-xarray-x7F8vs/python-xarray-2022.10.0/xarray/tutorial.py:133, in open_dataset(name, cache, cache_dir, engine, **kws)
    131     import pooch
    132 except ImportError as e:
--> 133     raise ImportError(
    134         "tutorial.open_dataset depends on pooch to download and manage datasets."
    135         " To proceed please install pooch."
    136     ) from e
    138 logger = pooch.get_logger()
    139 logger.setLevel("WARNING")

ImportError: tutorial.open_dataset depends on pooch to download and manage datasets. To proceed please install pooch.

Plot the first timestep:

[3]:
projection = ccrs.LambertConformal(central_longitude=-95, central_latitude=45)

f, ax = plt.subplots(subplot_kw=dict(projection=projection))

air.isel(time=0).plot(transform=ccrs.PlateCarree(), cbar_kwargs=dict(shrink=0.7))
ax.coastlines()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In [3], line 5
      1 projection = ccrs.LambertConformal(central_longitude=-95, central_latitude=45)
      3 f, ax = plt.subplots(subplot_kw=dict(projection=projection))
----> 5 air.isel(time=0).plot(transform=ccrs.PlateCarree(), cbar_kwargs=dict(shrink=0.7))
      6 ax.coastlines()

NameError: name 'air' is not defined
../_images/examples_area_weighted_temperature_6_1.png

Creating weights

For a rectangular grid the cosine of the latitude is proportional to the grid cell area.

[4]:
weights = np.cos(np.deg2rad(air.lat))
weights.name = "weights"
weights
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In [4], line 1
----> 1 weights = np.cos(np.deg2rad(air.lat))
      2 weights.name = "weights"
      3 weights

NameError: name 'air' is not defined

Weighted mean

[5]:
air_weighted = air.weighted(weights)
air_weighted
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In [5], line 1
----> 1 air_weighted = air.weighted(weights)
      2 air_weighted

NameError: name 'air' is not defined
[6]:
weighted_mean = air_weighted.mean(("lon", "lat"))
weighted_mean
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In [6], line 1
----> 1 weighted_mean = air_weighted.mean(("lon", "lat"))
      2 weighted_mean

NameError: name 'air_weighted' is not defined

Plot: comparison with unweighted mean

Note how the weighted mean temperature is higher than the unweighted.

[7]:
weighted_mean.plot(label="weighted")
air.mean(("lon", "lat")).plot(label="unweighted")

plt.legend()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In [7], line 1
----> 1 weighted_mean.plot(label="weighted")
      2 air.mean(("lon", "lat")).plot(label="unweighted")
      4 plt.legend()

NameError: name 'weighted_mean' is not defined