<jupyter_start><jupyter_text>Alert: Some widgets in this notebook are set to render dynamically and require a live notebook server. If you're viewing this notebook on a static website, the widgets won't respond. The main strength of [HoloViews](http://holoviews.org) and its extensions (like GeoViews) is the ability to quickly explore complex datasets by declaring lower-dimensional views into a higher-dimensional space. In HoloViews we refer to the interface that allows you to do this as the conversion API. To begin with we will load a multi-dimensional dataset of surface temperatures for different "realizations" (modelling parameters) using [XArray](https://github.com/pydata/xarray/):<jupyter_code>xr_ensembles = xr.open_dataset('./sample-data/ensembles.nc')
xr_ensembles<jupyter_output><empty_output><jupyter_text>As we saw in the [Gridded Datasets I Tutorial](Gridded_Datasets_I.ipynb) we can easily wrap this xarray data structure as a HoloViews Dataset:<jupyter_code>dataset = gv.Dataset(xr_ensembles, vdims='surface_temperature', crs=ccrs.PlateCarree())
dataset<jupyter_output><empty_output><jupyter_text>From the repr we can immediately see the list of key dimensions (time, realization, longitude and latitude) and the value dimension of the cube (surface_temperature). However, unlike most other HoloViews Elements, the ``Dataset`` Element does not display itself visually. This is because it can be n-dimensional and therefore does not have any specific straightforward visual representation on a 2D display. To view the cube, we first have to transform it into individually visualizable chunks.  Before doing so, we will want to supply a custom value formatter for the time dimension so that it is readable by humans:<jupyter_code>hv.Dimension.type_formatters[np.datetime64] = '%Y-%m-%d'<jupyter_output><empty_output><jupyter_text>ConversionsA HoloViews Dataset is a wrapper around a complex multi-dimensional datastructure which allows the user to convert their data into individually visualizable views, each usually of lower dimensionality. This is done by grouping the data by some dimension and then casting it to a specific Element type, which visualizes itself.The ``dataset.to`` interface makes this especially easy.  To use it, you supply the Element type that you want to view the data as and the key dimensions of that view and it will figure out the rest. Depending on the type of Element, you can specify one or more dimensions to be displayed. GeoViews provides a set of GeoElements that allow you to display geographic data on a cartographic projection, but you can use any Elements from HoloViews for non-geographic plots.Recall that the cube we are working with has 4 coordinate dimensions (or key dimensions as they are known in HoloViews) -- time, realization, longitude, and latitude.  For our purposes, a geographic plot is defined as a plot that has longitude along the x axis and latitude along the y axis. To declare a two-dimensional geographic plot, we therefore simply request a `gv.Image` plot with ``longitude`` and ``latitude`` as key dimensions.  There is one value dimension (vdim) available, ``surface_temperature``, and any remaining key dimensions (``time`` and ``realization`` in this case) are assigned to a ``HoloMap`` data structure by default.  The resulting ``HoloMap`` gives you widgets automatically to allow you to explore the data across the two "remaining" key dimensions (those not mapped onto axes of the image):<jupyter_code>geo_dims = ['longitude', 'latitude']
(dataset.to(gv.Image, geo_dims) * gf.coastline)[::5, ::5]<jupyter_output><empty_output><jupyter_text>In this way we can visualize the geographic data in a number of ways, currently either as an ``Image`` (as above) or as ``LineContours``, ``FilledContours``, or ``Points``:<jupyter_code>%%opts Points [color_index=2 size_index=None] (cmap='jet')
hv.Layout([dataset.to(el, geo_dims)[::10, ::10] * gf.coastline
           for el in [gv.FilledContours, gv.LineContours, gv.Points]]).cols(1)<jupyter_output><empty_output><jupyter_text>Note that by default the conversion interface will automatically expand all the individual Elements, which can take some time if the data is very large. Instead we can also request the objects to be expanded dynamically using the ``dynamic`` keyword:<jupyter_code>dataset.to(gv.Image, geo_dims, dynamic=True) * gf.coastline<jupyter_output><empty_output><jupyter_text>Using ``dynamic`` mode means that the data for each frame is only extracted when you're actually viewing that part of the data, which can have huge benefits in terms of speed and memory consumption.  However, it relies on having a running Python process to render and serve each image, and so it cannot be used when generating static HTML output such as for the GeoViews web site. Irregularly sampled dataOften gridded datasets are not regularly sampled, instead providing irregularly sampled multi-dimensional coordinates. Such datasets can be easily visualized using the QuadMesh element.<jupyter_code>%%opts QuadMesh [colorbar=True fig_size=300 projection=ccrs.Robinson()] (cmap='RdBu_r')
xrds = xr.tutorial.load_dataset('rasm')
qmesh = gv.Dataset(xrds.Tair).to(gv.QuadMesh, ['xc', 'yc'], dynamic=True)
qmesh.redim.range(Tair=(-30, 30)) * gf.coastline<jupyter_output><empty_output><jupyter_text>Non-geographic viewsSo far we have focused entirely on geographic views of the data, plotting the data on a projection. However the conversion interface is completely general, allowing us to slice and dice the data in any way we like. For these views we will switch to the bokeh plotting extension:<jupyter_code>%output backend='bokeh'<jupyter_output><empty_output><jupyter_text>The simplest example of this capability is simply a view showing the temperature over time for each realization, longitude, and latitude coordinate:<jupyter_code>%%opts Curve [xrotation=25 width=600 height=400] {+framewise} NdOverlay [legend_position='right' toolbar='above']
dataset.to(hv.Curve, 'time', dynamic=True).overlay('realization')<jupyter_output><empty_output><jupyter_text>Note that the longitude slider will have no effect, if latitude is -90 or +90, since there is only one data point for the North or South poles (regardless of the declared longitude).  Here the `.overlay` gives a different curve for each `realization`; without it all `realization` values would be pooled together.We can also make non-geographic 2D plots, for instance as a ``HeatMap`` over time and realization, at a specified longitude and latitude:<jupyter_code>%%opts HeatMap [width=600 colorbar=True tools=['hover'] toolbar='above']
dataset.to(hv.HeatMap, ['realization', 'time'], dynamic=True)<jupyter_output><empty_output><jupyter_text>Lower-dimensional viewsSo far all the conversions shown have incorporated each of the available coordinate dimensions explicitly. However, often times we want to see the spread of values along one or more dimensions, pooling all the other dimensions together. A simple example of this is a box plot where we might want to see the spread of surface_temperature on each day, pooled across all latitude and longitude coordinates. To pool across particular dimensions, we can explicitly declare the "map" dimensions, which are the key dimensions of the HoloMap container rather than those of the Elements contained in the HoloMap. By explicitly declaring no dimensions to  ``groupby``, we can tell the conversion interface to pool across all dimensions *except* the particular key dimension(s) supplied, in this case the `'time'` (plot **A**) and `'realization'` (plot **B**):<jupyter_code>%%output backend='matplotlib'
%%opts BoxWhisker [xrotation=25 bgcolor='w']
hv.Layout([dataset.to(hv.BoxWhisker, d, None, []) for d in ['time', 'realization']])<jupyter_output><empty_output><jupyter_text>This approach also gives us access to other statistical plot types. For instance, with the ``seaborn`` library installed, we can use the ``Distribution`` Element, which visualizes the data as a kernel density estimate. In this way we can visualize how the distribution of surface temperature values varies over time and the model realizations. We do this by omitting 'latitude' and 'longitude' from the list of dimensions, generating a lower-dimensional view into the data, where a temperature histogram is shown for every `'realization'` and `'time'`, using `GridSpace`:<jupyter_code>%%output backend='matplotlib'
%opts GridSpace [shared_xaxis=True]
grid = dataset.to(hv.Distribution, 'surface_temperature', groupby=['realization', 'time']).grid()
grid<jupyter_output><empty_output><jupyter_text>Reducing the dataSo far all the examples we have seen have displayed all the data in some way or another. Another way to explore a dataset is to explicitly reduce the dimensionality or select subregions of a dataset. There are two main ways to do this---either we explicitly select a subset of the data, or we collapse a dimension using an aggregation function, e.g. by computing a mean along a particular dimension. Selecting slicesUsing the ``select`` method we can easily select ranges of coordinates in the dataset. Unfortunately, the select method does not currently know that latitude and longitude are cyclic, so instead we have to select regions at both ends of the prime meridian (0$^\circ$ longitude) and overlay them. In this way we can stitch together multiple cubes or xarrays or simply view specific subregions:<jupyter_code>%%output backend='matplotlib'
northern = dataset.select(latitude=(25, 75))
(northern.select(longitude=(260, 305)).to(gv.Image, geo_dims) *
 northern.select(longitude=(330, 362)).to(gv.Image, geo_dims) *
 gf.coastline)[::5, fdf8:f53e:61e4::18]<jupyter_output><empty_output><jupyter_text>Selecting a particular coordinateTo examine one particular coordinate, we can ``select`` it, cast the data to Curves, reindex the data to drop the now-constant latitude and longitude dimensions, and overlay the remaining 'realization' dimension:<jupyter_code>%%opts NdOverlay [width=600 height=400 legend_position='right' toolbar='above'] Curve (color=Palette('Set1'))
dataset.select(latitude=0, longitude=0).to(hv.Curve, ['time']).reindex().overlay()<jupyter_output><empty_output><jupyter_text>Aggregating coordinatesAnother option is to aggregate over certain dimensions, so that we can get an idea of distributions of temperatures across all latitudes and longitudes. Here we compute the mean temperature and standard deviation by latitude and longitude, casting the resulting collapsed view to a Spread Element:<jupyter_code>hv.Spread(dataset.aggregate('latitude', np.mean, np.std)) +\
hv.Spread(dataset.aggregate('longitude', np.mean, np.std))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.07993657308086932, 'fraction_numerical': 0.006715791437365917, 'mean_word_length': 6.195973154362416, 'pattern_counts': {'":': 0, '<': 61, '<?xml version=': 0, '>': 61, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '15', 'dir': 'jupyter-structured-clean-dedup', 'id': '93539', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 2979, 'n_tokens_neox': 2837, 'n_words': 1308, 'path': 'notebooks/user_guide/Gridded_Datasets_II.ipynb', 'repo_name': 'scaine1/geoviews', 'size': '10706'}