Adding interactivity with Voila
Table of contents
- What is Voila?
- Installation
- The
interact
function - Example of Voila Usage : Data Visualization Dashboard
- Running the dashboard
- Conclusion
Voila is a powerful tool that allows you to convert Jupyter notebooks into interactive web applications. With Voila, you can share your data analysis, visualizations, and machine learning models in a user-friendly web-based format. In this section, we’ll explore the concept of Voila and provide some examples to illustrate its capabilities.
What is Voila?
Voila is an open-source Python library that acts as a Jupyter notebook renderer. It takes your Jupyter notebook, executes the code cells, and displays the results in a web-based dashboard. This dashboard can include interactive widgets, plots, and text explanations, creating an interactive and user-friendly experience without the need for end-users to access or modify the underlying code.
Installation
You need to install the package voila
, this can be done on your terminal using :
conda install -c conda-forge voila
you might have to restart running jupyter lab instances.
The interact
function
The interact
function is a fundamental component of interactive computing in Jupyter notebooks, and it’s often used in conjunction with libraries like IPython widgets for creating interactive elements in Python code. Here’s an explanation of what interact
does:
-
Creates Interactive Widgets: The
interact
function allows you to create interactive widgets (user interface elements) in your Jupyter notebook. These widgets can take various forms, including sliders, dropdowns, text input boxes, and buttons. -
Associates Widgets with Functions: You associate these widgets with Python functions. When a user interacts with a widget, the associated function is automatically called with the widget’s current value as an argument.
-
Updates Output Dynamically: As the user interacts with the widgets, the output of the associated function is updated in real-time within the notebook. This can include plots, text, data tables, or any other content you want to display.
-
Enhances User Experience: Interactivity created using
interact
can greatly enhance the user experience when working with data, models, or any other computational tasks. Users can explore and manipulate data or models directly within the notebook.
Here’s a simple example to illustrate how interact
works:
from ipywidgets import interact
# Define a function that takes a number as input and squares it
def square(x):
return x * x
# Create an interactive widget (slider) that allows users to select a number
# When the user interacts with the slider, the square function is called, and the result is displayed.
interact(square, x=(0, 10))
In this example, interact
creates a slider widget with a range from 0 to 10. As the user moves the slider, the square
function is called with the current slider value (x
), and the result (the square of the value) is displayed below the widget.
This is just a basic example; you can create much more complex interactive interfaces using interact
and other IPython widgets.
Overall, interact
is a powerful tool for building interactive components in Jupyter notebooks, making it easier to engage with and explore data, models, and visualizations directly in your Python code.
Example of Voila Usage : Data Visualization Dashboard
Let’s reuse our Electrical power plant dataset and make it interactive !
First we load the libraries we need :
# Import necessary libraries
import pandas as pd
import matplotlib.pyplot as plt
# Create interactive widgets (e.g., dropdowns, sliders)
from ipywidgets import interact
Then, we format the data correctly, in df
:
df = pd.read_csv('ElectricityProductionPlant.csv')
df_MainCategory=pd.read_csv('MainCategoryCatalogue.csv',index_col='Catalogue_id')
df_SubCategory = pd.read_csv('SubCategoryCatalogue.csv',index_col='Catalogue_id')
df_PlantCategory = pd.read_csv('PlantCategoryCatalogue.csv',index_col='Catalogue_id')
df['PlantCategory']=df['PlantCategory'].fillna('Unknown')
newline ={'en': 'Unknown','fr' : 'Inconnu'}
df_PlantCategory.loc['Unknown']=newline
df['MainCategory'] = df_MainCategory.loc[df['MainCategory']]['en'].values
df['SubCategory'] = df_SubCategory.loc[df['SubCategory']]['en'].values
df['PlantCategory'] = df_PlantCategory.loc[df['PlantCategory']]['en'].values
then we want to plot the distribution of power for a given canton for that we will use :
df[df['Canton']==canton]['TotalPower'].plot(kind='hist', bins=100,log = True)
This command select a given Canton with the variable canton
and plot an histogram with a resolution of 100 bins. We use the log for the y axis for expressing the power.
In order to use this plot command with interact we include it in a function :
def plot_data(canton):
df[df['Canton']==canton]['TotalPower'].plot(kind='hist', bins=100,log = True, xlabel = 'Power (kw)',ylabel = 'Frequency (log)', title = f'Distribution of Electrical power for the {canton}')
We then need the list of canton, we can get it from the column Canton
of df
by removing the duplicates :
df['Canton'].unique()
---
array(['BL', 'AG', 'BE', 'ZH', 'SG', 'TI', 'FR', 'SO', 'NW', 'LU', 'TG',
'VS', 'VD', 'SH', 'JU', 'AR', 'AI', 'GE', 'GR', 'UR', 'ZG', 'OW',
'SZ', 'GL', 'NE', 'BS'], dtype=object)
so adding all this for interact()
gives :
interact(plot_data, canton=df['Canton'].unique())
Running the dashboard
It’s then possible to run your jupyter notebook as a dashboard without the code.
For that you have to start Voila :
- From your terminal :
voila <path-to-notebook>
- Or, in the url of your jupyter-lab :
<url-of-my-server>/voila
.
For example, if you typed jupyter-lab
and it was running at http://localhost:8888/lab
, then Voilà would be accessed at http://localhost:8888/voila
.
If you want to share this voila notebook with other you can consider different services, one free and well documented is called MyBinder
Conclusion
Voila is a powerful tool for converting Jupyter notebooks into interactive web applications. Whether you want to create data visualization dashboards, deploy machine learning models, or share interactive reports, Voila simplifies the process and makes your work accessible to a broader audience. Explore Voila’s capabilities to enhance the interactivity and usability of your Jupyter notebooks.