Bar Chart Race & Choropleth Map of COVID-19 python | Towards Data Science

“Visualization gives you answers to questions you didn’t know you had” — Ben Schneiderman
In the era of data science, we must say data is beauty. We can not even think of a day without data. More or less modern technologies are dependent on the data-driven process. But only raw data doesn't make any charm to us until it is processed. When data is processed, we get information from it. Information may be visual, statistical, predictive, and so on. If we can aesthetically visualize data, we can easily get the insight into the data. It provides an overview of the data. Proper visualization makes a clear intuition of the whole scenario in the human brain.
“Most of us need to listen to the music to understand how beautiful it is. But often that’s how we present statistics: we just show the notes, we don’t play the music ” — Hans Rosling
And Hans Rosling indicated the actual thinking of data visualization. Data visualization is essential for each and every profession. In this article, we will try our best to represent the COVID-19 scenario, all over the world. At the same time, we will learn some interactive plotting techniques with python.
Python provides so many libraries which makes our life easy and beautiful. We will learn some interesting plotting techniques with the COVID-19 dataset.
When you go through the whole article you will be able to create animations as shown in the harder part of the article. No background knowledge is needed to read the article. It is nothing but a few lines of python code. Let me guide through.
Python provides us with the flexibility to use different libraries for different tasks. Here, we will use matplotlib and plotly libraries to have the visual output with bar chart race and choropleth map with the COVID-19 dataset.
Little bit data preprocessing for our desired plots.
Stylish bar chart race with COVID-19 dataset for Confirmed, Recovered, and Death cases.
Interactive choropleth map with COVID-19 dataset
Let’s move on to the next step...
Download the COVID-19 dataset from kaggle. The data is well organized and updated daily. I am using the dataset which is last updated on 25 April 2020.
Importing pandas for working with dataframe, numpy for different mathematical operation and matplotlib for our bar chart race.
import pandas as pdimport numpy as npimport matplotlib.ticker as tickerimport matplotlib.pyplot as plt
The dataset contains all the affected countries’ confirmed positive cases, death cases, and recovered cases of coronavirus. If we want to catch sight of the data, it will look like this.
covid = pd.read_csv('covid_19_data.csv')covid.head(5)
Now, we want to rename the columns because it will help us to manipulate the data more easily.
covid.rename(columns={'ObservationDate':'Date','Province/State':'State','Country/Region':'Country'},inplace=True)
From the first 5 rows of the dataset, we come to know that there are some redundant and unnecessary columns, we will leave the columns and keep only the necessary columns.
covid=covid[["Date","State","Country","Confirmed","Deaths","Recovered"]]
Our main target is to make a bar chart race based on the country, so we can group the country by date for finding out the total number of cases in a country.
grouped = covid.groupby(['Country','Date'])covid_confirmed = grouped.sum().reset_index().sort_values(['Date'],ascending=False)
We saved the output dataframe to covid_confirmed and it seems like below.
Finding out the top ten countries of coronavirus confirmed cases for plotting an initial bar chart. We are stepping down to the steps of the bar chart race.
df = (covid_confirmed[covid_confirmed['Date'].eq("04/25/2020")].sort_values(by="Confirmed",ascending=False).head(10))
Output
Making a Bar Chart Race with matplotlib of coronavirus spread
#plotting the initial horaizontal barchart fig, ax = plt.subplots(figsize=(15, 8))ax.barh(df['Country'], df['Confirmed'])plt.xlabel('Number of Confirmend Cases')plt.ylabel('Country')
This few lines of code will generate the following output with matplotlib.
But we want to have the highest confirmed case at the top. For this, we need to flip the dataframe.df[::-1] ,this piece of code will flip the dataframe df
dff=df[::-1]fig, ax = plt.subplots(figsize=(15, 8))ax.barh(dff['Country'], dff['Confirmed'])plt.xlabel('Number of Confirmed Cases')plt.ylabel('Country')
Wow! we are a few steps ahead of our desired output. The above bar chart does not seem too good. We need more information and visual color in the chart. For this, we can follow the following techniques
i.Color code each country with different colors
ii.Color code with a fixed number of colors
iii.Serially 10 different colors for the top ten affected countries.
I will show you each and every step.
Coding each country with individual colors with a dictionary.
colors holds a dictionary of country’s name as key and color code is the values for each country.
You can also use the following method.
colors = dict(zip(df_date_series.Country.unique(),['#adb0ff', '#ffb3ff', '#90d595', '#e48381', '#f7bb5f','#fb6b19','#1fb1fb'] * 31))
Just set 10 color codes for the 10 affected country
This method is used in the draw_barchartfunction shown in the function section.
color=["#980505","#CD1212","#D84E4E","#CB6262","#D39B5F","#F7EC10","#D0F710","#9CF710","#B4D67F","#969C8E"]
However, I am using the first method for the following bar chart.
Congratulations! we are at the very final step of our bar chart race with the COVID-19 dataset. we will create a function integrating with all of the above codes and some stylish.
“Bar Chart Race in Python with Matplotlib” article helped me a lot. For the better style of the bar chart. I am quoting some functionalities of the polish style from the article,
Text: Update font sizes, color, orientation
Axis: Move X-axis to top, add color & subtitle
Grid: Add lines behind bars
Format: comma-separated values and axes tickers
Add title, credits, gutter space
Remove: box frame, y-axis labels
We will use these things for the aesthetic design of our bar chart race.
Function
In the draw_barchart function, I have implemented the third color code option. I have set fixed colors for the top 10 affected countries with the list of 10 color codes.
For individual function call, the function will output like this for draw_barchart(“04/25/2020”).
Making an animation is our final goal, we are going to do this. Are you ready? Here is the code for your animation.
Now we have the following animation.
Instead of using HTML, you can also save the animation using animator.save() method. If you change the parameter case to Deaths or Recovered the animation will show the bar chart race of Deaths and Recovered.
Interactive and Animated Choropleth Map of coronavirus spread with Plotly
At the end of the part of this article, we will create an interactive choropleth map like the following animation.
We need not deal with any country where there are no confirmed corona cases. So, we will drop the rows where is no coronavirus confirmed cases.
modified_confirmed = covid_confirmed[covid_confirmed.Confirmed > 0]
For making an effective choropleth map, we must have a distinguishable number of coronavirus affected cases. Let’s have some intuition about the COVID-19 dataset with a kernel density plot.
The first plot shows that most of the countries' values are condensed to a point. But when we plot the values with log10 values, it shows more spread in nature. It indicates that if we use the original number of confirmed cases, we can not distinguish between the colors of the map. Because most of the countries will be plotted with similar types of colors. We must include the log10 value of our dataset for better results. Let's do it.
modified_confirmed['Affected_Factor'] = np.log10(modified_confirmed.Confirmed)
Now, our modified_confirmed dataset looks like this.
Yes! we have added a column named Affected_Factor to the dataframe based on the log10 value of Confirmed cases. And we are just one step ahead for our final interactive choropleth map.
About Plotly Library
The plotly Python library (plotly.py) is an interactive, open-source plotting library that supports over 40 unique chart types covering a wide range of statistical, financial, geographic, scientific, and 3-dimensional use-cases.
Installation
If you use an anaconda environment, you can install the library with the following conda command in the conda comment prompt.
conda install -c plotly plotly
You can also check the official website of anaconda for the installation process. For other environments, pip install can be used.
$ pip install plotly
Importing the Necessary modules
import plotly as pyimport plotly.express as px
We will plot the interactive choropleth maps using COVID-19 dataset with plotly.express module. Now we will write our final code for the interactive map.
We have passed some parameter into the plotly.express object px.
Here is a short description of the parameters.
Dataframe: I have reversed the dataframe modified_confirmed with [::-1]. Because the dataframe is sorted according to the recent to past date but we need to show the animation from the date when coronavirus started to affect people.
location parameter is set according to the Country column.
And all other parameters definition are embedded as comment in the code.
What does the Affected_Factor legend indicate in the plot?
The legend Affected_Factor maybe confusing though I have mentioned it in the preprocessing section. It is the log10 value of the confirmed cases. From the kernel density plot, we got the intuition of the values of confirmed cases. The number of confirmed cases in different countries is very close. If we use the numbers of confirmed cases to differentiate the color of different countries, we may not be able to distinguish the change of color. Most of the countries will be plotted with similar types of colors. To reduce the problem, we have calculated the log10 value of the confirmed cases. It is more distinguishable. The second kernel density plot also indicates the fact. You can also check it out by yourself.
Now, our interactive choropleth map is ready. The map provides information about the spread of COVID-19 in the whole world. The color of the map is getting changed with the increasing number of confirmed coronavirus cases with the passage of time. We can also find out all the information by hover over the mouse courser. The map also supports zooming in and out.
Data visualization is the best way to represent the overall condition of anything at a glance. Enrich libraries of python make it easy for us. We just need to know how to use it, how the function works. Official documentation can help you a lot in this regard.
If you want to get the full project, just reach out to the GitHub repository. You can also view the whole jupyter notebook from here.
Python supports so many visualization libraries. Among then matplotlib is the popular one and it is a huge library. You can also find other visualization libraries’ documentation like seaborn, geopandas, geopy, plotly etc. for more aesthetic plotting of data.
For any query, let me know in the comment section.
Thank you for spending the time to read the article.
[Note: Towards Data Science is a Medium publication primarily based on the study of data science and machine learning. We are not health professionals or epidemiologists, and the opinions of this article should not be interpreted as professional advice. To learn more about the coronavirus pandemic, you can click here.]