How to Create an Interactive Dropdown in Jupyter | by Shinichi Okada | Towards Data Science

Table of ContentsIntroduction1. Libraries2. Data Setup for the Dropdown3. Multiple Plot Function4. Interactive Dropdown Menu5. All the Code6. Using for Other DatasetsConclusion
In the last article, I wrote about how to create a bubble map using Plotly.express and Mapbox. The bubble map can show all the data with different sizes on a map.
In this article, I am going to write about an interactive graph using a dropdown menu.
When you have a series of datasets and want to separate one dataset from others, this method is useful.
I am using CSSEGISandData’s COVID-19 Github repo for this article.
import pandas as pdimport numpy as npimport plotly.graph_objects as go
pandas is a fast, powerful, flexible, and easy to use open-source data analysis and manipulation tool. Numpy is the fundamental package for scientific computing with Python. Plotly is an interactive, open-source Python graphing library.
Let’s start preparing our dataset. We are going to use the time-series data and you can find the raw data here.
Create a variable confirmed_global , and store the data into covid19_confirmed using Panda’s read_csv. We set the index column to Country/Region and display the dataframe.
# confirmed_globalconfirmed_global='https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv'covid19_confirmed=pd.read_csv(confirmed_global,index_col='Country/Region')display(covid19_confirmed)
There are 266 rows. This has Country/Region in index and Lat , Long, and dates on the label.
We are going to extract the latest date from the dataframe. We transpose the dataset, covid19_confirmed (Fig 1), using T and display the last 5 rows. Pandas’ transpose reflects the DataFrame over its main diagonal by writing rows as columns and vice-versa.
display(covid19_confirmed.T.tail())
The transposed dataframe has dates in the index and country names in the label.
We find the latest date at the end of the index column. We can use index.values[-1] to extract the latest date.
confirmed_latest = covid19_confirmed.T.index.values[-1]display(confirmed_latest)
Output: ‘6/9/20’
There are multiple rows that have the same Country/Region.
We can find 8 rows with Australia in fig 3, above.
We group them together by Country/Region and calculate the sum.
df_grouped_conf=covid19_confirmed.groupby('Country/Region').sum()display(df_grouped_conf.head(10))
Here are the first 10 rows.
Before we had 266 rows and now we have 142 rows. Australia has one row.
The df_grouped_conf (Fig 4) has the latest date (6/9/20 for this case) at the end.
We are going to sort the dataframe by this value, confirmed_latest with using ascending=False. We select the top 10 countries using head(10) and drop Lat and Long columns. We transpose the dataframe using T at the end.
df_confirmed=df_grouped_conf.sort_values(confirmed_latest,ascending=False).head(10).drop(['Lat', 'Long'],axis=1).T
towardsdatascience.com
towardsdatascience.com
We can find out other Plotly dropdown examples here.
We create a function called multi_plot. This requires two variables:
df: dataframe with countries as columns and rows as date
addAll: boolean. True display ALL in the dropdown button. ALL displays all countries at once. We set the default True.
We create a plotly.graph_objects’s Figure instance.
We use a for loop to iterate county names obtained by df.columns.to_list().
df.columns.to_list() returns a list, [‘US’, ‘Brazil’, ‘Russia’, ...].
In the iteration, we add a trace to the figure. You can use plotly.graph_objects.Scatter or plotly.graph_objects.Bar for the trace, and we are going to use Scatter.
We define the x, y, and name. The name parameter sets a trace name. The trace name appears as the legend item and on hover.
def multi_plot(df, title, addAll = True):    fig = go.Figure()    for column in df.columns.to_list():        fig.add_trace(            go.Scatter(                x = df.index,                y = df[column],                name = column            )        )    // continue
We define a dictionary button_all and function create_layout_button, which are used in update_layout. update_layout updates the properties of the figure’s layout and returns the Figure object.
In fig.update_layout() method, we use updatemenus, which is a tuple of plotly.graph_objects.layout.Updatemenu instance.
We also set yaxis_type="log" to show the logarithmic scale on the y-axis and height to 400px.
    // continue     button_all = dict(label = 'All',                      method = 'update',                      args = [{'visible':             df.columns.isin(df.columns),                               'title': 'All',                               'showlegend':True}])    def create_layout_button(column):        return dict(label = column,                    method = 'update',                    args = [{'visible': df.columns.isin([column]),                             'title': column,                             'showlegend': True}])    fig.update_layout(        updatemenus=[go.layout.Updatemenu(            active = 0,            buttons = ([button_all] * addAll) +  list(df.columns.map(lambda column: create_layout_button(column)))            )        ],         yaxis_type="log"           )    # Update remaining layout properties    fig.update_layout(        title_text=title,        height=800            )           fig.show()
The final part is using this multi_plot function.
multi_plot(df_confirmed, title="Logarithmic COVID-19 time series total confirmed by country")
The CSSEGISandData’s COVID-19 Github repo has two more datasets. You can use the same code to create other graphs.
You can see it live here.
https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv
https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv
You may find Plotly has too many parameters and sometimes confusing. But sample codes provide various examples, which you can use for your data science project.
Get full access to every story on Medium by becoming a member.