Dashboards
DS 2023 | Communicating with Data

Overview¶
A dashboard is a graphical software application that pulls data from one or more sources and displays it in one place with multiple vidualizations and widgets.
Regarding input data, these may come from multiple sources and may or may not be real-time soruces that update the dashboard continuously.
In contrast to an essay or slide presentation, dashboards are open-ended relative to a specific thesis: the goal is to support inquiry and situational awareness.
Although open-ended, dashboards are built to support specific goals and monitor specific kinds of events, such as the spread of a virus or the state of the weather.
Use cases¶
Interactive arguments. Although not technically a dashboard, a simple and effective use case is to incorporate interactive widgets in narrative or argumentative order, replacing a static argument with tools that allow the user to validate or digger deeper into the claims made by a paper.
Environmental awareness. A classic use of dashboards is to provide real-time information about wide-area phenomena, such as the spread of a virus or the weather. Widgets show different facets of a general phenomenon, often pulling from different data sources. Think of a weather app, that shows humidity, temperature, wind speed, and doppler views of precipitation over a geographic area.
Decision support. Another classic use of dashboards is to provide decision-support: timely and situational information can be used to guide decision-making in a variety of domains, from finanace to medicine.
Business intelligence. More broadly, dashboards may be used to provide members of an organization with key aspects of their enterprise to support decison-making across a variety of activities.
Sharing an analysis with people who don’t code. A manager, a client, or a friend in another major can use a slider without reading Python.
Teaching. A slider that changes a histogram’s bins shows what a paragraph about bins can only describe.
Checking your own work. While exploring data, a quick page lets you flip through every group and measure.
General kinds of dashboards¶
In gerneral, there are three main kinds of dashboards:
Monitoring dashboards show values that change over time: a server’s load, today’s sales, the open beds in a hospital. These can be real-time or longer term. They often integrate data from a variety of sources to give an accurate and current picture of events of interest.
Exploratory dashboards let a reader ask small questions of a fixed dataset: pick a group, pick a measure, see the plot.
Explanatory dashboards provide interactivity in a context where the participation of the user is rhetorically advantageous to the promotion of an argument or thesis.
Aspects of design¶
All dashboards are made up of the same general elements:
Data sources
Widgets and visualizations
Arrangements
Dependencies
Level of interactivity
Dashboard Tools in Python¶
Python has many tools for making dashboards.
They differ mostly in how much new code they ask you to learn.
| Tool | What you write | From | Notes |
|---|---|---|---|
| Voilà | An ordinary notebook with ipywidgets | Project Jupyter | Turns a notebook into a page. Nothing new to learn. |
| Streamlit | A script that reruns from the top on every change | Snowflake | Very popular. Has its own widgets. |
| Dash | An app with a layout and callback functions | Plotly | Built around Plotly figures. Scales to large apps. |
| Panel | Notebooks or scripts | HoloViz | Works with most plotting libraries, inside or outside notebooks. |
| Shiny for Python | An app with reactive functions | Posit | The Python version of R’s Shiny. |
| Solara | Components in the style of React | Widgetti | Built on ipywidgets. |
Most of these tools require that you rewrite your code as an application, with its own rules for layout and for responding to the user.
However, Voilà asks for almost nothing new: If you can write a notebook with widgets, you can make a Voilà dashboard.
This notebook focuses on Voilà.
Using Voilà¶
Voilà builds on everything we’ve already learned: Matplotlib, Plotly, and Python Widgets.
Since Voilà is not in our ds2023 environment, we need to install it.
You can do this with either conda or pip,
In a terminal, after activating ds2023 do this:
conda install -c conda-forge voilaor this:
pip install voilaPattern 1: Notebook to dashboard¶
The first and simplest way to create a dashboard with Voilà is to take a notebook that uses Python Widges, for example by using @interact, and then run it with voila.
For example, to show the Palmer Penguins notebook as a dashboard, to do this after downloading the notebook:
voila penguins-dashboard.ipynbVoilà starts a small server and opens the page in a browser tab, at an address like http://localhost:8866.
You can press Ctrl-C in the terminal to stop it.
Note that you can also run Voilà from within JupyterLab. Installing Voilà adds a Render with Voilà button to the notebook toolbar.
Clicking on it opens the current notebook as a rendered page in a new tab beside the notebook.
VS Code has no such button, so use its terminal.
A few options are worth knowing:
--theme=darkuses JupyterLab’s dark theme.--show_tracebacks=Trueshows the full error when a cell fails. Voilà hides errors by default, which is right for readers but frustrating for us while we build.--strip_sources=Falsekeeps the code on the page, which we rarely want.
Making a notebook ready for Voilà¶
Here some tips on how to make your notebook ready for Voilà.
Always restart the kernak and run all cells before converting. If the notebook doesn’t run from top to bottom, neither will the page.
Know that every output appears. For exmaple, a stray
penguins.head()will show up. Delete it or keep it on purpose.End each plotting function with
plt.show(). Each change then replaces the figure instead of adding another one below it.Load data once, at the top. A function that reads a CSV every time the slider moves makes the page crawl.
Write the Markdown for your reader. Notes like “this didn’t work, trying again” belong in a different notebook.
Use headers and structure the page. Take advantage the notebook’s capability of being organized like an essay.
The Limit of pattern 1¶
Since Voilà just follows the notebook’s layout, everything appears in one column.
This is OK for an essay, but with a dashboard, you want to take advantage of horizontal space to show more things at once.
To achieve this effect, we need to arrange things ourselves.
Pattern 2: Arranging widgets¶
The interact function builds its controls and displays them right away. The plot and widgets live where the function is defined.
Theinteractive function, on the other hand, takes the same arguments, but instead returns the widget instead of displaying it.
This way, you can show the interactive plot anywhere you want on the page.
Let’s demonstrate this with the Penguin’s dataset.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import ipywidgets as widgets
from ipywidgets import interact, interactivepenguins = sns.load_dataset('penguins').dropna()
measure_cols = ['bill_length_mm', 'bill_depth_mm', 'flipper_length_mm', 'body_mass_g']
penguins.head()Here, we define to visualization functions, one for a histogram and one for a scatterplot.
def plot_hist(measure='flipper_length_mm', bins=20):
(penguins
.pivot(columns='species', values=measure)
.plot.hist(bins=bins, alpha=0.5, figsize=(5, 3.5), title=measure))def plot_scatter(x='bill_length_mm', y='bill_depth_mm'):
penguins.plot.scatter(x=x, y=y, c='species', figsize=(5, 3.5))Next, we bind these functions to some widgets using interactive.
Note the arguments to the function are identical to @interact, except that we put the saved plot as the first argument.
hist = interactive(plot_hist, measure=measure_cols, bins=(5, 50, 5))Now, we can display this wherever we want, like so:
histNot only does interactive let up place the plot wherever we want, it also exposes the properties of the plot.
Each interactive plot is an object that has “children” — the elements that compose the interactive plot.
You can see this by exploring it’s children attribute which contains a list of objects.
hist.children[0]hist.children[1]hist.children[2]In other words, an interactive object is a box of widgets.
The controls come first, in the order of the function’s parameters.
The last child is an Output widget, which is where the plot is drawn.
Since these are ordinary widgets, we can put them into other boxes.
Python Widgets provides two useful boxes for us:
widgets.HBoxlays its children out in a row.widgets.VBoxstacks them in a column.
Each takes a list of widgets.
Let’s see how this works.
Controls in a row¶
Let’s put the controls side by side above the plot.
First, let’s create a fresh instance of hist.
hist = interactive(plot_hist, measure=measure_cols, bins=(5, 50, 5))Then, we put the widgets into a horizontal box and save it.
controls = widgets.HBox(hist.children[:-1]) # The widgetsFinally, we pass the horizontal box to a vertical box and show it.
widgets.VBox([controls, hist.children[-1]]) # The figureNotice that we made a fresh hist before arranging it.
A widget can be shown in more than one place, but each copy is live, and moving one moves them all.
Starting fresh keeps the examples apart.
Controls in a sidebar¶
A sidebar puts the controls in a column to the left of the plot.
We give the sidebar a fixed width with widgets.Layout, so it doesn’t change size as labels change.
hist = interactive(plot_hist, measure=measure_cols, bins=(5, 50, 5))
sidebar = widgets.VBox(hist.children[:-1], layout=widgets.Layout(width='320px'))
widgets.HBox([sidebar, hist.children[-1]])Two Plots side-by-side¶
Since interactive object is itself a widget, we can put two of them in an HBox.
Each keeps its own controls.
hist = interactive(plot_hist, measure=measure_cols, bins=(5, 50, 5))
scatter = interactive(plot_scatter, x=measure_cols, y=measure_cols)
widgets.HBox([hist, scatter])This is why our plotting functions use a small figsize.
Two figures 5 inches wide fit across most screens; two figures 10 inches wide do not.
One control for two plots¶
So far, we’ve used interactive to build controls from short forms: a list becomes a dropdown, and a tuple becomes a slider.
But we can also pass it a widget we made ourselves.
If we pass the same widget to two interactive calls, both plots listen to it.
Let’s make one dropdown that drives a histogram and a box plot.
def plot_box(measure='flipper_length_mm'):
(penguins
.pivot(columns='species', values=measure)
.plot.box(figsize=(5, 3.5), title=measure))
plt.show()Now let’s create one widget that will be used for two plots.
measure = widgets.Dropdown(options=measure_cols, value='flipper_length_mm', description='Measure')Now let’s put this all together.
hist = interactive(plot_hist, measure=measure, bins=(5, 50, 5))
box = interactive(plot_box, measure=measure)
controls = widgets.HBox(hist.children[:-1])
plots = widgets.HBox([hist.children[-1], box.children[-1]])
widgets.VBox([controls, plots])A complete dashboard¶
Now let’s put the pieces together: a sidebar with both controls, and the two plots beside it.
This cell, plus a title and the set-up code, is the whole of penguins-dashboard.ipynb.
measure = widgets.Dropdown(options=measure_cols, value='flipper_length_mm', description='Measure')
bins = widgets.IntSlider(value=20, min=5, max=50, step=5, description='Bins', continuous_update=False)
hist = interactive(plot_hist, measure=measure, bins=bins)
box = interactive(plot_box, measure=measure)
sidebar = widgets.VBox([measure, bins], layout=widgets.Layout(width='320px'))
plots = widgets.HBox([hist.children[-1], box.children[-1]])
widgets.HBox([sidebar, plots])Notice how short a dashboard notebook is.
It has a title, a sentence of instructions, one cell of set-up, and one cell that builds the layout.
Compare it with penguins-dashboard.ipynb, where the Markdown carries the reader from one plot to the next.
The two patterns suit different readers: the first tells a story, and the second offers a tool.
Publishing with Binder and GitHub¶
Running Voilà on our laptop only helps people looking at our laptop.
To share a dashboard, it needs a computer on the internet that can run its kernel.
Binder (mybinder.org) is a free service that does this.
Given a public GitHub repository, Binder builds an environment from it, starts Jupyter, and opens the page we ask for.
We will ask it to open our notebook in Voilà.
Step 1: Make a Repository¶
In GitHub Desktop, choose File > New Repository and name it penguins-dashboard.
When you publish it, uncheck Keep this code private.
The repository needs only four files:
README.mdpenguins-dashboard.ipynbrequirements.txtruntime.txt
Copy penguins-dashboard.ipynb into the repo folder.
Step 2: Describe the Environment¶
Binder knows nothing about our ds2023 environment.
It reads the repository’s files to decide what to install.
requirements.txt lists the packages, one per line:
voila
ipywidgets
pandas>=3.0
matplotlib
seabornruntime.txt names the version of Python:
python-3.12We ask for pandas 3 because plot.scatter(c='species') and other code in this course need it, and pandas 3 needs a recent Python.
List only what the dashboard imports.
Each extra package makes the first launch slower.
A package that is missing from the list shows up as an import error on the page.
Step 3: Test, Commit, and Push¶
Before pushing, run the dashboard locally one more time:
voila penguins-dashboard.ipynb --show_tracebacks=TrueIf it works, commit all four files in GitHub Desktop and click Push origin.
Binder reads the repository on GitHub, not the folder on your laptop, so nothing happens until you push.
Step 4: Build the Binder Link¶
Go to mybinder.org and fill in the form:
GitHub repository name or URL: your repository’s URL.
Git ref: leave it blank, which means the default branch.
Path to a notebook file: change the menu from File to URL, then enter
voila/render/penguins-dashboard.ipynb.
Click launch.
The voila/render/ part tells Binder to open the notebook in Voilà instead of in JupyterLab.
The page also shows the link it built, which looks like this:
https://mybinder.org/v2/gh/YOUR-USERNAME/penguins-dashboard/HEAD?urlpath=voila%2Frender%2Fpenguins-dashboard.ipynb%2F is just / written in a form that is safe inside a URL.
HEAD means the latest commit on the default branch.
You can write this link by hand for any repository by changing the username, repository, and notebook name.
Step 5: Add a Badge¶
The form also gives Markdown for a launch binder badge.
Paste it into README.md, so the repository’s front page has a button that opens the dashboard:
[](https://mybinder.org/v2/gh/YOUR-USERNAME/penguins-dashboard/HEAD?urlpath=voila%2Frender%2Fpenguins-dashboard.ipynb)Commit and push the README, and the dashboard is published.
Anyone with the link can use it, and no one needs to see a line of code.
What to Expect from Binder¶
Binder is generous, but it is not a web host.
The first launch is slow. After each push, Binder rebuilds the environment, which can take several minutes. Later launches are much faster. Launch it once yourself after pushing, so your readers don’t wait.
Idle sessions end. A session that sits unused for about ten minutes is shut down, and the reader has to relaunch.
There is a crowd limit. About 100 people can use one repository at the same time.
Nothing is saved. When a session ends, everything in it is gone.
There is no guarantee. mybinder.org is free and run by volunteers on donated computers. Sometimes it is slow or down.