Staying calm in 2020 — part 3. Cooking is a lot like coding — i.e. if…
By: Julian Sara Joseph
Tags: Coding, Maps, Bar Chart, Cooking, Python

Yes, it is we have all tried our hands at baking cakes with EMO, making edible meals other than Maggi everyday to survive in this lockdown. What I realised though is that it is a lot like coding. You have to first make a plan, get all the ingredients, follow a recipe (with some buffer for improvisation based on what you have) and cook it within a stipulated time just like you would code for an interview ;) and then clear the mess you made in the kitchen like you would clear the memory after use in programming!

In fact, Grace Hopper used to tell women in 1990s the reverse— “Programming is just like planning a dinner”.

Lastly like coding can be therapeutic, cooking too is a perfect stress-buster!

No this is blog post is not on cooking, but on coding — what I picked up first. So follow along to make Bar charts and Maps — the final post in the Data visualisation series!

Please note we are focusing on coding it in Python with a few libraries in these series. (I assume you know which plot serves as eye-candy and which visualisations really get the message across, the intuition behind the choice of charts — I’ll try to write on that in detail in the next story.)

We have learned how to plot Line charts, and 3-D Scatter plots using COVID datasets from different sources. However, in order to get a chart depicting all the Confirmed, Recovered, Deceased cases for all states — instead of drawing line charts for individual columns of Confirmed cases, Recovered cases and Deceased cases, I could instead create a chart that tells the whole story in one go. (Step 2- Set a goal) [Remember the 5 steps mentioned in part 1]

Let’s use the exact same dataset we used in part-2 . The state wise dataset for India. (step 1- Get the data).

We can continue to use ‘Matplotlib’ and this time use ‘bar’ functions to make a stacked bar chart for our objective.(step 3- decide the library)

All of us know how bad the scene is in Maharashtra, and since its exhausting to see it everyday, I’m going to remove ‘Maharashtra’ and the ‘Total’ row as well. Then we will need three series for the three stacked bars. (Step 4- Transform the data)

states_latest = pd.read_csv('/content/datasets_549966_1296705_state_level_latest.csv') states_latest = states_latest[all_states_latest['State']!='Total']

#this Total row would be the longest 'bar' and confuse us while we #see the chart states_latest = states_latest[all_states_latest['State']!='Maharashtra']

#just because we are tired of seeing this in our news everyday

list_of_states=list(states_latest.iloc[:,0]) confirmed=states_latest.iloc[:,1].values recovered=states_latest.iloc[:,2].values deceased=states_latest.iloc[:,3].values

Now lets style our canvas, make it dark-themed and give it a beautiful background of slightly visible grid lines. Also add a title!

plt.figure(figsize=(25,10)) ax=plt.axes() ax.set_facecolor('black') ax.grid(linewidth=0.4, color='#8f8f8f')

ax.set_title('India State wise breakdown

',size=50,color='#28a9ff')

Now we can go on to design the minute details like the tick size and colours.

plt.xticks(rotation='vertical', size='20', color='white') plt.yticks(size='20',color='red') plt.tick_params(size=20,color='white')

We definitely have to label our axes.

ax.set_xlabel('

State',size=25, color='#4bb4f2') ax.set_ylabel('No. of cases

',size=25, color='#4bb4f2')

With all that set, lets go ahead and call our magic wand of plt.bar()

plt.bar(list_of_states, confirmed,label='confirmed', color='orange') plt.bar(list_of_states, recovered,label='recovered',color='blue') plt.bar(list_of_states, deceased,label='deceased',color='purple')

As you may have noticed, I like to label everything I can, so let’s annotate and add legends for the different colours we chose above. Orange, blue and purple. Do you know why I chose this instead of the standard ‘Red, Green and yellow’ — because there may be colour blind people who may be viewing your charts and see it as follows:

for i,j in zip(x,confirmed): ax.annotate(str(int(j)), xy=(i,j+3), color='white', size='15') plt.legend(['Confirmed','Recovered','Deceased'], fontsize=20)

Voila! we are done.

Since the chart doesn’t seem fully visible lets change the size of the canvas plt.figure(figsize =(45,13))

Zoomed out

Chloropleth Maps

(Know the intuition behind using them)

(Step 2)Our Goal is to see the confirmed cases as colours on a world map

Step 1: Get the data. We are using John Hopkins Dataset from https://github.com/CSSEGISandData/COVID-19, as it gets updated pretty frequently. You can download the latest one and use it as follows:

global_df = pd.read_csv('/content/drive/My Drive/code-along/time_series_covid19_confirmed_global.csv') global_df

Click to enlarge and see.

Step 3: We will be using `plotly` and its functions for this.

from plotly import graph_objects as go import plotly.express as px import pandas as pd import plotly.graph_objects as go

Step 4: Change the data

total_list = global_df.groupby('Country')['4/7/20'].sum().tolist() country_list = global_df["Country"].tolist() country_set = set(country_list) country_list = list(country_set) country_list.sort() new_df = pd.DataFrame(list(zip(country_list, total_list)), columns =['Country', 'Total_Cases'])

Step 5: Plot the Map

fig = go.Figure(data=go.Choropleth(

locationmode = "country names",

locations = new_df['Country'],

z = new_df['Total_Cases'],

text = new_df['Total_Cases'],

#colorscale=colors,

autocolorscale=True,

reversescale=True,

colorbar_title = 'Reported Covid-19 Cases', )) fig.update_layout(title_text='Reported Covid-19 Cases until July 4th, 2020', geo=dict(showcoastlines=True,),) fig.show()

You can of course uncomment then colourscale=colors and change “autocolorscale”=False and “reversescale”=False to add a list of colours you would want to see in the Map, maybe like this:

Go ahead and try out a palette of your own.