How to Create an Animated Bar Chart in Jupyter | Towards Data Science

Table of ContentsIntroduction1. Data preparation2. Animated Bar Chart3. A line chartConclusion
Every news outlet writes about economic hardships due to COVID-19. The fallout has disproportionally affected black communities.
The Federal Reserve Bank of St. Louis (FRED) updated its unemployment rate data. The observation range varies by data sets, but the latest data is from May 2020. We’re going to visualize how the unemployment rate changed by race and gender over the year using a Plotly animated bar chart on Jupyter.
This article assumes you are already familiar with the basic operation in JupyterLab/Jupyter Notebook.
Plotly installation
plotly.py may be installed using pip.
$ pip install plotly==4.8.1
for Conda users:
$ conda install -c plotly plotly=4.8.1
JupyterLab Support (Python 3.5+)
Using pip:
$ pip install jupyterlab "ipywidgets>=7.5"
for Conda users:
$ conda install jupyterlab "ipywidgets=7.5"
Then run the following (you need node installed):
# JupyterLab renderer support $ jupyter labextension install jupyterlab-plotly@4.8.1  # OPTIONAL: Jupyter widgets extension $ jupyter labextension install @jupyter-widgets/jupyterlab-manager plotlywidget@4.8.1
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
The above data are 20 Yrs. & Over (LNS14000024), 20 Yrs. & Over, White Men (LNS14000028), 20 Yrs. Over, White Women (LNS14000029), 20 Yrs. & Over, Black or African American Men (LNS14000031), 20 Yrs. & Over, Black or African American Women (LNS14000032)), 20 Yrs. & Over, Hispanic or Latino Men (LNS14000034), 20 Yrs. & Over, Hispanic or Latino Women (LNS14000032).
We’re going to concatenate all data sets, add a category column with appropriate names and filter by the date so that all data sets will have the same length as seen below.
import pandas as pdimport plotly.express as px over20='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/d1db4261b76af67dd67c00a400e373c175eab428/LNS14000024.csv'over20_white_men='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/d1db4261b76af67dd67c00a400e373c175eab428/LNS14000028.csv'over20_white_women='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/d1db4261b76af67dd67c00a400e373c175eab428/LNS14000029.csv'over20_black_men='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/7d63e7a7495dfb8578120016c7a7dd4edc04e20d/LNS14000031.csv'over20_black_women='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/d1db4261b76af67dd67c00a400e373c175eab428/LNS14000032.csv'over20_hispanic_men='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/f693c9bdd76875b12a14033cc54931da894bd341/LNU04000034.csv'over20_hispanic_women='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/f693c9bdd76875b12a14033cc54931da894bd341/LNU04000035.csv' df_over20 = pd.read_csv(over20)df_over20_wm = pd.read_csv(over20_white_men)df_over20_ww = pd.read_csv(over20_white_women)df_over20_bm = pd.read_csv(over20_black_men)df_over20_bw = pd.read_csv(over20_black_women)df_over20_hm = pd.read_csv(over20_hispanic_men)df_over20_hw = pd.read_csv(over20_hispanic_women) def prepare(dfs, datefrom):    result=[]    for item in dfs:        item.columns = ['date','rate','category']        item = item[item['date']>= datefrom]        result.append(item)    return result dfs = [df_over20, df_over20_wm, df_over20_ww, df_over20_bm, df_over20_bw, df_over20_hm, df_over20_hw]datefrom='2017-01-01'categories = ['Average', 'White men', 'White women', 'Black men', 'Black women','Hispanic men', 'Hispanic women'] i=0while i < len(categories):    dfs[i].loc[:,'category'] = categories[i]    i = i+1     df=prepare(dfs, datefrom)    df = pd.concat(df, ignore_index=True)display(df)
We import necessary libraries, Pandas and Plotly.express.
We create variables for each data using Github URLs.
We read all comma-separated values files (csv files) using read_csv.
We create a function called prepare. This function takes two parameters, dfs a list of DataFrames and datefrom a string of a date.
We create an empty list result. We iterate through the list of DataFrames to rename columns, filter date field using datefrom variable, and append each DataFrame to result.
We define a variable dfs using all DataFrames, datefrom and categories.
We add a new column using dfs and categories.
We use prepare function dfs and datefrom as arguments.
We combine all DataFrames using concat, with the ignore_index=True parameter. Each DataFrame has its own index and this allows us to ignore them and label index from 0, ..., n-1. The output of the df has the following structure.
The plotly.express module is plotly’s high-level API for rapid figure generation.
fig = px.bar(df, x="category", y="rate", color="category",   animation_frame="date", animation_group="category",    range_y=[0,20])fig.update_layout(    height=600,    title_text='Over 20 Unemployment Rate in USA from'+datefrom+' to May 2020')fig.show()
Every Plotly Express function returns a graph_objects.Figure object, and we instantiate it using plotly.express.bar. We set parameter, x, y, color, etc.
We use update_layout to set height and title, then display the animated bar chart.
The unemployment of Black or African American Men and Women is consistently around double rate and during some periods they are more than twice than White Men and Women. We see the sudden spikes for all data sets at the end but the difference of rates becomes smaller.
This chart below shows the unemployment rate from 1972–01–01 to 2020–05–01. We select five DataFrames and we change the datefrom value. If you want to create a line chart animation, please see this post.
df = pd.concat([df_over20, df_over20_wm, df_over20_ww, df_over20_bm, df_over20_bw], ignore_index=True)datefrom='1972-01-01'fig = px.line(df, x="date", y="rate", color="category",range_x=[datefrom,'2020-07-30'])# fig.update_layout(hovermode='x unified')fig.update_layout(    height=600,    title_text='Over 20 Unemployment Rate in USA from'+datefrom+' to May 2020')fig.show()
An animated bar chart is an excellent tool to show a dramatic unemployment rate change due to COVID-19. Pandas and Python make it easy to combine and modify the original data.
In the near future, I’d like to review this post to see how the rate of unemployment changes for different groups.
Get full access to every story on Medium by becoming a member.