%matplotlib inline
import numpy as np
import pandas as pd
import xarray as xr
import cartopy.crs as ccrs
from matplotlib import pyplot as plt

print("numpy version  : ", np.__version__)
print("pandas version : ", pd.__version__)
print("xarray version   : ", xr.version.version)

"""
Explanation: Working with Multidimensional Coordinates
Author: Ryan Abernathey
Many datasets have physical coordinates which differ from their logical coordinates. Xarray provides several ways to plot and analyze such datasets.
End of explanation
"""


ds = xr.tutorial.load_dataset('rasm')
ds

"""
Explanation: As an example, consider this dataset from the xarray-data repository.
End of explanation
"""


print(ds.xc.attrs)
print(ds.yc.attrs)

"""
Explanation: In this example, the logical coordinates are x and y, while the physical coordinates are xc and yc, which represent the latitudes and longitude of the data.
End of explanation
"""


fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(14,4))
ds.xc.plot(ax=ax1)
ds.yc.plot(ax=ax2)

"""
Explanation: Plotting
Let's examine these coordinate variables by plotting them.
End of explanation
"""


ds.Tair[0].plot()

"""
Explanation: Note that the variables xc (longitude) and yc (latitude) are two-dimensional scalar fields.
If we try to plot the data variable Tair, by default we get the logical coordinates.
End of explanation
"""


plt.figure(figsize=(14,6))
ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_global()
ds.Tair[0].plot.pcolormesh(ax=ax, transform=ccrs.PlateCarree(), x='xc', y='yc', add_colorbar=False)
ax.coastlines()
ax.set_ylim([0,90]);

"""
Explanation: In order to visualize the data on a conventional latitude-longitude grid, we can take advantage of xarray's ability to apply cartopy map projections.
End of explanation
"""


# define two-degree wide latitude bins
lat_bins = np.arange(0,91,2)
# define a label for each bin corresponding to the central latitude
lat_center = np.arange(1,90,2)
# group according to those bins and take the mean
Tair_lat_mean = ds.Tair.groupby_bins('xc', lat_bins, labels=lat_center).mean()
# plot the result
Tair_lat_mean.plot()

"""
Explanation: Multidimensional Groupby
The above example allowed us to visualize the data on a regular latitude-longitude grid. But what if we want to do a calculation that involves grouping over one of these physical coordinates (rather than the logical coordinates), for example, calculating the mean temperature at each latitude. This can be achieved using xarray's groupby function, which accepts multidimensional variables. By default, groupby will use every unique value in the variable, which is probably not what we want. Instead, we can use the groupby_bins function to specify the output coordinates of the group.
End of explanation
"""


