Created
February 3, 2016 09:56
-
-
Save expersso/513c75b144ddb3217c14 to your computer and use it in GitHub Desktop.
Create a plot of changes in African fertility rates (1950-2015)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tools) | |
library(dplyr) | |
library(readxl) | |
library(ggplot2) | |
library(countrycode) | |
library(ggthemes) | |
# Function to download and open Excel files | |
get_data <- function(url, ...) { | |
tmp <- tempfile(fileext = paste0(".", file_ext(url))) | |
download.file(url, tmp, mode = "wb") | |
df <- read_excel(tmp, ...) | |
names(df) <- make.names(tolower(names(df))) | |
df | |
} | |
# Get fertility and population data | |
fertility_url <- paste0("http://www.un.org/en/development/desa/population/", | |
"publications/dataset/fertility/wfd2015/", | |
"UNPD_WFD_2015_FERTILITY.xlsx") | |
pop_url <- paste0("http://esa.un.org/unpd/wpp/DVD/Files/1_Indicators%20", | |
"(Standard)/EXCEL_FILES/1_Population/WPP2015_POP_F15_3_", | |
"ANNUAL_POPULATION_BY_AGE_FEMALE.XLS") | |
fertility <- get_data(fertility_url, sheet = "FERTILITY_INDICATORS", skip = 1) | |
pop <- get_data(pop_url, sheet = "ESTIMATES", skip = 16) | |
names(pop)[6] <- "year" | |
# Join together fertility and population data on country and year | |
df <- inner_join(fertility, select(pop, country.code, year, X0.4:X100.), | |
by = c("iso.code" = "country.code", | |
"yearstart" = "year")) | |
df$region <- countrycode(df$iso.code, "iso3n", "region") | |
plot <- df %>% | |
filter(agegroup == "[15-19]") %>% | |
filter(grepl("Africa", region)) %>% | |
ggplot(aes(x = timemid, y = datavalue, color = region, | |
weight = X15.19, size = X15.19)) + | |
geom_point(alpha = 0.15, show.legend = FALSE) + | |
geom_smooth(show.legend = FALSE) + | |
facet_wrap(~region, scales = "free") + | |
scale_color_few() + | |
theme_light(9) + | |
scale_x_continuous(limits = c(1950, NA)) + | |
scale_y_continuous(limits = c(0, 350)) + | |
labs(x = NULL, y = "# of births per 1,000 women\n", | |
title = "Total Fertility Rates (Women Aged 15-19)\n") | |
# Save as SVG for post-production in Inkscape | |
ggsave(plot, file = "fertility.svg", width = 4, height = 3) |
Author
expersso
commented
Feb 3, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment