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.
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
Dataset
Read the actual covid-19 affected countries dataset,
Day wise
Plot the dataset on a given day,
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
Styling
Here comes the aesthytic looks, we can make use of the supported options to alter,
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
import matplotlib.pyplot as plt | |
import matplotlib.ticker as ticker | |
import matplotlib.animation as animation | |
from IPython.display import HTML |
Dataset
Read the actual covid-19 affected countries dataset,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
df = pd.read_csv('https://gist.githubusercontent.com/ravic499/73aee576217f7386d38212de3058a4a6/raw/278cd260c2372e56ca1509d5193fbbc5fedd7016/covid19.csv', | |
usecols=['Country','Date','Confirmed']) | |
df.head(5) |
Day wise
Plot the dataset on a given day,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
current_day = "2020-05-23" | |
dff = (df[df['Date'].eq(current_day)].sort_values(by='Confirmed').head(5)) | |
dff |
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fig, ax = plt.subplots(figsize=(15, 8)) | |
ax.barh(dff['Country'], dff['Confirmed']) |
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
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,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) |
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
Good One Ravi!
ReplyDelete