Creating an Interactive Dashboard from Jupyter Notebook with Voila | by Ruben Winastwan | Towards Data Science

With the emergence of BI tools such as PowerBI and Tableau, Jupyter Notebook probably wouldn’t be the first tool that comes up in your mind when you want to create an interactive dashboard. However, thanks to Voila, now it is possible to build an interactive dashboard directly from Jupyter Notebook.
In this article, I want to show you the step-by-step guide on how to create interactive plots with Jupyter Notebook, turn them into a standalone dashboard, and then deploy it on the cloud with Heroku so that other people can see your dashboard. So, let’s get started!
In this article, I’m going to use the San Fransisco dataset. The dataset contains more than 150,000 rows of crime history that occurred in San Fransisco during 2016.
As usual, we can load the dataset with Pandas. To get a sense of what the dataset looks like, let’s print out the first five rows of the dataset afterward.
import numpy as np
import pandas as pd
import folium

df = pd.read_csv('SF_crimes.csv')

df.head()

 

Since the purpose of the article is to show how to turn interactive visualizations in your Jupyter Notebook into a standalone dashboard using Voila, then I’m not going to do EDA of this dataset. Let’s jump into creating widgets to add interactivity to the visualizations of this dataset.
Now that we’ve loaded the data, we can start right away to create widgets. These widgets are essentials to add interactivity to our visualizations. In this article, we’re going to use three widgets: one slider widget and two multiple selection widgets. To create these widgets, we can use ipywidgets library that is available for Jupyter Notebook.
The first widget that we are going to create is the slider widget. To do this, we can use IntSlider()attribute from ipywidgets. This slider widget will control how many rows of the dataset that Pandas should load. For example, if the slider value is 1000, then Pandas should load the first 1000 rows of the dataset. Below is the code implementation of that.
import ipywidgets as widgetsimport pandas as pdstyle = {'description_width': 'initial'}limit_case = widgets.IntSlider(    value=1000,    min=100,    max=5000,    step=1,    description='Max Number of Case:',    disabled=False,    style=style)
In the code above, we passed several arguments into IntSlider()attribute from ipywidgets. The first one is value , which is the default value that will be displayed when we run the code. Next, min and max are the minimum and maximum range values that can be considered in the slider. Meanwhile, step is the value increment or decrement when we move the slider up or down. Finally, we add style argument such that the word in description will not be truncated.
Next, with interactive()attribute from ipywidgets, we can link up the widget with the variable in which the value we want to interactively change. Now if we change the slider value, we can see that the length of the dataset will be changed accordingly.
import ipywidgets as widgets
import pandas as pd

style = {'description_width': 'initial'}

limit_case = widgets.IntSlider(
    value=1000,
    min=100,
    max=5000,
    step=1,
    description='Max Number of Case:',
    disabled=False,
    style=style)

def update_df_length(limit):
    
    df = pd.read_csv('SF_crimes.csv')
    df = df.iloc[0:limit, :]
    
    print("Number of rows in the dataset that have been successfully loaded:"+str(len(df)))

widgets.interactive(update_df_length, limit=limit_case)

interactive(children=(IntSlider(value=1000, description='Max Number of Case:', max=5000, min=100, style=Slider...
 

If you run the code cells above, you’ll get an interactive slider widget like this.
Next, let’s create the second widget, which is the multiple selection widget. We can do this by using SelectMultiple()attribute from ipywidgets. With this widget, we have the option to visualize the crime only in particular selection of districts instead of all districts. In order to create this multiple selection widget, below is the code implementation.
import pandas as pdimport ipywidgets as widgetsfrom ipywidgets import Layoutdf = pd.read_csv('SF_crimes.csv')unique_district = df.PdDistrict.unique()district = widgets.SelectMultiple(    options = unique_district.tolist(),    value = ['BAYVIEW', 'NORTHERN'],    description='District',    disabled=False,    layout = Layout(width='50%', height='80px', display='flex'))
In the code above, we use SelectMultiple() attribute to enable us to pick more than one values of our district variable. The first argument that we should specify is options , which should contain the list of available options of our variable (in our case different kinds of San Fransisco districts). The next one is value , which should contain the variable values that we want to display as default, and then description is for the text field to describe the name of the widget.
import pandas as pd
import ipywidgets as widgets

df = pd.read_csv('SF_crimes.csv')

unique_district = df.PdDistrict.unique()

from ipywidgets import Layout

district = widgets.SelectMultiple(
    options = unique_district.tolist(),
    value = ['BAYVIEW', 'NORTHERN'],
    description='District',
    disabled=False,
    layout = Layout(width='50%', height='80px', display='flex')
)

district

SelectMultiple(description='District', index=(1, 4), layout=Layout(display='flex', height='80px', width='50%')...
 

If you run the code cells above, you’ll get the following interactive multiple selection widget.
To wrap up, we can create the third widget that is exactly the same as the previous multiple selection widget. The purpose of this widget is to enable us to choose which category of crimes that we want to visualize. Below is the code implementation of this widget.
import pandas as pdimport ipywidgets as widgetsfrom ipywidgets import Layoutdf = pd.read_csv('SF_crimes.csv')unique_cat = df.Category.unique()style = {'description_width': 'initial'}category = widgets.SelectMultiple(    options = unique_cat.tolist(),    value = ['VANDALISM', 'ASSAULT', 'ROBBERY'],    description='Criminal Case',    disabled=False,    style=style,    layout = Layout(width='50%', height='80px'))
The arguments that we passed on this SelectMultiple() attribute is the same as before, except that the value and options arguments would be the crime categories instead of districts.
import pandas as pd
import ipywidgets as widgets
from ipywidgets import Layout

df = pd.read_csv('SF_crimes.csv')

unique_cat = df.Category.unique()

style = {'description_width': 'initial'}

category = widgets.SelectMultiple(
    options = unique_cat.tolist(),
    value = ['VANDALISM', 'ASSAULT', 'ROBBERY'],
    description='Criminal Case',
    disabled=False,
    style=style,
    layout = Layout(width='50%', height='80px')
)

 

If you run the code cells above, you’ll get the following widget.
Next, we want to combine all of the three widgets that we’ve created before to create an interactive visualization. To visualize the crime locations, we can visualize them with a map, since we have the information regarding the latitude and longitude in the dataset.
To visualize the dataset into a map, we can use folium library. If you haven’t installed folium yet, you can install it using pip command.
pip install folium
We can integrate the map with the widgets such that when we make a different selection with the widgets, the visualization will adjust accordingly.
First, the value of the slider widget will determine how many crimes in the dataset that we should consider in the visualization. Next, the map should then show the crime categories and the districts based on our selection with the multiple selection widgets.
To create additional visualizations, we can also create two bar charts. One bar chart to show how many crimes are there based on the categories that we’ve selected using the widgets. The other chart is to show how many crimes are there in the district that we’ve selected using the widget.
Finally, we need to define a function to integrate all of the three widgets with our map visualization and the two bar charts.
Below is the complete code implementation to do all of that from start to finish.
Now if we call the function update_map in the last code cell of Jupyter Notebook above, we get the interactivity to our map and bar chart visualizations based on the value that we’ve selected in all of the three widgets.
Now we’re done with our job with Jupyter Notebook to create interactive visualizations with the help of ipywidgets library!
So far, we’ve created interactive visualizations with the help of ipywidgets , matplotlib , and folium library. As of right now, you can proceed to show the visualization in your Jupyter Notebook to other people.
However, in most cases, you’ll show the visualization to non-technical people, people who’re not interested to see the chunks of Python code in your notebook and just want to see a clean visualization. Hence, using Jupyter Notebook to show the interactive visualization wouldn’t be the best choice.
To transform the visualization on your Jupyter Notebook to a standalone dashboard, we can use Voila. Now if you haven’t installed Voila yet, you can install it using pip command as follows:
pip install voila
Once you’ve installed Voila, it’s going to be very easy to create a standalone dashboard. All you need to do is go to your terminal or Anaconda prompt, and then type the following format:
voila path/to/your/notebook.ipynb
Alternatively, you can do so directly in your notebook by clicking the Voila icon in your Jupyter Notebook toolbar.
Now if you did either of two steps above, you’ll get the following standalone dashboard.
And that’s it! We have transformed the visualizations in our Jupyter Notebook into a standalone dashboard. Now with the same trick you can transform your own visualization with any dataset in Jupyter Notebook to a standalone dashboard.
So far, the dashboard that you’ve built with Voila only runs locally in your local computer. It means that you can’t actually share it with other people, unless you lend your computer to them.
In order for other people to have access to your dashboard, you need to deploy your dashboard on the cloud, such as AWS, GCP, Azure, or Heroku. In this article, we’re going to use Heroku to deploy our dashboard such that other people can see your dashboard with their own computer.
The first step to deploy your dashboard with Heroku is by logging-in to your Heroku account. If you don’t have an account yet, you can sign up to Heroku for free.
The next step is to download and install Heroku command line interface (CLI) to your local machine.
After Heroku CLI installation, now you need to create two additional files beside your Jupyter notebook file. These files are:
requirements.txt: This text file should contain all of the dependencies or libraries that you used in your Jupyter Notebook. As an example, in this article we use folium , numpy , pandas , ipywidgets , matplotlib, and voila libraries. Hence, we need to list all of them in this file. As an addition, since we use Jupyter Notebook, we need to add ipykernel in this file such that Heroku can run the commands in our Jupyter Notebook. Below is what the content of requirements.txt looks like.
numpypandasfoliumipywidgetsmatplotlibvoilaipykernel
Procfile: This is the file that tells Heroku how and what files are necessary to run your Jupyter Notebook. You can type the following as the content of this file.
web: voila --port=$PORT --no-browser --enable_nbextensions=True your_jupyter_notebook_name.ipynb
You can create those two files with any text editor you have in your computer, for example Notepad or Notepad++. Next, save those files in the same folder where you save your Jupyter Notebook file.
Now open your terminal or command prompt, and then type heroku login in it. This will direct you to a browser page where you’re prompted to log-in with your Heroku account.
Next, go to the working directory where you save your Jupyter file, requirements.txt, and Procfile with your command prompt.
In the working directory, initialize an empty repository by typing git init. Next, you can create a new app on your Heroku account by typing the following format: heroku create your-app-name .
After creating your app, then proceed by typing the following commands in order:
git add .git commit -m "Your customized message"git push heroku master
Now after you typed git push heroku master , Heroku will start the process to create the app to host your dashboard. After a minute or so, you’ll get a link to your dashboard in the command prompt. The link will be similar with the name of your app.
And that’s it! Now you can share the link with other people so that they can see your interactive dashboard.
You can see the deployed dashboard for the visualizations in this article here.
In case you’re interested to see the Jupyter Notebook used in this article and requirements.txt as well as the Procfile, you can see it here.