The purpose of this blog is to happily share my learning and ideas to help people, who actively seek solutions for the day-to-day problems faced.

Covid-19 - the race we don't want to win

Bar Chart

Bar chart race started to gain popularity recently and some of them went viral. Have you ever wondered how to create one, then this is the time, today we are going to see how we can make use of python to create one on our own with minimal lines of code

Covid-19

If there is one race in the world right now, which none of us want to win then it as to be covid-19. How many of us would have thought about this. Our lives are at stake and my heartfelt condolences for the life that left us in this crucial period. Hope we will find a cure soon until then please be responsible and keep proper social distancing.

covid-19 affected countries

So here is how I started to animate the total number of covid-19 affected cases across the  world

Libraries used

pandas - to read csv
matplotlib - to plot the graph and to animate
IPython - to display the animation as HTML

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.animation as animation
from IPython.display import HTML
view raw covid-19-1.py hosted with ❤ by GitHub

Dataset

Read the actual covid-19 affected countries dataset,

df = pd.read_csv('https://gist.githubusercontent.com/ravic499/73aee576217f7386d38212de3058a4a6/raw/278cd260c2372e56ca1509d5193fbbc5fedd7016/covid19.csv',
usecols=['Country','Date','Confirmed'])
df.head(5)
view raw covid-19-2.py hosted with ❤ by GitHub

Day wise

Plot the dataset on a given day,

current_day = "2020-05-23"
dff = (df[df['Date'].eq(current_day)].sort_values(by='Confirmed').head(5))
dff
view raw covid-19-3.py hosted with ❤ by GitHub

Draw Chart

Let's learn to draw a chart, if you see here we have used subplots to draw the chart with the help of figure and an axes, then we used barh to draw horizonal bar chart

fig, ax = plt.subplots(figsize=(15, 8))
ax.barh(dff['Country'], dff['Confirmed'])
view raw covid-19-4.py hosted with ❤ by GitHub

Styling

Here comes the aesthytic looks, we can make use of the supported options to alter,

  • Text: Font size, color and placement
  • Axis: Labels for x and y axis and its placement
  • Credits and Content: Title, content and credits

fig, ax = plt.subplots(figsize=(15, 8))
def draw_barchart(year):
dff = df[df['Date'].eq(year)].sort_values(by='Confirmed').tail(10)
ax.clear()
ax.barh(dff['Country'], dff['Confirmed'])
dx = dff['Confirmed'].max() / 200
for i, (value, name) in enumerate(zip(dff['Confirmed'], dff['Country'])):
ax.text(value-dx, i, name, size=14, weight=600, ha='right', va='bottom')
ax.text(value+dx, i, f'{value:,.0f}', size=14, ha='left', va='center')
ax.text(1, 0.4, year, transform=ax.transAxes, color='#777777', size=46, ha='right', weight=800)
ax.text(0, 1.06, 'Confirmed Cases (thousands)', transform=ax.transAxes, size=12, color='#777777')
ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}'))
ax.xaxis.set_ticks_position('top')
ax.tick_params(axis='x', colors='#777777', 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, 'The most affected countries in the world as on 2020-05-23',
transform=ax.transAxes, size=24, weight=600, ha='left')
ax.text(1, 0, 'by @ravic499; credit @pratapvardhan', transform=ax.transAxes, ha='right',
color='#777777', bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
plt.box(False)
draw_barchart("2020-05-23")
view raw covid-19-6.py hosted with ❤ by GitHub

So we are almost nearing the completion, only animation alone as to be made.

Animation

As we know, Animation/Videos are made up of series of pictures we are using the same logic here with the help of matplotlib.animation module, FuncAnimation is used to animate our barchart with draw_barchart function called continously for the last 130 days,

import matplotlib.animation as animation
from IPython.display import HTML
import datetime
date_list=[]
for i in range(0, 130):
date_list.append((datetime.date.today() - datetime.timedelta(i)).isoformat())
date_list=date_list[::-1]
fig, ax = plt.subplots(figsize=(15, 8))
animator = animation.FuncAnimation(fig, draw_barchart, frames=date_list)
HTML(animator.to_jshtml())
view raw covid-19-7.py hosted with ❤ by GitHub

Also I have used HTML from the IPython module to display our animated barchart as shown below,



Easy right ? then why to wait ? start to explore more and create a bar chart on your own

Inspired by : bar chart race in python 
Credits to: pratap vardhan

1 comment: