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

Tutorial 2: Building Panels

" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "Panel is designed to make it simple to add interactive controls to your existing plots and data displays, simple to build apps for your own use in a notebook, simple to deploy apps as standalone dashboards to share with colleagues, and seamlessly shift back and forth between each of these tasks as your needs evolve. If there is one thing you should take away from this tutorial, it's Panel!\n", "\n", "Throughout this tutorial we will use an earthquake dataset collected by the US Geological survey, so will start by loading it:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import dask.dataframe as dd\n", "\n", "df = dd.read_parquet('../data/earthquakes.parq', columns=['time', 'place', 'mag']).reset_index(drop=True).persist()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Additionally before displaying anything with Panel it is always necessary to load the Panel extension:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import panel as pn\n", "\n", "pn.extension()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## pn.interact\n", "\n", "Before we get into the details of how Panel allows you to render and lay out objects we will dive straight in and use Panel's `interact` function, modeled on the similar function in `ipywidgets`, to get a simple interactive app immediately. For instance, if you have a function that returns a row of a dataframe given an index, you can very easily make a panel with a widget to control the row displayed." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def select_row(row=0):\n", " return df.loc[row].compute()\n", "\n", "pn.interact(select_row, row=(0, len(df)-1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This approach can be used for any function that returns a displayable object, calling the function whenever one of the parameters of that function has changed. \n", "\n", "In the spirit of \"shortcuts, not dead ends\", let's see what's in the object returned by `interact`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "app = pn.interact(select_row, row=(0, len(df)-1))\n", "\n", "print(app)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here, `interact` has constructed a Column panel consisting of one Column of widgets (with one widget), and one Row of output (with one HTML pane). This object, once created, is a full compositional Panel object, and can be reconfigured and expanded with additional content if you wish, without breaking the connections between widgets and values:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pn.Column(\"## Choose a row\", pn.Row(app[0], app[1]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Hopefully from this simple example you can see the sorts of things Panel can do. In the rest of this section we'll cover some of the items you can use in a panel and how to compose them. In the subsequent section we will dive into how to set up widgets and their relationships explicitly, and then build a custom dashboard as an exercise. For now, we won't show code for any particular plotting library, but if you have a favorite one already, you should be able to use it with Panel in the exercises.\n", "\n", "## Component types\n", "\n", "Before we start building more interactive apps, we will learn about the three main types of components in Panel:\n", "\n", "* **Pane**: A Pane provides a view of an external object (text, image, plot, etc.) by wrapping it\n", "* **Panel**: A Panel lays out multiple components in a row, column, or grid.\n", "* **Widget**: A Widget provides input controls to add interactive features to your Panel.\n", "\n", "If you ever want to discover how a particular component works, see the [reference gallery](https://panel.pyviz.org/reference/index.html).\n", "\n", "## Displaying content\n", "\n", "The fundamental concept behind Panel is that it transforms the objects you give it into a viewable object that can be composed into a layout and updated dynamically. In this tutorial we will be building a dashboard visualizing a dataset of earthquake events, so let us start by displaying a title using the `pn.panel` function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "title = pn.panel('## Earthquake Dashboard')\n", "\n", "title" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To understand how Panel rendered this string we can take a look at the textual representation of this object:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(title)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Panel transformed the `str` object and wrapped it in a so-called `Markdown` `Pane`. The ``pn.panel`` function attempts to find the most appropriate representation for different objects whether it is a string, an image, or even a plot. So if we provide the location of a PNG file instead as a path or a URL, the ``panel`` function will automatically infer that it should be rendered as an image:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "usgs_logo = pn.panel('../assets/usgs_logo.png', height=130)\n", "\n", "print(usgs_logo)\n", "\n", "usgs_logo" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The appropriate representation is resolved using a set of precedences, so it may sometimes be necessary to explicitly declare the type of Pane that is required. For example, if we want to display some `HTML`, which cannot easily be distinguished from Markdown, we can explicitly declare it by specifying the `HTML` Pane type from the `pn.pane` module:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pn.pane.HTML('Breaking news: A major earthquake has hit.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise\n", "\n", "Use the ``pn.panel`` function to display some different types of objects, e.g. an image, a pandas dataframe or even a plot you made." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now construct the same type of object by explicitly constructing the appropriate type in the ``pn.pane`` module (Hint: Print the object in the previous example to find out what it is):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Laying out content\n", "\n", "In addition to `Pane` objects, Panel provides `Panel` objects that allow laying out components. The principal layouts are by ``Row`` or ``Column``. These components act just like a regular ``list`` in Python:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "column = pn.Column(title, usgs_logo)\n", "\n", "column" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Panels may be nested arbitrarily to construct complex layouts. Internally, Panel will call the ``pn.panel`` function on any objects which are not already a known component type, making it easy to lay out objects without explicitly wrapping them in a panel component, though wrapping it explicitly can help ensure that it is the type you expect:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "\n", "df_top5 = pd.DataFrame([\n", " ('2004-12-26T00:58:53.45', '2004 Sumatra - Andaman Islands Earthquake', 9.1),\n", " ('2011-03-11T05:46:24.12', '2011 Great Tohoku Earthquake, Japan', 9.1),\n", " ('2010-02-27T06:34:11.53', 'Offshore Bio-Bio, Chile', 8.8),\n", " ('2005-03-28T16:09:36.53', 'Northern Sumatra, Indonesia', 8.6),\n", " ('2012-04-11T08:38:36.72', 'Off the west coast of northern Sumatra', 8.6)\n", "], columns=['Time', 'Place', 'Magnitude'])\n", "\n", "row = pn.Row(column, pn.panel(df_top5, width=500))\n", "\n", "row" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise\n", "\n", "Use ``Row`` and ``Column`` panels to lay out some of the objects (text, images, or plots) you rendered in the previous exercise." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Try swapping a ``Row`` or ``Column`` with a ``Tabs`` component:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Updating content\n", "\n", "So far we have only seen how Panel can be used to render and lay out objects, which on its own is not too exciting. However, all Panel objects can be modified once constructed, and all associated views will automatically update in response. Let us take the ``title`` pane we constructed above as an example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "title" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "All Panes have an ``object`` parameter that represents the object they are wrapping. If we set the ``object`` all displayed versions of the pane will update in response:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#title.object = '## The Most Powerful Earthquakes'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This dynamic behavior also extends to Panels, whose Panes will update as they are changed:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "column" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As we discussed above ``Row`` and ``Column`` Panels behave much like lists. Just like lists, we can use ``append``, ``pop``, ``remove``, and all the other standard methods (including setting with =) to modify them. E.g. we could dynamically add a caption for the logo:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "text = \"\"\"\n", "This dashboard displays the most powerful earthquakes recorded\n", "by the US Geological Survey between 2000 and 2018.\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# column.append(text)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you uncomment and execute that cell, make sure to scroll back up to confirm that all versions of the ``column`` have been updated." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise: Construct and display a new Panel and then replace a component in a new cell" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
Hint
\n", "\n", "Use `print()` to see how objects are indexed, then use indexing to replace a component:\n", "\n", "```python\n", "row[1] = \"../assets/panel.png\"\n", "```\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Serving Panel apps\n", "\n", "So far we have been building Panel objects entirely within a notebook, which is a convenient way to build up an app, particularly for one-time or private use. However, a large part of the power of Panel is that it allows us to seamlessly transition between an iterative process inside the notebook to a deployed app. When developing an app inside the notebook it will display inline, but you can see what it looks like as a deployed app by calling ``.show()`` on the object." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# row.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Once you are happy with the app or dashboard you have built you can annotate it with ``.servable()``. In the notebook, this annotation has no effect, but it will later indicate to the ``panel serve`` command that you want this particular component to be served. If you then go to the command line and run ``panel serve 02_Introduction_to_Panel.ipynb``, the code cells in the notebook will be executed and the resulting dashboard will be available as a web server." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "row.servable()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that despite this deep support for switching back and forth between Jupyter and deployed servers, Jupyter is in no way required for this process -- the same deployed dashboard can be obtained by simply exporting the code cells here into their own .py file, and doing `panel serve 02_Introduction_to_Panel.py`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise\n", "\n", "Build a Panel component (or reuse one from a previous exercise) and call ``.show()`` on it." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "language_info": { "name": "python", "pygments_lexer": "ipython3" } }, "nbformat": 4, "nbformat_minor": 4 }