Working with Gridded Data I

GeoViews is designed to make full use of multidimensional gridded datasets stored in netCDF or other common formats, via the xarray and iris interfaces in HoloViews. This notebook will demonstrate how to load data using both of these data backends, along with some of their individual quirks. The data used in this notebook was originally shipped as part of the SciTools/iris-sample-data repository, but a smaller netCDF file is included as part of the GeoViews so that it can be used with xarray as well.

In [1]:
import iris
import numpy as np
import xarray as xr
import holoviews as hv
import geoviews as gv
import geoviews.feature as gf
from cartopy import crs


Setting some notebook-wide options

Let's start by setting some normalization options (discussed below) and always enable colorbars for the elements we will be displaying:

In [2]:
%opts Image {+framewise} [colorbar=True] Curve [xrotation=60]

You can see that it is easy to set global defaults for a project, allowing any suitable settings to be made into a default on a per-element-type basis. Now let's specify the maximum number of frames we will be displaying:

In [3]:
%output max_frames=1000 

Loading our data

In this notebook we will primarily be working with xarray, but we will also load the same data using iris so that we can demonstrate that the two data backends are nearly equivalent.


As a first step we simply load the data using the open_dataset method xarray provides and have a look at the repr to get an overview what is in this dataset:

In [4]:
xr_ensemble = xr.open_dataset('./sample-data/')
Dimensions:                  (bnds: 2, latitude: 145, longitude: 192, time: 6)
  * time                     (time) datetime64[ns] 2011-08-16T12:00:00 ...
  * latitude                 (latitude) float32 -90.0 -88.75 -87.5 -86.25 ...
  * longitude                (longitude) float32 0.0 1.875 3.75 5.625 7.5 ...
    forecast_period          (time) timedelta64[ns] 29 days 12:00:00 ...
    forecast_reference_time  datetime64[ns] 2011-07-18
Dimensions without coordinates: bnds
Data variables:
    surface_temperature      (time, latitude, longitude) float64 214.0 214.0 ...
    latitude_longitude       int32 -2147483647
    time_bnds                (time, bnds) float64 3.645e+05 3.652e+05 ...
    forecast_period_bnds     (time, bnds) float64 336.0 1.08e+03 1.08e+03 ...
    source: Data from Met Office Unified Model
    um_version: 7.6
    Conventions: CF-1.5


Similarly we can load the same dataset using Iris' load_cube function and get a similar overview using the summary method.

In [5]:
iris_ensemble = iris.load_cube('./sample-data/')
print iris_ensemble.summary()
surface_temperature / (K)           (time: 6; latitude: 145; longitude: 192)
     Dimension coordinates:
          time                           x            -               -
          latitude                       -            x               -
          longitude                      -            -               x
     Auxiliary coordinates:
          forecast_period                x            -               -
     Scalar coordinates:
          forecast_reference_time: 2011-07-18 00:00:00
          Conventions: CF-1.5
          STASH: m01s00i024
          source: Data from Met Office Unified Model
          um_version: 7.6
     Cell methods:
          mean: time (1 hour)

Describing the differences between these two libraries is well beyond the scope of this tutorial, but you can see from the summaries that the two libraries deal differently with both the bounds and with the actual data variables. Iris cubes support only a single data variable, while an xarray dataset can have any number of variables. In this case we are only interested in the surface_temperature dimension, indexed by longitude , latitude and time .

We can easily express this interest by wrapping the data in a GeoViews Dataset Element and declaring the key dimensions ( kdims ) and value dimensions ( vdims ). Note that the Iris interface is much smarter in the way it extracts the dimensions, so usually you will not have to supply them explicitly.

In [6]:
kdims = ['time', 'longitude', 'latitude']
vdims = ['surface_temperature']

xr_dataset = gv.Dataset(xr_ensemble, kdims=kdims, vdims=vdims, crs=crs.PlateCarree())
iris_dataset = gv.Dataset(iris_ensemble, kdims=kdims, vdims=vdims)

Now we can compare the repr of the two Elements:

In [7]:
print repr(xr_dataset)
print repr(iris_dataset)
:Dataset   [time,longitude,latitude]   (surface_temperature)
:Dataset   [time,longitude,latitude]   (surface_temperature)

Despite appearing identical, there are some internal differences, such as in the data types. xarray uses NumPy datetime64 types for dates, while iris will use simple floats:

In [8]:
print("XArray time type: %s" % xr_dataset.get_dimension_type('time'))
print("Iris time type: %s" % iris_dataset.get_dimension_type('time'))
XArray time type: <type 'numpy.datetime64'>
Iris time type: <type 'numpy.float64'>

To improve the formatting of dates on the xarray dataset we can set the formatter for datetime64 types:

In [9]:
hv.Dimension.type_formatters[np.datetime64] = '%Y-%m-%d'

The other major differences in the way iris cubes are handled are in deducing various bits of metadata including the coordinate system, units, and formatters. Otherwise the two Dataset Elements will behave largely the same.

For either data backend, the Dataset object is not yet visualizable, because we have not chosen which dimensions to map onto which axes of a plot.

A Simple example

To visualize the datasets, in a single line of code we can specify that we want to view it as a collection of Images indexed by longitude and latitude (a HoloViews HoloMap of gv.Image elements):

In [10]:, ['longitude', 'latitude'])

Notice how we also had to specify the coordinate reference system ( crs ). This is because xarray does not extract a coordinate system from the data. Iris on the other hand makes that information available automatically, which means we don't have to declare it explicitly:

In [11]:, ['longitude', 'latitude'])

You can see that in both cases the time dimension was automatically mapped to a slider, because we did not map it onto one of the other available dimensions (x, y, or color, in this case). You can drag the slider to view the surface temperature at different times.

Now let us load a cube showing the pre-industrial air temperature:

In [12]:
air_temperature = gv.Dataset(xr.open_dataset('./sample-data/'), kdims=['longitude', 'latitude'],
                             group='Pre-industrial air temperature', vdims=['air_temperature'],
:Dataset   [longitude,latitude]   (air_temperature)

Note that we have the air_temperature available over longitude and latitude but not the time dimensions. As a result, this cube is a single frame (at right below) when visualized as a temperature map.

In [13]:
(['longitude', 'latitude'])+['longitude', 'latitude']))

The above plot shows how to combine a fixed number of plots using + , but what if you want to combine some arbitrarily long list of objects? You can do that by making a Layout explicitly, which is what + does internally.

The following more complicated example shows how complex interactive plots can be generated with relatively little code, and also demonstrates how different HoloViews elements can be combined together. In the following visualization, the black dot denotes a specific longitude, latitude location (0,10) , and the curve is a sample of the surface_temperature at that location. The curve is unaffected by the time slider because it already lays out time along the x axis:

In [14]:
%%opts Curve [aspect=2 xticks=4 xrotation=15] Points (color='k')
temp_curve = hv.Curve(, latitude=10), kdims=['time'])
temp_map =,['longitude', 'latitude']) * gv.Points([(0,10)], crs=crs.PlateCarree())
temp_map + temp_curve

Overlaying data and normalization

Let's view the surface temperatures together with the global coastline:

In [15]:
%%opts Image [projection=crs.Geostationary()] (cmap='Greens') Overlay [xaxis=None yaxis=None]['longitude', 'latitude']) * gf.coastline

Notice that every frame individually uses the full dynamic range of the Greens color map. This is because normalization is set to +framewise at the top of the notebook, which means every frame is normalized independently. This sort of normalization can be computed on an as-needed basis, using whatever values are found in the current data being shown in a given frame, but it won't let you see how different frames compare to each other.

To control normalization, we need to decide on the normalization limits. Let's see the maximum temperature in the cube, and use it to set a normalization range by using the redim method:

In [16]:
%%opts Image [projection=crs.Geostationary()] (cmap='Greens') Overlay [xaxis=None yaxis=None]
max_surface_temp = xr_dataset.range('surface_temperature')[1]
print max_surface_temp
xr_dataset.redim(surface_temperature=dict(range=(300, max_surface_temp))).to(gv.Image,['longitude', 'latitude']) \
  * gf.coastline

By specifying the normalization range we can reveal different aspects of the data. In the example above we can see a cooling effect over time as the dark green areas close to the top of the normalization range (317K) vanish. Values outside this range are clipped to the ends of the color map.

Lastly, here is a demo of a conversion from surface_temperature to FilledContours :

In [17]:,['longitude', 'latitude']) * gf.coastline

As you can see, it's quite simple to expose any data you like from your Iris cube or xarray, easily and flexibly creating interactive or static visualizations.