Analysing and Visualising the Country wise Population from 1955 to 2020 with Pandas, Matplotlib, Seaborn and Plotly | by Durgesh Samariya | Towards Data Science

On August 12, 2020, I started 100 Days of Data Science Challenge. The main goal of this challenge is to learn/code about data science for 1 hour daily for 100 days. I am planning to learn and code projects to improve my skills and getting hands-on experience. I am going to share my journey on GitHub, Instagram, and Medium. Don’t forget to follow me on social media.
For the first three days, I worked on a Country-wise population dataset available on Kaggle. Each day I answer a few questions using data analysis and visualization.
First thing first. Let’s import all the required libraries. For this project, Pandas, Matplotlib, Seaborn, and Plotly libraries are enough.
Let’s import them first.
# data analysisimport pandas as pd# data visualizationimport matplotlib.pyplot as pltimport seaborn as snsimport plotly.express as pxplt.style.use('fivethirtyeight')%matplotlib inline
I used fivethirtyeight plot style. Checkout more styles here.
Now let’s import data. You can download dataset from kaggle. After downloading data from kaggle, we have one csv file — Countries Population from 1995 to 2020.csv. So now let’s import data in dataframe.
# load datasetpopulation = pd.read_csv('./Countries Population from 1995 to 2020.csv')
About Dataset:
Year — Year detail in which population data is recordedCountry — Name of CountryPopulation — Population of Country in a given yearYearly % Change — Change in population since last year (in %)Yearly Change — Change in population since last yearMigrants — Number of migrantsMedian Age — Median age of the populationFertility Rate — Fertility rate (in %)Density (P/Km2) — Density of countryUrban Pop % — % of the population is living in an Urban areaUrban Population — Net population living in Urban areaCountry’s Share of World Pop % — Country’s share in Total World PopulationWorld Population — World PopulationCountry Global Rank — Global rank of country
Now let’s have a look at some example samples.
population.head() 
Its time to perform some data analysis.
Let’s have a look at shape of the data.
population.shape# output(4195, 14)
We have 4195 samples and 14 features.
Let’s check infomation of the dataset.
population.info()# output<class 'pandas.core.frame.DataFrame'>RangeIndex: 4195 entries, 0 to 4194Data columns (total 14 columns): #   Column                          Non-Null Count  Dtype  ---  ------                          --------------  -----   0   Year                            4195 non-null   int64   1   Country                         4195 non-null   object  2   Population                      4195 non-null   int64   3   Yearly % Change                 4195 non-null   float64 4   Yearly Change                   4195 non-null   int64   5   Migrants (net)                  3600 non-null   float64 6   Median Age                      3600 non-null   float64 7   Fertility Rate                  3600 non-null   float64 8   Density (P/Km2)                 4195 non-null   object  9   Urban Pop %                     4082 non-null   float64 10  Urban Population                4082 non-null   float64 11  Country's Share of World Pop %  4195 non-null   float64 12  World Population                4195 non-null   int64   13  Country Global Rank             4195 non-null   int64  dtypes: float64(7), int64(5), object(2)memory usage: 459.0+ KB
By looking at above output, I can say few things.
Country and Density (P/Km2) are object type. So I will change them in String and integer respectively.Density (P/Km2) have additional thousand comma in value. ex 1,111. So let remove that first.There are few missing values, but for now I will ignore them.
Country and Density (P/Km2) are object type. So I will change them in String and integer respectively.
Density (P/Km2) have additional thousand comma in value. ex 1,111. So let remove that first.
There are few missing values, but for now I will ignore them.
# remove extra symbolpopulation['Density (P/Km2)'] = population['Density (P/Km2)'].replace(',','')
Now let’s change the type of country and density value.
population['Density (P/Km2)'] = population['Density (P/Km2)'].astype(int)population['Country'] = population['Country'].astype(str)
Now let’s have a look at descriptive statistics.
population.describe()
# 2020 population datacurrent_population = population[population['Year'] == 2020][:30]plt.rcParams['figure.figsize'] = (25, 7)ax = sns.barplot(x = current_population['Country'][:30], y = current_population['Population'][:30], palette = 'dark')ax.set_xlabel(xlabel = 'Countries', fontsize = 10)ax.set_ylabel(ylabel = 'Population in Billion', fontsize = 10)ax.set_title(label = 'Population of top 30 countries in 2020', fontsize = 20)plt.xticks(rotation = 90)plt.show()
plt.figure(figsize=(9,25))ax = sns.barplot(x="Population", y="Country",                 data=current_population, palette="tab20c",                 linewidth = 1)for i,j in enumerate(current_population["Population"]):    ax.text(.5, i, j, weight="bold", color = 'black', fontsize =10)plt.title("Population of each country in 2020")ax.set_xlabel(xlabel = 'Population in Billion', fontsize = 10)ax.set_ylabel(ylabel = 'Countries', fontsize = 10)plt.show()
unique_countries = population['Country'].unique()plt.style.use("seaborn-talk")# set yearyear = 2020df_last_year = population[population['Year'] == year]series_last_year = df_last_year.groupby('Country')['Population'].sum().sort_values(ascending=False)labels = []values = []country_count = 10other_total = 0for country in series_last_year.index:    if country_count > 0:        labels.append(country)        values.append(series_last_year[country])        country_count -= 1    else:        other_total += series_last_year[country]labels.append("Other")values.append(other_total)wedge_dict = {    'edgecolor': 'black',    'linewidth': 2        }explode = (0, 0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0)plt.title(f"Total Share of in World's Population the top 10 countries in {year}")plt.pie(values, labels=labels, explode=explode, autopct='%1.2f%%', wedgeprops=wedge_dict)plt.show()
China have highest share in World Population followed by India.
population_top5_2020 = population[population['Year'] == 2020][:5]top_5_countries = population_top5_2020['Country'].unique()top5_popultion = population[population['Country'].isin(top_5_countries)][['Year', 'Country', 'Population']]top5_popultion_pivot = top5_popultion.pivot(index='Year', columns='Country', values='Population')top5_popultion_pivot.style.background_gradient(cmap='PuBu')# Please note, in medium I am unable show the gradient color. 
fig,ax = plt.subplots(figsize=(20, 10))sns.despine()sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2})sns.barplot(x="Year", y="Population", data=top5_popultion, hue='Country')ax.set_ylabel(ylabel = 'Population in Billion', fontsize = 10)ax.set_xlabel(xlabel = 'Year', fontsize = 10)ax.set_title('Top 5 most populated countries in the World')ax.legend();
population_2020 = population[population['Year'] == 2020]fig = px.choropleth(population_2020, locations="Country",                     locationmode='country names', color="Density (P/Km2)",                     hover_name="Country", range_color=[1,1000],                     color_continuous_scale="blues",                     title='Density of Countries in 2020')fig.update(layout_coloraxis_showscale=True)fig.show()
# highest dense country by populationpopulation_2020[population_2020['Density (P/Km2)']==population_2020['Density (P/Km2)'].max()][['Country','Density (P/Km2)']]
# lowest dense country by populationpopulation_2020[population_2020['Density (P/Km2)']==population_2020['Density (P/Km2)'].min()][['Country','Density (P/Km2)']]
# highly populated countrypopulation_2020[population_2020['Population']==population_2020['Population'].max()][['Country','Population']]
fig = px.choropleth(population_2020, locations="Country",                     locationmode='country names', color="Population",                     hover_name="Country",                    color_continuous_scale="dense",                     title='Population of Countries in 2020')fig.update(layout_coloraxis_showscale=True)fig.show()
population_more_than_one_million = population[(population['Population'] >= 1000000) & (population['Year']==2020)]number_of_countries = population_more_than_one_million.shape[0]print("There are {} countries in the world with more than 1 million population.".format(number_of_countries))## OutputThere are 159 countries in the world with more than 1 million population.
Let’s have look at the world map, where country population is more than 1 million.
fig = px.choropleth(population_more_than_one_million, locations="Country",                     locationmode='country names', color="Population",                     hover_name="Country",                    color_continuous_scale="blues",                     title='Countries with more than 1 million Population')fig.update(layout_coloraxis_showscale=True)fig.show()
population_more_than_one_billion = population[(population['Population'] >= 1000000000) & (population['Year']==2020)]number_of_countries = population_more_than_one_billion.shape[0]print("There are {} countries in the world with more than 1 Billion population.".format(number_of_countries))# outputThere are 2 countries in the world with more than 1 Billion population.
Let’s have look at the world map with countries more than 1 billion population.
fig = px.choropleth(population_more_than_one_billion, locations="Country",                     locationmode='country names', color="Population",                     hover_name="Country",                    color_continuous_scale="reds",                     title='Countries with more than 1 billion Population')fig.update(layout_coloraxis_showscale=True)fig.show()
There are only two countries China and India with more than 1 Billion population.
I hope this article was helpful to you. I tried to answer a few questions using data science. There are many more questions to ask. Now, I will move towards another dataset tomorrow. All the codes of data analysis and visuals can be found at this GitHub repository or Kaggle kernel.
Thanks for reading. I appreciate any feedback.
If you like my work and want to support me, I’d greatly appreciate it if you follow me on my social media channels:
The best way to support me is by following me on Medium.
Subscribe to my new YouTube channel.
Sign up on my email list.