-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRViz_Happiness.Rmd
551 lines (460 loc) · 19.8 KB
/
RViz_Happiness.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
---
title: "Happiness"
subtitle: "A Journey Around the Globe."
author: "Dustin Pacholleck & Adnan Sevinc"
date: "2023-01-15"
output:
ioslides_presentation:
widescreen: true
logo: img/wne_logo2017.png
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = FALSE,
message = FALSE,
warning = FALSE,
cache = FALSE
)
```
```{r settings_1, include=FALSE}
#install needed packages more easily with pacman
if (!require("pacman")) install.packages("pacman")
pacman::p_load( # Install or/and import libraries.
"ggplot2",
"tidyverse",
"dplyr",
"CGPfunctions",
"rnaturalearth",
"sf",
"ggrepel",
"ggthemes",
"gridExtra",
"cowplot",
"ggforce",
"GGally",
"Rmisc",
"grid",
"viridis",
"RColorBrewer",
"gganimate",
"gifski",
"wbstats",
"directlabels",
"reshape2",
"devtools",
"ggstance",
"patchwork",
"aplot",
"tidypaleo",
"gapminder",
"ggpmisc"
)
Sys.setlocale("LC_TIME", "English")
# Set the current path as directory
setwd(dirname(rstudioapi::getSourceEditorContext()$path))
# Import dataset
data <- read.csv("data/DataForTable2.1.csv")
# Create copy of dataset for future work
data_raw <- data %>%
select(-c(Negative.affect,Positive.affect,Confidence.in.national.government)) # Delete Columns
# Rename Columns
names(data_raw)<-c("Country",
"Year",
"HappinessScore",
"GDPPer",
"SocialSupport",
"LifeExpectancy",
"Freedom",
"Generosity",
"Corruption")
# Import additional stats from World Bank
# Define indicators
my_indicators <- c(
life_exp = "SP.DYN.LE00.IN",
gdp_capita ="NY.GDP.PCAP.CD",
pop = "SP.POP.TOTL"
)
# Query data
world_stats <- wb_data(my_indicators, start_date = min(data$year), end_date = max(data$year))
# Inspecting dataframe
data <- data[complete.cases(data),] #only complete dataset
nrow(data)
# Drop the below columns
data$Negative.affect<-NULL
data$Positive.affect<-NULL
data$Confidence.in.national.government<-NULL
#Rename Columns
names(data)
names(data)<-c("Country",
"Year",
"HappinessScore",
"GDPPer",
"SocialSupport",
"LifeExpectancy",
"Freedom",
"Generosity",
"Corruption")
# Complete dataset with missing years
countries <- unique(data$Country)
years <- unique(data$Year)
all <- data.frame(expand.grid(countries,years))
names(all) <- c("Country", "Year")
data <- left_join(all,data, by = c("Country"="Country", "Year" = "Year"))
data <- left_join(data,world_stats, by = c("Country"="country", "Year" = "date"))
world <- ne_countries(scale = "medium", returnclass = "sf")
data <- left_join(data, world[c("name","economy","continent", "subregion")], by = c("Country"="name"))
```
## Happiness Around the World {.flexbox .vcenter}
```{r Map World, echo=FALSE}
# Filter to 2021
data_2021 <- data %>%
mutate(HappinessScore = round(HappinessScore,2)) %>%
filter(Year == 2021)
# Join spacial data with dataset
data_world <- full_join(data_2021, world, by = c("Country"="name","economy","continent", "subregion","geometry"))
# Create base world plot
theme_set(theme_bw())
gworld_base <-
ggplot(data = data_world) +
coord_sf(expand = FALSE) +
geom_sf(aes(geometry = geometry, fill = HappinessScore)) +
scale_fill_gradient(low="red", high="green",na.value = "grey")
# Create World Plot
gworld <-
gworld_base +
theme(legend.position = 'bottom',
plot.title = element_text(size = 20, hjust = 0.5)) +
labs(title = "Happiness Worldwide in 2021",
caption = "Own creation. Data: World Happiness Report, World Bank")
gworld
```
## Distribution of Happiness {.flexbox .vcenter}
```{r Hist, echo=FALSE}
# Prep data
data_hist <- data %>%
drop_na(continent) %>% # Drop na from continent
select(c("continent", # Select specific Column
"Country",
"Year",
"HappinessScore",
"GDPPer",
"SocialSupport",
"LifeExpectancy",
"Freedom",
"Generosity",
"Corruption"))
# Generate plot
ggplot(data_hist %>% filter(continent != "Seven seas (open ocean)"), aes(x = HappinessScore, fill = continent)) + # Filter out Open seas.
geom_histogram(fill = "grey", alpha = .5) +
geom_histogram(colour = "black") +
facet_wrap(~ continent) + # separate by continent.
guides(fill = FALSE)+
labs(title = "Distribution of Happiness Score by Region",
x = "",
y = "",
caption = "Own creation. Data: World Happiness Report, World Bank")+
theme(plot.title = element_text(size = 15, hjust = 0.5))+
theme_stata() # Use stata theme
```
## Happiness Ranking {.flexbox .vcenter}
```{r BarPlot2, echo=FALSE}
# Prepare data
data_barplot_country <- data %>% # Mean Happiness Score by Country
select(c( "Country",
"HappinessScore"
)) %>%
drop_na(Country) %>% # Drop Na
group_by(Country) %>%
summarise_all(mean , na.rm = TRUE) # Summarise all column by mean
data_barplot_country_top10 <- data %>% #Top 10 countries in terms of Happiness score
select(c( "Country",
"HappinessScore",
)) %>%
drop_na(Country) %>%
group_by(Country) %>%
summarise_all(mean , na.rm = TRUE) %>%
top_n(10) %>% # First 10
mutate (Position = 'Top10') %>% # Flag as Top 10
arrange(desc(HappinessScore)) # Descending Order
data_barplot_country_bottom10 <- data %>% #Bottom 10 countries in terms of Happiness score
select(c( "Country",
"HappinessScore")) %>%
drop_na(Country) %>%
group_by(Country) %>%
summarise_all(mean , na.rm = TRUE) %>%
top_n(-10) %>% # Bottom 10
mutate (Position = 'Bottom10') %>% # Flag as Bottom 10
arrange(HappinessScore) # Ascending Descending Order
data_barplot_country_top_bottom_union <-
union_all(data_barplot_country_top10,data_barplot_country_bottom10) %>% # Union Top and Bottom 10 Countries
arrange(HappinessScore)
data_barplot_country_top_bottom_union = data %>% # Right Join in order to get Continent
select(continent,Country) %>%
unique() %>%
right_join(data_barplot_country_top_bottom_union, by ="Country")
data_barplot_country_top_bottom_union$HappinessScore <- round(data_barplot_country_top_bottom_union$HappinessScore,3) # Round Happiness Score
data_barplot_country_top_bottom_union$Country <- reorder(data_barplot_country_top_bottom_union$Country, data_barplot_country_top_bottom_union$HappinessScore) # Reorder Country
data_barplot_country_top_bottom_union$continent <- reorder(data_barplot_country_top_bottom_union$continent, data_barplot_country_top_bottom_union$HappinessScore) # Reorder Happiness Score
data_barplot_country_top_bottom_union[is.na(data_barplot_country_top_bottom_union$continent),"continent"] <- "Africa" # Missing Continet Africa fill out.
freq_table <- data_barplot_country_top_bottom_union %>% # Frequency Table of Top 10 in terms of Continent.
select(continent,Position) %>%
count() %>%
arrange(desc(Position), desc(freq))
names(freq_table)[3] = '# Countries' # Rename as # Countries
names(freq_table)[1] = 'Continent' # Renames as Continent
# Generate Plot
ggplot(data_barplot_country_top_bottom_union, aes(x = Country, y= HappinessScore, fill = Position)) +
geom_bar(stat='identity') +
coord_flip()+
labs(title = "Top and Bottom 10 Countries by Average Happiness",
y = 'Average Happiness Score',
x = NULL,
fill = '',
caption = "Own creation. Data: World Happiness Report, World Bank") +
theme_minimal() +
theme(legend.position = 'bottom',
plot.title = element_text(hjust = 0.5),
axis.text.x=element_blank(),
axis.ticks.x=element_blank()) +
geom_text(aes(label = HappinessScore), vjust = .2,hjust = -.1, position = position_dodge(.5),
size = 3) +
scale_fill_manual(values = c('grey78', 'khaki')) +
geom_hline(yintercept = mean(data$HappinessScore, na.rm = TRUE,show.legend = TRUE), linetype="dashed", color = "red") +
annotate(geom = 'table',
x=0,
y=12,
label=list(freq_table))
```
## Happiness in Europe {.flexbox .vcenter}
```{r Map Europe, echo=FALSE}
# Use world base plot for subplot
gworld_sub <-
gworld_base +
geom_rect(xmin = -30, xmax = 50, ymin = 35, ymax = 70, # Place rectange at Europe
fill = NA, colour = "black", size = 1.5) +
theme(legend.position= 'none',
axis.text = element_blank(),
axis.ticks=element_blank(),
)
# Create plot for Europe
geurope <- ggplot(data = data_world) +
coord_sf(expand = FALSE) +
geom_sf(aes(geometry = geometry, fill = HappinessScore)) +
annotate(geom = "text", x = 19, y = 52, label = "Poland", # Add Poland as text
fontface = "italic", color = "black", size = 4) +
scale_fill_gradient(low="red", high="green",na.value = "grey") +
coord_sf(xlim = c(-30, 50), ylim = c(35, 70), expand = TRUE) +
theme(legend.position = 'bottom',
plot.title = element_text(size = 20, hjust = 0.5)) +
labs(title = "Happiness Europe in 2021",
caption = "Own creation. Data: World Happiness Report, World Bank")
# Generate plot for Europe with world subplot
ggdraw() +
draw_plot(geurope,
0, 0, 1, 1) +
draw_plot(gworld_sub,
0.03, 0.25, 0.2, 0.2) # subplot in left corner
```
## Change of Happiness Ranking {.flexbox .vcenter}
```{r Happiness Ranking 2, echo=FALSE}
# Data prep
european_union <- c("Austria","Belgium","Bulgaria","Croatia","Cyprus", # List of European Countries.
"Czech Rep.","Denmark","Estonia","Finland","France",
"Germany","Greece","Hungary","Ireland","Italy","Latvia",
"Lithuania","Luxembourg","Malta","Netherlands","Poland",
"Portugal","Romania","Slovakia","Slovenia","Spain",
"Sweden","United Kingdom")
european_union_data <- # Extract Just European Countries
data_raw %>%
filter(Country %in% european_union)
european_union_data_top10 <- european_union_data %>% # Extract Top 10 European Countries
group_by(Country) %>%
summarise_all(mean) %>%
arrange(desc(HappinessScore)) %>%
head(10)
european_union_data_top10_PL <- european_union_data %>%
filter(Country %in% c(european_union_data_top10$Country , "Poland")) %>% # Filter date
filter(Year> 2009) %>%
filter(Year<= 2021)
data1 <- european_union_data_top10_PL
data1$Year <- as.character(data1$Year) # Year to character for newggslopegraph.
data1$HappinessScore <- round(data1$HappinessScore,2) # Round happiness to 2 decimal
# Generate Plot
newggslopegraph(data1, Year, HappinessScore, Country,
Title = "Top 10 European Countries & Poland's Happiness Score",
SubTitle = "2010-2021",
Caption = "Own creation. Data: World Happiness Report, World Bank",
DataLabelPadding = 0.2,
DataLabelLineSize = 0.5,
DataLabelFillColor = "lightblue")
```
## Drivers of Happiness {.flexbox .vcenter}
```{r Scatter plot, echo=FALSE}
# Data prep
data_Scatter <- data_raw %>%
mutate(PolandFlag = ifelse(Country == "Poland", "Poland", "Trend Line")) # Flag the Country whether is Poland or Others.
# Generate Plots
g1 <- ggplot(data_Scatter,aes(x = GDPPer, y = HappinessScore,color = PolandFlag)) +
geom_point(color = "#adaaaa")+
geom_smooth(alpha = 0.2) +
geom_rect(xmin = 9.977814, xmax = 10.4364, ymin = 5.646205, ymax = 6.242094, # To rectangle Poland
fill = NA, colour = "red", size = 1)+
scale_y_continuous(breaks = seq(0, 8, by = 0.5))+ # y scale start from 0 till 8 with 0.5 incremental
scale_x_continuous(breaks = seq(0, 12, by = 0.5),
labels = paste0('$', # Paste $ sign to x scale.
seq(0, 12, by = 0.5)))+
labs(title = '',
x = 'GDP Per capita' , y = 'HappinessScore')
g2 <- ggplot(data_Scatter,aes(x = SocialSupport, y = HappinessScore,color = PolandFlag)) +
geom_point(color = "#adaaaa") +
geom_rect(xmin = 0.8634442, xmax = 0.9550653, ymin = 5.646205, ymax = 6.242094,
fill = NA, colour = "red", size = 1)+
geom_smooth()+
scale_y_continuous(breaks = seq(0, 8, by = 0.5))+
scale_x_continuous(breaks = seq(0, 1, by = 0.1))+
labs(title = '',
x = 'Social Support' , y = 'HappinessScore')
g3 <- ggplot(data_Scatter,aes(x = LifeExpectancy, y = HappinessScore,color = PolandFlag)) +
geom_point(color = "#adaaaa") +
geom_smooth()+
geom_rect(xmin = 66.56, xmax = 69.05, ymin = 5.646205, ymax = 6.242094,
fill = NA, colour = "red", size = 1)+
scale_y_continuous(breaks = seq(0, 8, by = 0.5))+
scale_x_continuous(breaks = seq(10, 70, by = 10))+
labs(title = '',
x = 'Life Expectancy' , y = 'HappinessScore')
g4 <- ggplot(data_Scatter,aes(x = Freedom, y = HappinessScore,color = PolandFlag)) +
geom_point(color = "#adaaaa")+
geom_smooth()+
geom_rect(xmin = 0.7318056, xmax = 0.8828858, ymin = 5.646205, ymax = 6.242094,
fill = NA, colour = "red", size = 1)+
scale_y_continuous(breaks = seq(0, 8, by = 0.5))+
scale_x_continuous(breaks = seq(0, 1, by = 0.1))+
labs(title = '',
color = '',
x = 'Freedom' , y = 'HappinessScore')
g4 <- g4 + theme(legend.position = "bottom")
# Get legend from last plot
legend <- get_legend(g4)
# Title formatting
title <- textGrob("Correlation of Happiness Score",
gp = gpar(fontsize = 15, # font size
fontface = 2) # bold type
)
# Arrange plots
grid.arrange(arrangeGrob(g1 + theme(legend.position = "none"), #We use grid.arrange to display 4 graphs.
g2 + theme(legend.position = "none"),
g3 + theme(legend.position = "none"),
g4 + theme(legend.position = "none"),
ncol = 2),
legend,
nrow = 2,
top = title,
heights = c(10, 1)
)
```
<font size="1"> *Own creation. Data: World Happiness Report, World Bank* </font>
## Happiness and GDP {.flexbox .vcenter}
```{r Bubble plot, include=FALSE}
## Search for countries with biggest difference in score for highlighting
# focus <- unique(data$Country %>% filter(Year > 2010 & continent == 'Europe))
# inspect <- data_bubble[c("Country",
# "Year",
# "HappinessScore",
# "GDPPer",
# "SocialSupport",
# "LifeExpectancy",
# "Freedom",
# "Generosity",
# "Corruption")] %>%
# filter(Country %in% focus) %>%
# group_by(Country) %>%
# summarise_at(vars(HappinessScore),
# list(min = min, max=max)) %>%
# mutate(diff = max-min) %>%
# arrange(diff) %>%
# ungroup()
# Set focus countries
focus <- c("Poland", "Germany", "Ukraine", "Romania", "Bulgaria")
# Set up dataframe
data_bubble <- data %>%
filter(!is.na(data$HappinessScore) & Year > 2010 & continent == "Europe") %>%
mutate(mask= case_when(Country %in% focus ~ Country))
# produce animation
bubble <- ggplot(data_bubble, aes(gdp_capita, HappinessScore, size = pop, color = mask)) +
geom_point(data = subset(data_bubble, !is.na(mask)),
aes(gdp_capita, HappinessScore, size = pop, color = mask),
alpha = 0.8,show.legend = FALSE) + # Points in Focus
geom_point(data = subset(data_bubble, is.na(mask)),
aes(gdp_capita, HappinessScore, size = pop, color = mask),
alpha = 0.8,show.legend = FALSE) + # Points without Focus
scale_size(range = c(2, 12)) +
scale_x_log10() +
theme(plot.title = element_text(size = 20, hjust = 0.5)) +
labs(title = 'Happiness vs. GDP per Capita Over Time in {round(frame_time,0)}',
x = 'GDP per capita', y = 'Happiness',
caption = "Own creation. Data: World Happiness Report, World Bank") +
geom_text(data = subset(data_bubble, Country %in% focus), aes(label = Country), size = 2, color="black") +
# gganimate specific:
labs(title = 'Year: {frame_time}', x = 'GDP per Capita', y = 'Happiness') +
transition_time(as.integer(Year)) +
ease_aes('linear') +
shadow_wake(1, alpha = 0.2, exclude_layer = 2:3, size = 1, wrap = FALSE) # no wake for non focus countries and text
# Save as gif (commented to save runtime when knitting)
# gif <- animate(bubble,renderer = gifski_renderer(), end_pause=100, nframes = 200)
# anim_save("img/BubbleChart.gif",animation=gif)
```
![](img/BubbleChart.gif)
## Happiness and COVID {.flexbox .vcenter}
```{r line plot, echo=FALSE}
# Data prep
data_line <- data %>%
group_by(Year, continent) %>%
summarise_at(vars(HappinessScore),
list(HappinessScore = mean), na.rm = TRUE) %>% # Get mean by continent per year
ungroup()
data_line2 <- data %>%
group_by(Year) %>%
summarise_at(vars(HappinessScore),
list(HappinessScore = mean), na.rm = TRUE) %>% # Get global mean by year
ungroup()
data_line2 <- data_line2 %>% add_column("Country"="World") # Add column Country for unioning
names(data_line) <- c("Year",
"Country",
"HappinessScore") # Unify naming
# Union data
data_line <- union_all(data_line, data_line2)
data_line <- union_all(data_line, filter(data[c("Year", "Country","HappinessScore")], Country == "Poland"))
# Generate Plot
ggplot(filter(data_line, Country %in% c("World","Europe","Poland") & Year >= 2010),aes(Year,HappinessScore, group = Country, color = Country)) +
geom_rect(aes(xmin = 2019, ymin = -Inf,
xmax = Inf, ymax = Inf),
alpha = .4, fill = "grey", color = NA # Highlight COVID time with rectangle
) +
geom_line(size = 1.2) +
geom_point() +
geom_vline(xintercept = 2019,color = "black", size = 2) + # Add vertical line to separate pre and post COVID
geom_dl(aes(label = Country), method = list(dl.combine("last.points"), vjust = 1, hjust=0.5, cex = 1)) +
annotate("text", x = 2019, y = 7, label = "COVID-19", vjust = 2, hjust=-0.1, size = 5) + # Add text for COVID
theme(legend.position = 'bottom',
plot.title = element_text(size = 20, hjust = 0.5)) +
labs(color = NULL,
title = "Happiness Under COVID-19",
caption = "Own creation. Data: World Happiness Report, World Bank") +
scale_color_manual(values = c('#003399', '#D22630', 'black')) # Change colours to European blue and Polish red
```
## Fin.{.flexbox .vcenter}
![](img/Happy.png)
## Appendix
## Appendix 1 - Happiness Distribution by Continent {.flexbox .vcenter}
```{r Boxplot, echo=FALSE}
ggplot(data = filter(data, !is.na(data$continent)),
aes(y = HappinessScore, x = continent)) +
geom_boxplot() +
stat_summary(geom = 'point', shape = 15, fun = mean, size = 2) +
labs(title = "Happiness Compared by Continent",
x = "",
caption = "Own creation. Data: World Happiness Report, World Bank") +
theme(legend.position = 'bottom',
plot.title = element_text(size = 20, hjust = 0.5))
```