Creating Bar Chart Race with less than 20 lines of code using bar_chart_race Python Package
When I came across the need for creating a bar chart race I ended up writing a lengthy code . I was wondering if we could have a python open source package to plot bar chart race and recently I found it here https://pypi.org/project/bar-chart-race/
This article intends to the demonstrate usage of package bar_chart_race by plotting bar chart race for monthly stock market prices of Apple Inc, Microsoft and Facebook for last 5 years.
Here’s a glimpse of what we are going to build:
Data
We are going to use the data for last five years monthly closing stock prices of Apple, Microsoft and Facebook.
Implementation
Implementation is quite simple and it involves below three steps
- Installing Package
- Reading Data
- Creating bar chart race
Installing Package
pip install bar_chart_race
Reading Data
import pandas as pd
import bar_chart_race as bcr # Importing the python library
df = pd.read_csv(‘data.csv’,index_col=’Date’) #Setting the date column as Index
print(df.head)
Creating bar chart race with horizontal orientation
bcr.bar_chart_race(df=df, filename=’stocks_horiz_desc.mp4',
orientation=’h’,# orientation='v' to create vertical bar chart race
sort=’desc’,
label_bars=True,
use_index=True,
steps_per_period=10,
period_length=400,
figsize=(7.5, 4.5),
cmap=’dark24',
title=’Stock Price Comparison for Apple Inc,Microsoft and Facebook’,
bar_label_size=7,
tick_label_size=7,
period_label_size=16,
fig=None)
Summary:
Here are some of the usage limitations of this package and they are also listed on the pypi.org website.
In my opinion this could be very useful library to start with bar chart race and surely can be used.
Must begin with a pandas DataFrame containing ‘wide’ data where:
Every row represents a single period of time
Each column holds the value for a particular category
The index contains the time component (optional)
References: