{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "

Exercise 3: Building Pipelines

" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this exercise we will explore hvplot `.interactive()` to add widgets to our analyses and plots. \n", "\n", "We'll first load the earthquakes `DataFrame` and filter to those with `>=7` magnitude:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pathlib\n", "import pandas as pd\n", "import xarray as xr\n", "import panel as pn # noqa\n", "\n", "import hvplot.pandas # noqa: adds hvplot method to pandas objects\n", "import hvplot.xarray # noqa: adds hvplot method to xarray objects" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df = pd.read_parquet(pathlib.Path('../../data/earthquakes-projected.parq'))\n", "columns = ['time', 'mag', 'depth', 'latitude', 'longitude', 'place', 'type']\n", "df = df.set_index(df.time)[columns]\n", "most_severe = df[df.mag >= 7]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Initial inspection of the depth data\n", "\n", "Declare and display a depth float slider with the handle `depth_slider` (and named 'Minimum depth') that ranges between zero and 700 meters and verify that the depth values in `most_severe` lie in this range. Set the default value to the middle of this range.\n", "\n", "\n", "
Hint
\n", "\n", "You can use the `min()` and `max()` method on the `depth` `Series` of `most_severe` to check the range. To declare the slider, use a `pn.widgets.FloatSlider`.\n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "depth_slider = ... \n", "depth_slider" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
Solution
\n", "\n", "```python\n", "depth_slider = pn.widgets.FloatSlider(name='Minimum depth', start=0, end=700, value=350)\n", "depth_slider\n", "```\n", " \n", "```python\n", ">> most_severe.depth.min()\n", "4.2\n", ">> most_severe.depth.max()\n", "675.4\n", " \n", "```\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exploring an interactive `DataFrame`\n", "\n", "Now we will create a new interactive `DataFrame` called `dfi` with `sizing_mode='stretch_width'`.\n", "\n", "\n", "
Hint
\n", "\n", "Use the `.interactive` method on `most_severe` to create the interactive `DataFrame` called `dfi`\n", "
\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dfi = ... # Interactive DataFrame version of most_severe" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
Solution
\n", "\n", "```python\n", "dfi = most_severe.interactive(sizing_mode='stretch_width')\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now use this interactive `Dataframe` to filter the earthquakes deeper than specified by the `depth_slider`. Call this filtered dataframe `depth_filtered` and to view it conveniently, use the `.head()` method to see the first few entries.\n", "\n", "\n", "
Hint
\n", "\n", "Use the the regular pandas idiom to filter a `DataFrame` with `df[mask]` where `mask` is boolean mask. The only difference is instead of picking a fixed depth value to filter by, you can use the `depth_slider` widget instead.\n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "depth_filtered = ...\n", "# Now display the head of this interactive dataframe" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
Solution
\n", "\n", "```python\n", "depth_slider = pn.widgets.FloatSlider(name='Minimum depth', start=0, end=700, value=350)\n", "\n", "dfi = most_severe.interactive(sizing_mode='stretch_width')\n", "depth_filtered = dfi[dfi['depth'] < depth_slider]\n", "\n", "depth_filtered.head()\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Plotting the depth filtered data\n", "\n", "For an initial plot, try calling `.hvplot()` and seeing what happens.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# depth_filtered.hvplot()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now let us focus on plotting the magnitude of the filtered earthquakes as a scatter plot with red cross (`x`) markers.\n", "\n", "
Hint
\n", "\n", "The magnitude column is called `mag`, you can set cross markers with `marker='x'` and to get a scatter plot you can use `kind='scatter'`.\n", "
\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Scatter plot of magnitude, filtered by depth with red cross markers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
Solution
\n", "\n", "```python\n", "depth_slider = pn.widgets.FloatSlider(name='Minimum depth', start=0, end=700, value=350)\n", "\n", "dfi = most_severe.interactive(sizing_mode='stretch_width')\n", "depth_filtered = dfi[dfi['depth'] < depth_slider]\n", "depth_filtered.hvplot(y='mag', kind='scatter', color='red', marker='x')\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Using interactive xarrays\n", "\n", "The `.interactive` interface doesn't only apply to pandas `DataFrames`: you can use the same approach with xarray. Here we load our population raster and perform some simple cleanup:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "raw_ds = xr.open_dataarray(pathlib.Path('../../data/raster/gpw_v4_population_density_rev11_2010_2pt5_min.nc'))\n", "cleaned_ds = raw_ds.where(raw_ds.values != raw_ds.nodatavals).sel(band=1)\n", "cleaned_ds = cleaned_ds.rename({'x': 'longitude','y': 'latitude'})\n", "cleaned_ds.name = 'population'\n", "cleaned_ds = cleaned_ds.fillna(0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One operation we could do on this raster is to collapse one of the two dimensions. For instance, we could view the mean population over latitude (averaged over longitude) or conversely the mean population over longitude (averaged over latitude). To select between these options, we will want a dropdown widget called `collapsed_axis`.\n", "\n", "
Hint
\n", "\n", "A dropdown widget in panel can be made with a `pn.widgets.Select` object. The dropdown options are specified as a list of strings to the `options` argument.\n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "collapsed_axis = ... # Declare a dropdown to select either 'latitude' or 'longitude' and display it" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
Solution
\n", "\n", "```python\n", "collapsed_axis = pn.widgets.Select(options=['latitude', 'longitude'], name='Collapsed dimension')\n", "collapsed_axis\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now create an interactive xarray `DataArray` called `dsi` in the analogous fashion to the interactive `DataFrame` we created earlier. As before, specify `sizing_mode='stretch_width'`.\n", "\n", "
Hint
\n", "\n", "As before, the interactive object is created by calling the `.interactive()` method. This time the method is called on an xarray object instead of a pandas object.\n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dsi = ... # An interactive DataArray" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
Solution
\n", "\n", "```python\n", "dsi = cleaned_ds.interactive(sizing_mode='stretch_width')\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Plotting population averaged over either latitude or longitude\n", "\n", "Now we can use the xarray API to collapse either latitude or longitude by taking the mean. To do this, we can use the `.mean()` method of an xarray `DataArray` which accepts a `dim` argument specifying the dimension over which to apply the mean. After collapsing the dimensions specified by the widget, plot the population with a green curve.\n", "\n", "
Hint
\n", "\n", "First write and test a static version of your pipeline, where you supply 'latitude' or 'longitude' explicitly to the `dim` argument of the `mean` method and then call `.hvplot` to plot it while specifying `color='green'`. Then try passing your `collapsed_axis` widget instead of that fixed string. \n", "
\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Using `dsi` plot the population as a green curve where the collapsed dimension is selected by the widget" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
Solution
\n", "\n", "```python\n", "dsi = cleaned_ds.interactive(sizing_mode='stretch_width')\n", "collapsed_axis = pn.widgets.Select(options=['latitude', 'longitude'], name='Collapsed dimension')\n", "dsi.mean(dim=collapsed_axis).hvplot(color='green')\n", "```" ] } ], "metadata": { "language_info": { "name": "python", "pygments_lexer": "ipython3" } }, "nbformat": 4, "nbformat_minor": 5 }