DEV Community

Cover image for How to Make a Bar Chart Race With Python in 2 Minutes
Lorenzo Felletti
Lorenzo Felletti

Posted on • Originally published at Medium

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

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

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 to step 1)

mkdir my_bar_chart_race
Enter fullscreen mode Exit fullscreen mode

Then create a new virtual environment, and activate it

python3 -m venv venv
source venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

Step 1

If you haven’t already, install pandas

pip3 install pandas
Enter fullscreen mode Exit fullscreen mode

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

pip3 instll bar_chart_race
Enter fullscreen mode Exit fullscreen mode

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:
1_fF8ZmCdekNvNOqRSpmEMsw

The dataset

1_Ae6Xx-cugqR_oSVK0S4tBg (1)

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
Enter fullscreen mode Exit fullscreen mode

Load the dataset

df = pd.read_csv('./2020-championship.csv')
df = df.set_index('race')
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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.

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

Top comments (0)