How to Create Bar Chart Race using Matplotlib in Python and using Flourish Studio ?
Matplotlib is an open source library
Photo by Pietro Mattia on Unsplash
Bar chart race is trending now as one of the trending visualization, by using Matplotlib we can create this chart, for non program Flourish Studio released race chart, that I will give brief introduction later.
Data on GST revenue by states which can be imported from this link
I was wondering how difficult it would be to create a Bar race chart in python using Matplotlib, but it turned out it was not that difficult at all.
Let’s Code
In your system please install all the dependent libraries
import matplotlib.ticker as tickerimport matplotlib.animation as animationfrom IPython.display import HTMLimport matplotlib.pyplot as pltimport pandas as pd
Importing the GST data.
df=pd.read_excel(‘xxxxx.xlsx’,sheet_name=’xxxx’)df.head()
Data Transformation
current_year = 2019dff = (df[df[‘year’].eq(current_year)].sort_values(by=’value’, ascending=True))dff
Creating the Basic chart
fig, ax = plt.subplots(figsize=(15, 8))ax.barh(dff[‘name’], dff[‘value’],color=’brown’)
fig, ax = plt.subplots(figsize=(15, 8))dff = dff[::-1] # flip values from top to bottom# pass colors values to ‘color=’ax.barh(dff[‘name’],dff[‘value’],color=’brown’)# iterate over the values to plot labels and valuesfor i, (value, name) in enumerate(zip(dff[‘value’], dff[‘name’])):ax.text(value, i, name, ha=’right’)# Add year right middle portion of canvasax.text(1, 0.4, current_year, transform=ax.transAxes, size=40, ha=’right’)
Now, we’re left with the beautification part of the chart.
We will beautify following thing:
- Updating the font size and color
- Adding Title
- Format: comma separated values and axes tickers
- Grid: Add lines behind bars
fig, ax = plt.subplots(figsize=(15, 8))def draw_barchart(year):dff = df[df[‘year’].eq(year)].sort_values(by=’value’, ascending=True)ax.clear()ax.barh(dff[‘name’], dff[‘value’],color=’brown’)dx = dff[‘value’].max() / 200for i, (value, name) in enumerate(zip(dff[‘value’], dff[‘name’])):ax.text(value-dx, i, name, size=14, weight=600, ha=’right’, va=’bottom’)# … polished stylesax.text(1, 0.4, year, transform=ax.transAxes, color=’red’, size=46, ha=’right’, weight=800)ax.text(0, 1.06, ‘revenue (cr)’, transform=ax.transAxes, size=12, color=’green’)ax.xaxis.set_major_formatter(ticker.StrMethodFormatter(‘{x:,.0f}’))ax.xaxis.set_ticks_position(‘top’)ax.tick_params(axis=’x’, colors=’red’, labelsize=12)ax.set_yticks([])ax.margins(0, 0.01)ax.grid(which=’major’, axis=’x’, linestyle=’-’)ax.set_axisbelow(True)ax.text(0, 1.12, ‘Total GST revenue state wise’,transform=ax.transAxes, size=24, weight=600, ha=’left’)ax.text(1, 0, ‘by @prabhat’, transform=ax.transAxes, ha=’right’,color=’blue’, bbox=dict(facecolor=’white’, alpha=0.8, edgecolor=’red’))plt.box(False)draw_barchart(2018)
Animations
Matplotlib’s animation base class deals with the animation part. It provides a framework around which the animation functionality is built. There are two main interfaces to achieve that using:
FuncAnimation makes an animation by repeatedly calling a function func.
ArtistAnimation: Animation using a fixed set of Artist objects.
However, out of the two, FuncAnimation is the most convenient one to use. You can read more about them in the documentation since we will only concern ourselves with the FuncAnimation tool.
fig, ax = plt.subplots(figsize=(15, 8))animator = animation.FuncAnimation(fig, draw_barchart, frames=range(2017, 2020))HTML(animator.to_jshtml())
And here is the desired output.
Bar chart race can be created using Flourish as well, this is basically for non programmers.
Photo by Anthony DELANOIX on Unsplash
Why use Flourish?
There are a lot of dedicated softwares available, Flourish comes with six preloaded templates for making interactive map visualizations. You can upload your data on the existing templates and can create the graph easily.
Flourish bar race features
- Set font and colours
- Images: circular or rectangular
- Interactive filters
- Sort by biggest or smallest bars
- Show a totalizer
- Fully mobile friendly
Conclusion
Python is a very strong programming language because of its libraries and one of them is Matplotlib for visualization. Although, creating a more customized chart can be time consuming and complex however anything is possible in python. On the other hand, Flourish is a user friendly data visualization platform to create powerful and interactive data stories.
I hope this article will help you and save a good amount of time.
HAPPY CODING.