How to Create a Drop-Down Menu and a Slide Bar for your Favorite Visualization Tool | by Khuyen Tran | Towards Data Science

Imagine we are analyzing the trend population of countries in the world from 1960 to 2018 to predict the population in the next coming years.
To visualize the trend of the country, we choose Plotly for its simple and beautiful visualization. Start with ‘Vietnam’
import pandas as pd import datapane as dp import plotly.express as pxdata = pd.read_csv('population.csv')fig = px.line(data.set_index('Countries').loc['Vietnam'],              labels={'index': 'Year', 'value': 'Population'},              title='Population Over Time',             )fig.show()
Then the United States
fig = px.line(data.set_index('Countries').loc['United States'],              labels={'index': 'Year', 'value': 'Population'},              title='Population Over Time',              )fig.show()
Seems like the curve is linearly increasing, but we are not sure if the curve is linear for every country, so we want to keep visualizing more countries. Is there a faster way to visualize these countries instead of changing the name of the country in df.loc['location']? Wouldn’t it be nice to have a drop-down menu to choose the country you want to visualize?
This could be easily done with a small add-on: Jupyter Widget.
Widgets are eventful python objects that can give control like a slider, textbox, etc. We can use widgets to build interactive GUIs for our notebooks.
Start with installation
With pip
pip install ipywidgetsjupyter nbextension enable --py widgetsnbextension
With conda
conda install -c conda-forge ipywidgets
Check out this link for further information about installation.
Import useful libraries
from ipywidgets import interact, interactive, fixed, interact_manualimport ipywidgets as widgets
Explore basic things we can do with interact. First, define a function that you want to explore. The following function returns x as the parameter x is changed.
def f(x):    return x
Create a slide bar by passing a tuple (min, max) to x
interact(f, x=(0.0,10.0))
Create a dropdown menu by passing a list of strings
interact(f, x=['love','hate'])
Based on this, maybe we can create a function for our plot that changes based on the country?
def f(country):    df.loc[country].iplot(                    xTitle='Year',                     yTitle='Population of {}'.format(country),                    title='Population Over Time'                     )
Represent countries with df.index
df.index
Create interact with one simple code.
interact(f, country=df.index)
Awesome! Seems like the population curves of some countries are linear. But we are also curious about how the distribution of populations in the world changes each year, could we create another function as a parameter? Absolutely!
Take the transpose of our previous graph and change country to year.
def f(year):    fig = px.line(data.set_index('Countries').T.loc[str(year)],              labels={'value':'Population in {}'.format(str(year))},              title= 'Population over time')    fig.show()    interact(f, year=list(data.T.index)[1:] )
If we prefer a slide bar, we could simply switch a list of years to a tuple (min year, max year)
interact(f, year=(1960, 2018))
That’s it! Now we could efficiently go through the distribution each year to see if the distribution has changed over time.
Congratulations! You have learned how to utilize Python Widgets to create a slide bar and drop-down menu for efficient visualization. I encourage you to try this out with any of your favorite visualization tools such as Matplotlib, Seaborn. Just a small twist in your code can save you a huge amount of time to invest in other important tasks of your data science projects.
Feel free to fork and play with the code for this article in this Github repo.
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these: