#!/usr/bin/env python
# coding: utf-8
#
Table of Contents
#
# # Compare weighted and unweighted mean temperature
#
#
# Author: [Mathias Hauser](https://github.com/mathause/)
#
#
# 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.
#
# In[ ]:
get_ipython().run_line_magic('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
# In[ ]:
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
# Plot the first timestep:
# In[ ]:
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()
# ### Creating weights
#
# For a rectangular grid the cosine of the latitude is proportional to the grid cell area.
# In[ ]:
weights = np.cos(np.deg2rad(air.lat))
weights.name = "weights"
weights
# ### Weighted mean
# In[ ]:
air_weighted = air.weighted(weights)
air_weighted
# In[ ]:
weighted_mean = air_weighted.mean(("lon", "lat"))
weighted_mean
# ### Plot: comparison with unweighted mean
#
# Note how the weighted mean temperature is higher than the unweighted.
# In[ ]:
weighted_mean.plot(label="weighted")
air.mean(("lon", "lat")).plot(label="unweighted")
plt.legend()