HW WEEK 6 2

Author

Andreas Sanches

GDP by World Bank Region

Open tidyverse and read the nations dataset

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.2     ✔ readr     2.1.4
✔ forcats   1.0.0     ✔ stringr   1.5.0
✔ ggplot2   3.4.3     ✔ tibble    3.2.1
✔ lubridate 1.9.2     ✔ tidyr     1.3.0
✔ purrr     1.0.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
setwd("/Users/andreassanches/Documents")
nations <- read_csv("nations.csv")
Rows: 5275 Columns: 10
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (5): iso2c, iso3c, country, region, income
dbl (5): year, gdp_percap, population, birth_rate, neonat_mortal_rate

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

Select the desirable variables and start sorting data

From this point, you start sorting things. Notice that I’m mutating 2 variables and dividing by a trillion to get the GDP of countries, and then we exclude all the “NA” values. Also, it’s important to group by “regions”, since our goal is to produce a streamgraph divided by regions.

regions_selected <- nations %>%
  select(gdp_percap, population, region, year) %>%
  group_by(region, year) %>%
  mutate(gdp_countries = gdp_percap * population / 1000000000000) %>%
  summarise(GDP = sum(gdp_countries, na.rm = TRUE))
`summarise()` has grouped output by 'region'. You can override using the
`.groups` argument.

Finally, create your visualization

Here, you label and define how your chart is going to look like. I added a thin white line around each regions through the “geom_area(color =”white”) code.

regions_selected_chart <- ggplot(regions_selected, aes(x = year, y = GDP, fill = region)) +
  labs(title = "GDP by World Bank Region") +
  geom_area(color = "white") +
  xlab("Year") +
  ylab("GDP ($ trillion)") +
  scale_fill_brewer(palette = "Set2")
regions_selected_chart