How To Make a Bar Chart Race With Python in 2 Minutes

How to create a cool bar chart race animation, the easiest way.

Lorenzo Felletti
Analytics Vidhya
2 min readFeb 1, 2021

--

Final result.

Prerequisites: having Python installed on your pc or being registered for Google Colaboratory.

Step 0

First, create a new directory for the project (if you use Google Colaboratory, skip this step)

mkdir my_bar_chart_race
cd my_bar_chart_race

Then, create and activate a new virtual environment

python3 -m venv venv
source venv/bin/activate

Step 1

If you haven’t already, install pandas

pip3 install pandas

Install the library we’ll use to create the bar chart race named, you won’t guess it, bar_chart_race

pip3 install bar_chart_race

Step 2

Now that we have the necessary libraries installed, let’s load our data.

In this tutorial, we’ll create a bar chart animation of the 2020 MotoGP World Championship’s title race. If you’re not familiar with this sport — that’s bad — don’t worry.
I will sum it up briefly for you to better understand what the data means.

How MotoGP works

MotoGP is the premier class of motorcycle road racing. A championship is held every year and consists of many races (or Grand Prix). After each Grand Prix, each rider gains some points depending on his final position at the GP. At the end of the season, the rider with the most point wins the championship.

The point system in use since 1993 is the following:

MotoGP point system

The dataset

The dataset has a row for each race where the first column reports the race, while the other columns are one for each rider showing his total points after that race.

You can find the dataset here.

Step 3

Now the cool part: coding!

Import the libraries

import pandas as pd
import bar_chart_race as bcr

Load the dataset

df = pd.read_csv('./2020-championship.csv')
df = df.set_index('race')

Let the magic happen

The final result is only one line of code away

bcr.bar_chart_race(
df=df,
title='2020 MotoGP Championship Race',
orientation='h',
sort='desc',
n_bars=10,
steps_per_period=40,
period_length=2000
)

Ok, we’ve done with the coding. You can save and run the program, and you will obtain as output the bar chart race video.

Done!

Congrats, you’ve finished. As easy as that.

Final result — video of the bar chart race.

That was just a short introduction to this library. You can unleash your imagination, creating much more advanced races with it.

--

--