import pandas as pd
import [Link] as plt
%matplotlib inline
#In Matplotlib, pyplot is used to create figures and change their
characteristics.
#The %matplotlib inline function allows for plots to be visible when
using Jupyter Notebook.
The Relation between – Matplotlib, PyPlot
• In Python, data visualizations can be done via many libraries. The most popular and
widely used of them all, and the one we’re discussing in project, is the Matplotlib library.
In fact, many of the other libraries utilize attributes of Matplotlib to display the plots they
generate.
• PyPlot is a module in Matplotlib which provides a MATLAB-like interface. MATLAB is
licensed software, whereas PyPlot is an open-source module that provides similar
functionality.
#Read the dataset
df = pd.read_csv('C:/Users/ipcs nagpur/Downloads/world-happiness-
[Link]')
[Link]()
Country name Regional indicator Ladder score \
0 Finland Western Europe 7.842
1 Denmark Western Europe 7.620
2 Switzerland Western Europe 7.571
3 Iceland Western Europe 7.554
4 Netherlands Western Europe 7.464
Standard error of ladder score upperwhisker lowerwhisker \
0 0.032 7.904 7.780
1 0.035 7.687 7.552
2 0.036 7.643 7.500
3 0.059 7.670 7.438
4 0.027 7.518 7.410
Logged GDP per capita Social support Healthy life expectancy \
0 10.775 0.954 72.0
1 10.933 0.954 72.7
2 11.117 0.942 74.4
3 10.878 0.983 73.0
4 10.932 0.942 72.4
Freedom to make life choices Generosity Perceptions of corruption
\
0 0.949 -0.098 0.186
1 0.946 0.030 0.179
2 0.919 0.025 0.292
3 0.955 0.160 0.673
4 0.913 0.175 0.338
Ladder score in Dystopia Explained by: Log GDP per capita \
0 2.43 1.446
1 2.43 1.502
2 2.43 1.566
3 2.43 1.482
4 2.43 1.501
Explained by: Social support Explained by: Healthy life expectancy
\
0 1.106 0.741
1 1.108 0.763
2 1.079 0.816
3 1.172 0.772
4 1.079 0.753
Explained by: Freedom to make life choices Explained by:
Generosity \
0 0.691
0.124
1 0.686
0.208
2 0.653
0.204
3 0.698
0.293
4 0.647
0.302
Explained by: Perceptions of corruption Dystopia + residual
0 0.481 3.253
1 0.485 2.868
2 0.413 2.839
3 0.170 2.967
4 0.384 2.798
#List all column names
for col_name in [Link]:
print(col_name)
Country name
Regional indicator
Ladder score
Standard error of ladder score
upperwhisker
lowerwhisker
Logged GDP per capita
Social support
Healthy life expectancy
Freedom to make life choices
Generosity
Perceptions of corruption
Ladder score in Dystopia
Explained by: Log GDP per capita
Explained by: Social support
Explained by: Healthy life expectancy
Explained by: Freedom to make life choices
Explained by: Generosity
Explained by: Perceptions of corruption
Dystopia + residual
Here, Ladder score is basically the happiness score, explained by six factors.
Dystopia is a hypothetical country that has values equal to the world’s lowest national averages
for each of the six factors.
Now, let’s move ahead with analyzing this dataset through Data Visualization using Matplotlib.
Line Graphs/Plots
#Create Series
expectancy = df['Healthy life expectancy']
score = df['Ladder score']
[Link](score, expectancy)
[<[Link].Line2D at 0x19614a12290>]
[Link](score, expectancy)
[Link]('Happiness Plot')
[Link]('Happiness Score')
[Link]('Age')
[Link](['Healthy Life Expectancy'])
[Link]()
#Add color, style, width to line element
[Link](score, expectancy, color = 'green', linestyle = '--',
linewidth=1.2)
[Link]('Happiness Plot')
[Link]('Happiness Score')
[Link]('Age')
[Link](['Healthy Life Expectancy'])
[Link]()
#Add color, style, width to line element
[Link](score, expectancy, color = 'red', linestyle = '-',
linewidth=1.2)
[Link]('Happiness Plot')
[Link]('Happiness Score')
[Link]('Age')
[Link](['Healthy Life Expectancy'])
[Link]()
#Add grid using grid() method
[Link](True)
[Link](score, expectancy)
[Link]('Happiness Plot')
[Link]('Happiness Score')
[Link]('Age')
[Link](['Healthy Life Expectancy'])
[Link]()
Making Multiple Plots in One Figure
Let’s compare the GDP and life expectancy of countries against their happiness score. For
comparison, we’ll need to plot ‘happiness score vs GDP’ and ‘happiness score vs life expectancy’
in a single figure.
#Create Series for GDP
gdp = df['Logged GDP per capita']
[Link](score, expectancy)
[Link](score, gdp)
[Link]('Happiness Score vs GDP and Life Expectancy')
[Link]('Happiness Score')
[Link](['Life Expectancy','GDP'])
[Link]()
From this graph, we can also visually identify a trend – both GDP per capita and life expectancy
have higher values than for countries with higher happiness scores.
If you want to display the plots in separate figures, use [Link]() after each plot statement as
shown below:
[Link](score, expectancy)
[Link]('Happiness Score vs Life Expectancy')
[Link]('Happiness Score')
[Link]()
[Link](score, gdp, color ='orange')
[Link]('Happiness Score vs GDP')
[Link]('Happiness Score')
[Link]()
Through these separate graphs, we can see that when there is a spike/dip for GDP per capita for
a given score, there is also a spike/dip for life expectancy for the same score.
Creating Subplots
We use [Link] to create a figure and a grid of subplots with a single call. For
example, for the previous scenario, we could create subplots using the following lines of codes:
#Creating two subplots
fig, axs = [Link](2)
[Link]('Vertically stacked subplots')
axs[0].plot(score, expectancy)
axs[1].plot(score, gdp, color = 'orange')
[<[Link].Line2D at 0x19622c67090>]
Figure Objects
The [Link] is a module in Matplotlib that provides the figure object, which contains all
the plot elements. This module controls the default spacing of the subplots.
[Link]() class is the top-level container for the plot elements. It returns the
figure instances.
[Link]() is used to create the empty figure object in Matplotlib. It has the following additional
parameters:
• figsize: Figure dimension (width, height) in inches
• dpi: Dots per inch
• facecolor: Figure patch facecolor
• edgecolor: Figure patch edge color
• linewidth: Linewidth of the frame
#Creating a figure object fig
fig=[Link](figsize=(10,4), facecolor ='green',
edgecolor='r',linewidth=5)
[Link](score, expectancy)
[Link]()
Bar Graphs/Plots
#Converting to int
HappinessScore = [Link](int)
#Counting the number of times each score occurs – the height of the
bars
count = HappinessScore.value_counts()
#Score of each count – X-axis
HapScore = [Link]
#Plotting the bar graph
[Link](HapScore, count)
[Link]('Happiness Score')
[Link]('Score')
[Link]('Count')
[Link]()
Histograms
[Link](score)
[Link]('Happiness Score Distribution')
[Link]('Happiness Score')
[Link]('Frequency')
[Link]()
Technically, the happiness score takes a continuous range of values, so we can get a general idea
of the score distribution through the above histogram. Though we can’t get exact data figures
just by looking at them.
Boxplots
A boxplot is used to display data distribution through quartiles. Quartiles (Q1, Q2, Q3, Q4) are
basically the division of data into four equal groups or intervals. A median separates the lower
half and upper half of the data.
The function used for the scatter plot is boxplot(). Used to detect outliers in data and how tightly
the data is grouped.
Let’s see if our Ladder score has any outlier data:
[Link](df['Ladder score'])
[Link]()
Hardly, there’s just one little circle outside the Minimum.
Scatter Plots
[Link](gdp, score)
[Link]('GDP vs Happiness Score')
[Link]('GDP per Capita')
[Link]('Happiness Score')
[Link]()
As expected, the higher the score for GDP per Capita, the higher is the happiness score of a
certain country.
Saving Plots
fig = [Link]()
[Link](gdp, score)
[Link]('GDP vs Happiness Score')
[Link]('GDP per Capita')
[Link]('Happiness Score')
[Link]('[Link]')
The image would have been saved with the filename ‘[Link]’.
To view the saved image, we’ll use the [Link] module, as shown below:
#Displaying the saved image
import [Link] as mpimg
image = [Link]("[Link]")
[Link](image)
[Link]()
Problem Statement
You are tasked with analyzing the World Happiness Report 2021 dataset to uncover insights into
global happiness levels. The dataset includes various factors such as GDP per capita, social
support, healthy life expectancy, freedom to make life choices, generosity, and perceptions of
corruption, all of which potentially influence the happiness scores (Ladder Score) of countries.
Your goal is to create visualizations that highlight the relationships and distributions of these
factors, and to identify which factors are most strongly associated with higher happiness scores.
PS1: How is the distribution of happiness scores (Ladder Score) across different regions?
PS2: What is the correlation between different factors in the dataset?
PS3: Which are the top 10 happiest countries according to the Ladder Score?
PS4: What is the relationship between GDP per capita and the happiness score?
PS5: How do various factors in the dataset relate to each other and to the happiness score?
import pandas as pd
import numpy as np
import [Link] as plt
import seaborn as sns
%matplotlib inline
import warnings
[Link]('ignore')
# Load the dataset
df = pd.read_csv('C:/Users/ipcs nagpur/Downloads/world-happiness-
[Link]')
[Link](10)
Country name Regional indicator Ladder score \
0 Finland Western Europe 7.842
1 Denmark Western Europe 7.620
2 Switzerland Western Europe 7.571
3 Iceland Western Europe 7.554
4 Netherlands Western Europe 7.464
5 Norway Western Europe 7.392
6 Sweden Western Europe 7.363
7 Luxembourg Western Europe 7.324
8 New Zealand North America and ANZ 7.277
9 Austria Western Europe 7.268
Standard error of ladder score upperwhisker lowerwhisker \
0 0.032 7.904 7.780
1 0.035 7.687 7.552
2 0.036 7.643 7.500
3 0.059 7.670 7.438
4 0.027 7.518 7.410
5 0.035 7.462 7.323
6 0.036 7.433 7.293
7 0.037 7.396 7.252
8 0.040 7.355 7.198
9 0.036 7.337 7.198
Logged GDP per capita Social support Healthy life expectancy \
0 10.775 0.954 72.0
1 10.933 0.954 72.7
2 11.117 0.942 74.4
3 10.878 0.983 73.0
4 10.932 0.942 72.4
5 11.053 0.954 73.3
6 10.867 0.934 72.7
7 11.647 0.908 72.6
8 10.643 0.948 73.4
9 10.906 0.934 73.3
Freedom to make life choices Generosity Perceptions of corruption
\
0 0.949 -0.098 0.186
1 0.946 0.030 0.179
2 0.919 0.025 0.292
3 0.955 0.160 0.673
4 0.913 0.175 0.338
5 0.960 0.093 0.270
6 0.945 0.086 0.237
7 0.907 -0.034 0.386
8 0.929 0.134 0.242
9 0.908 0.042 0.481
Ladder score in Dystopia Explained by: Log GDP per capita \
0 2.43 1.446
1 2.43 1.502
2 2.43 1.566
3 2.43 1.482
4 2.43 1.501
5 2.43 1.543
6 2.43 1.478
7 2.43 1.751
8 2.43 1.400
9 2.43 1.492
Explained by: Social support Explained by: Healthy life expectancy
\
0 1.106 0.741
1 1.108 0.763
2 1.079 0.816
3 1.172 0.772
4 1.079 0.753
5 1.108 0.782
6 1.062 0.763
7 1.003 0.760
8 1.094 0.785
9 1.062 0.782
Explained by: Freedom to make life choices Explained by:
Generosity \
0 0.691
0.124
1 0.686
0.208
2 0.653
0.204
3 0.698
0.293
4 0.647
0.302
5 0.703
0.249
6 0.685
0.244
7 0.639
0.166
8 0.665
0.276
9 0.640
0.215
Explained by: Perceptions of corruption Dystopia + residual
0 0.481 3.253
1 0.485 2.868
2 0.413 2.839
3 0.170 2.967
4 0.384 2.798
5 0.427 2.580
6 0.448 2.683
7 0.353 2.653
8 0.445 2.612
9 0.292 2.784
[Link]()
<class '[Link]'>
RangeIndex: 149 entries, 0 to 148
Data columns (total 20 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Country name 149 non-null
object
1 Regional indicator 149 non-null
object
2 Ladder score 149 non-null
float64
3 Standard error of ladder score 149 non-null
float64
4 upperwhisker 149 non-null
float64
5 lowerwhisker 149 non-null
float64
6 Logged GDP per capita 149 non-null
float64
7 Social support 149 non-null
float64
8 Healthy life expectancy 149 non-null
float64
9 Freedom to make life choices 149 non-null
float64
10 Generosity 149 non-null
float64
11 Perceptions of corruption 149 non-null
float64
12 Ladder score in Dystopia 149 non-null
float64
13 Explained by: Log GDP per capita 149 non-null
float64
14 Explained by: Social support 149 non-null
float64
15 Explained by: Healthy life expectancy 149 non-null
float64
16 Explained by: Freedom to make life choices 149 non-null
float64
17 Explained by: Generosity 149 non-null
float64
18 Explained by: Perceptions of corruption 149 non-null
float64
19 Dystopia + residual 149 non-null
float64
dtypes: float64(18), object(2)
memory usage: 23.4+ KB
[Link]().T
count mean
std \
Ladder score 149.0 5.532839
1.073924e+00
Standard error of ladder score 149.0 0.058752
2.200120e-02
upperwhisker 149.0 5.648007
1.054330e+00
lowerwhisker 149.0 5.417631
1.094879e+00
Logged GDP per capita 149.0 9.432208
1.158601e+00
Social support 149.0 0.814745
1.148890e-01
Healthy life expectancy 149.0 64.992799
6.762043e+00
Freedom to make life choices 149.0 0.791597
1.133318e-01
Generosity 149.0 -0.015134
1.506567e-01
Perceptions of corruption 149.0 0.727450
1.792263e-01
Ladder score in Dystopia 149.0 2.430000
5.347044e-15
Explained by: Log GDP per capita 149.0 0.977161
4.047399e-01
Explained by: Social support 149.0 0.793315
2.588713e-01
Explained by: Healthy life expectancy 149.0 0.520161
2.130191e-01
Explained by: Freedom to make life choices 149.0 0.498711
1.378884e-01
Explained by: Generosity 149.0 0.178047
9.827033e-02
Explained by: Perceptions of corruption 149.0 0.135141
1.143614e-01
Dystopia + residual 149.0 2.430329
5.376452e-01
min 25% 50%
75% \
Ladder score 2.523 4.852 5.534
6.255
Standard error of ladder score 0.026 0.043 0.054
0.070
upperwhisker 2.596 4.991 5.625
6.344
lowerwhisker 2.449 4.706 5.413
6.128
Logged GDP per capita 6.635 8.541 9.569
10.421
Social support 0.463 0.750 0.832
0.905
Healthy life expectancy 48.478 59.802 66.603
69.600
Freedom to make life choices 0.382 0.718 0.804
0.877
Generosity -0.288 -0.126 -0.036
0.079
Perceptions of corruption 0.082 0.667 0.781
0.845
Ladder score in Dystopia 2.430 2.430 2.430
2.430
Explained by: Log GDP per capita 0.000 0.666 1.025
1.323
Explained by: Social support 0.000 0.647 0.832
0.996
Explained by: Healthy life expectancy 0.000 0.357 0.571
0.665
Explained by: Freedom to make life choices 0.000 0.409 0.514
0.603
Explained by: Generosity 0.000 0.105 0.164
0.239
Explained by: Perceptions of corruption 0.000 0.060 0.101
0.174
Dystopia + residual 0.648 2.138 2.509
2.794
max
Ladder score 7.842
Standard error of ladder score 0.173
upperwhisker 7.904
lowerwhisker 7.780
Logged GDP per capita 11.647
Social support 0.983
Healthy life expectancy 76.953
Freedom to make life choices 0.970
Generosity 0.542
Perceptions of corruption 0.939
Ladder score in Dystopia 2.430
Explained by: Log GDP per capita 1.751
Explained by: Social support 1.172
Explained by: Healthy life expectancy 0.897
Explained by: Freedom to make life choices 0.716
Explained by: Generosity 0.541
Explained by: Perceptions of corruption 0.547
Dystopia + residual 3.482
Question1: How is the distribution of happiness scores (Ladder Score) across different regions?
Visualization 1: Distribution of Ladder Score by Region
# Set the style for the plots
[Link](style="whitegrid")
# Distribution of Ladder Score by Region
[Link](figsize=(12, 8))
[Link](x='Regional indicator', y='Ladder score', data=df)
[Link](rotation=90)
[Link]('Distribution of Ladder Score by Region')
[Link]('Region')
[Link]('Ladder Score')
[Link]()
Explanation:
• Purpose: To show the distribution of happiness scores across different regions.
• Visualization: A box plot that displays the spread of Ladder Scores within each region.
• Insight: This helps identify regions with higher or lower happiness scores and the
variation within each region.
Question2: What is the correlation between different factors in the dataset?
Visualization 2: Correlation Heatmap
the corr() method in pandas only works with numerical data, and your DataFrame contains
non-numeric columns. We need to select only the numeric columns before computing the
correlation matrix.
# Select only numeric columns for correlation
numeric_columns = [
'Ladder score',
'Standard error of ladder score',
'upperwhisker',
'lowerwhisker',
'Logged GDP per capita',
'Social support',
'Healthy life expectancy',
'Freedom to make life choices',
'Generosity',
'Perceptions of corruption',
'Ladder score in Dystopia',
'Explained by: Log GDP per capita',
'Explained by: Social support',
'Explained by: Healthy life expectancy',
'Explained by: Freedom to make life choices',
'Explained by: Generosity',
'Explained by: Perceptions of corruption',
'Dystopia + residual'
]
# Compute correlation matrix
correlation = df[numeric_columns].corr()
# Plot Correlation Heatmap
[Link](figsize=(14, 10))
[Link](correlation, annot=True, cmap='coolwarm', center=0)
[Link]('Correlation Heatmap of World Happiness Report 2021')
[Link]()
Explanation:
• Purpose: To display the correlation between different numerical variables in the dataset.
• Visualization: A heatmap where the color intensity indicates the strength of correlation.
• Insight: Identifies which factors are most strongly associated with the happiness score.
Question3:
Which are the top 10 happiest countries according to the Ladder Score?
Visualization 3: Bar Plot of Top 10 Happiest Countries
# Bar Plot of Top 10 Happiest Countries
top_10_happiest = [Link](10, 'Ladder score')
[Link](figsize=(12, 8))
[Link](x='Ladder score', y='Country name', data=top_10_happiest,
palette='viridis')
[Link]('Top 10 Happiest Countries')
[Link]('Ladder Score')
[Link]('Country')
[Link]()
Explanation:
• Purpose: To highlight the top 10 countries with the highest happiness scores.
• Visualization: A horizontal bar plot showing the Ladder Scores of the top 10 happiest
countries.
• Insight: Provides a quick comparison of the happiest countries in the dataset.
Question4: What is the relationship between GDP per capita and the happiness score?
Visualization 4: GDP per Capita vs. Ladder Score
# GDP per Capita vs. Ladder Score
[Link](figsize=(10, 6))
[Link](x='Logged GDP per capita', y='Ladder score', data=df,
hue='Regional indicator', palette='tab10', s=100)
[Link]('GDP per Capita vs. Ladder Score')
[Link]('Logged GDP per Capita')
[Link]('Ladder Score')
[Link](bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
[Link]()
The [Link] function can be used to adjust the positioning of the legend in a plot. Let's
break down its usage:
• bbox_to_anchor=(1.05, 1): This argument specifies the bounding box for the
legend. The coordinates (1.05, 1) place the legend slightly outside the plot area to the
right.
• loc=2: This locates the legend at the upper left corner of the bounding box specified by
bbox_to_anchor.
• borderaxespad=0.: This sets the padding between the axes and the legend box to
zero.
Explanation:
The legend is being positioned outside the main plotting area, to the right, to avoid overlapping
with the data points. This is particularly useful in scatter plots with many categories.
Explanation:
• Purpose: To show the relationship between GDP per capita and the happiness score.
• Visualization: A scatter plot where each point represents a country, color-coded by
region.
• Insight: Helps determine if wealthier countries tend to have higher happiness scores and
how this relationship varies by region.
Question5:
How do various factors in the dataset relate to each other and to the happiness score?
Visualization 5: Pair Plot to Explore Relationships
# Pair Plot to Explore Relationships
pair_columns = ['Logged GDP per capita', 'Social support', 'Healthy
life expectancy', 'Freedom to make life choices', 'Generosity',
'Perceptions of corruption', 'Ladder score']
[Link](df[pair_columns],diag_kind='kde',plot_kws={'alpha': 0.6})
[Link]('Pair Plot of Key Indicators and Ladder Score', y=1.02)
[Link]()
Explanation of above code: python [Link](df[pair_columns],
diag_kind='kde', plot_kws={'alpha': 0.6})
• [Link]: A function in Seaborn to create pair plots.
• df[pair_columns]: Selects only the specified columns from the DataFrame.
• diag_kind='kde': Specifies that the diagonal plots should be Kernel Density Estimate
(KDE) plots instead of histograms.
• plot_kws={'alpha': 0.6}: Keyword arguments for the individual plots. Here,
alpha=0.6 sets the transparency of the points in the scatter plots to 60%.
Add a Title to the Entire Plot: python [Link]('Pair Plot of Key
Indicators and Ladder Score', y=1.02)
• [Link]: Adds a centered title to the figure.
• y=1.02: Positions the title slightly above the top of the plot.
Explanation:
• Purpose: To visualize relationships and potential correlations between various factors
and the happiness score.
• Visualization: A matrix of scatter plots for each pair of variables, with KDE plots on the
diagonal.
• Insight: Provides a comprehensive view of how different factors are related to each other
and to the happiness score.
Conclusion:
These visualizations help in understanding the factors that influence happiness across different
countries and regions. They are designed to teach how to use matplotlib and seaborn to analyze
and visualize data effectively. Each visualization addresses a specific question, providing insights
into the dataset.
BY Pranjal Gajbhiye(AIE)
Happy Learning...